file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
pragma solidity ^0.4.13;
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;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract 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]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
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);
}
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);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public 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, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
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, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract TokenVault is Ownable {
/**
* @dev whether or not this vault is open and the tokens are available for withdrawal
*/
bool public open = false;
address public beneficiary;
modifier isOpen() {
require(open);
_;
}
modifier onlyBeneficiary() {
require(msg.sender == beneficiary);
_;
}
function TokenVault(address _beneficiary)
public
{
beneficiary = _beneficiary;
}
/**
* @dev opens the vault, allowing the Tokens to be withdrawn,
* @dev only callable by the owner (crowdsale)
*/
function open()
onlyOwner
external
{
open = true;
}
/**
* @dev withdraw all tokens to the caller
*/
function withdraw(StandardToken _token)
isOpen
onlyBeneficiary
external
{
require(_token.transfer(msg.sender, _token.balanceOf(address(this))));
}
function approve(
address _beneficiary,
StandardToken _token,
uint256 _value
)
onlyOwner
public
{
require(_token.approve(_beneficiary, _value));
}
} | opens the vault, allowing the Tokens to be withdrawn, only callable by the owner (crowdsale)/ | function open()
onlyOwner
external
{
open = true;
}
| 11,800,484 |
pragma solidity ^0.4.24;
// produced by the Solididy File Flattener (c) David Appleton 2018
// contact : [email protected]
// released under Apache 2.0 licence
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an address access to this role
*/
function add(Role storage role, address addr)
internal
{
role.bearer[addr] = true;
}
/**
* @dev remove an address' access to this role
*/
function remove(Role storage role, address addr)
internal
{
role.bearer[addr] = false;
}
/**
* @dev check if an address has this role
* // reverts
*/
function check(Role storage role, address addr)
view
internal
{
require(has(role, addr));
}
/**
* @dev check if an address has this role
* @return bool
*/
function has(Role storage role, address addr)
view
internal
returns (bool)
{
return role.bearer[addr];
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address addr, string roleName);
event RoleRemoved(address addr, string roleName);
/**
* @dev reverts if addr does not have role
* @param addr address
* @param roleName the name of the role
* // reverts
*/
function checkRole(address addr, string roleName)
view
public
{
roles[roleName].check(addr);
}
/**
* @dev determine if addr has role
* @param addr address
* @param roleName the name of the role
* @return bool
*/
function hasRole(address addr, string roleName)
view
public
returns (bool)
{
return roles[roleName].has(addr);
}
/**
* @dev add a role to an address
* @param addr address
* @param roleName the name of the role
*/
function addRole(address addr, string roleName)
internal
{
roles[roleName].add(addr);
emit RoleAdded(addr, roleName);
}
/**
* @dev remove a role from an address
* @param addr address
* @param roleName the name of the role
*/
function removeRole(address addr, string roleName)
internal
{
roles[roleName].remove(addr);
emit RoleRemoved(addr, roleName);
}
/**
* @dev modifier to scope access to a single role (uses msg.sender as addr)
* @param roleName the name of the role
* // reverts
*/
modifier onlyRole(string roleName)
{
checkRole(msg.sender, roleName);
_;
}
/**
* @dev modifier to scope access to a set of roles (uses msg.sender as addr)
* @param roleNames the names of the roles to scope access to
* // reverts
*
* @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this
* see: https://github.com/ethereum/solidity/issues/2467
*/
// modifier onlyRoles(string[] roleNames) {
// bool hasAnyRole = false;
// for (uint8 i = 0; i < roleNames.length; i++) {
// if (hasRole(msg.sender, roleNames[i])) {
// hasAnyRole = true;
// break;
// }
// }
// require(hasAnyRole);
// _;
// }
}
contract Whitelist is Ownable, RBAC {
event WhitelistedAddressAdded(address addr);
event WhitelistedAddressRemoved(address addr);
string public constant ROLE_WHITELISTED = "whitelist";
/**
* @dev Throws if called by any account that's not whitelisted.
*/
modifier onlyWhitelisted() {
checkRole(msg.sender, ROLE_WHITELISTED);
_;
}
/**
* @dev add an address to the whitelist
* @param addr address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address addr)
onlyOwner
public
{
addRole(addr, ROLE_WHITELISTED);
emit WhitelistedAddressAdded(addr);
}
/**
* @dev getter to determine if address is in whitelist
*/
function whitelist(address addr)
public
view
returns (bool)
{
return hasRole(addr, ROLE_WHITELISTED);
}
/**
* @dev add addresses to the whitelist
* @param addrs addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addAddressesToWhitelist(address[] addrs)
onlyOwner
public
{
for (uint256 i = 0; i < addrs.length; i++) {
addAddressToWhitelist(addrs[i]);
}
}
/**
* @dev remove an address from the whitelist
* @param addr address
* @return true if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeAddressFromWhitelist(address addr)
onlyOwner
public
{
removeRole(addr, ROLE_WHITELISTED);
emit WhitelistedAddressRemoved(addr);
}
/**
* @dev remove addresses from the whitelist
* @param addrs addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeAddressesFromWhitelist(address[] addrs)
onlyOwner
public
{
for (uint256 i = 0; i < addrs.length; i++) {
removeAddressFromWhitelist(addrs[i]);
}
}
}
contract StartersProxy is Whitelist{
using SafeMath for uint256;
uint256 public TX_PER_SIGNER_LIMIT = 5; //limit of metatx per signer
uint256 public META_BET = 1 finney; //wei, equal to 0.001 ETH
uint256 public DEBT_INCREASING_FACTOR = 3; //increasing factor (times) applied on the bet
struct Record {
uint256 nonce;
uint256 debt;
}
mapping(address => Record) signersBacklog;
event Received (address indexed sender, uint value);
event Forwarded (address signer, address destination, uint value, bytes data);
function() public payable {
emit Received(msg.sender, msg.value);
}
constructor(address[] _senders) public {
addAddressToWhitelist(msg.sender);
addAddressesToWhitelist(_senders);
}
function forwardPlay(address signer, address destination, bytes data, bytes32 hash, bytes signature) onlyWhitelisted public {
require(signersBacklog[signer].nonce < TX_PER_SIGNER_LIMIT, "Signer has reached the tx limit");
signersBacklog[signer].nonce++;
//we increase the personal debt here
//it grows much (much) faster than the actual bet to compensate sender's and proxy's expenses
uint256 debtIncrease = META_BET.mul(DEBT_INCREASING_FACTOR);
signersBacklog[signer].debt = signersBacklog[signer].debt.add(debtIncrease);
forward(signer, destination, META_BET, data, hash, signature);
}
function forwardWin(address signer, address destination, bytes data, bytes32 hash, bytes signature) onlyWhitelisted public {
require(signersBacklog[signer].nonce > 0, 'Hm, no meta plays for this signer');
forward(signer, destination, 0, data, hash, signature);
}
function forward(address signer, address destination, uint256 value, bytes data, bytes32 hash, bytes signature) internal {
require(recoverSigner(hash, signature) == signer);
//execute the transaction with all the given parameters
require(executeCall(destination, value, data));
emit Forwarded(signer, destination, value, data);
}
//borrowed from OpenZeppelin's ESDA stuff:
//https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/cryptography/ECDSA.sol
function recoverSigner(bytes32 _hash, bytes _signature) onlyWhitelisted public view returns (address){
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
require (_signature.length == 65);
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := byte(0, mload(add(_signature, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
require(v == 27 || v == 28);
return ecrecover(keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)
), v, r, s);
}
// this originally was copied from GnosisSafe
// https://github.com/gnosis/gnosis-safe-contracts/blob/master/contracts/GnosisSafe.sol
function executeCall(address to, uint256 value, bytes data) internal returns (bool success) {
assembly {
success := call(gas, to, value, add(data, 0x20), mload(data), 0, 0)
}
}
function payDebt(address signer) public payable{
require(signersBacklog[signer].nonce > 0, "Provided address has no debt");
require(signersBacklog[signer].debt >= msg.value, "Address's debt is less than payed amount");
signersBacklog[signer].debt = signersBacklog[signer].debt.sub(msg.value);
}
function debt(address signer) public view returns (uint256) {
return signersBacklog[signer].debt;
}
function gamesLeft(address signer) public view returns (uint256) {
return TX_PER_SIGNER_LIMIT.sub(signersBacklog[signer].nonce);
}
function withdraw(uint256 amountWei) onlyWhitelisted public {
msg.sender.transfer(amountWei);
}
function setMetaBet(uint256 _newMetaBet) onlyWhitelisted public {
META_BET = _newMetaBet;
}
function setTxLimit(uint256 _newTxLimit) onlyWhitelisted public {
TX_PER_SIGNER_LIMIT = _newTxLimit;
}
function setDebtIncreasingFactor(uint256 _newFactor) onlyWhitelisted public {
DEBT_INCREASING_FACTOR = _newFactor;
}
} | remove an address from the whitelist addr address return true if the address was removed from the whitelist, false if the address wasn't in the whitelist in the first place/ | function removeAddressFromWhitelist(address addr)
onlyOwner
public
{
removeRole(addr, ROLE_WHITELISTED);
emit WhitelistedAddressRemoved(addr);
}
| 278,080 |
./partial_match/8453/0x6Dbb7C61eD0E1DE7833f21Ce7B6DBd9d03F16aAC/sources/TARDIGRADE.sol | YOU CAN SET HERE THE BUY FEES YOU CAN SET HERE THE SELL FEES SET MARKETING AND DEV ADDRESS exclude from paying fees or having max transaction amount | constructor() ERC20("TARD", "TARD") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0xfCD3842f85ed87ba2889b4D35893403796e67FF1
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 3;
uint256 _buyLiquidityFee = 1;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 3;
uint256 _sellLiquidityFee = 1;
uint256 _sellDevFee = 0;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 16,780,500 |
./partial_match/1/0xd99E77D485368D0365Ca124f94c7580f844d9bE5/sources/SimpleBreeding.sol | Owner or operator can cancel sales auction for kitty owned by contract/ | function cancelSaleAuction(uint256 _kittyId) external onlyOwnerOrOperator {
saleAuction.cancelAuction(_kittyId);
}
| 9,407,939 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
//
interface IERC20 {
function TOTALSUPPLY726() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF629(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER594(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE637(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE448(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM690(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER907(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL108(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
//
library SafeMath {
function ADD13(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB204(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB204(a, b, "SafeMath: subtraction overflow");
}
function SUB204(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 MUL742(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 DIV441(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV441(a, b, "SafeMath: division by zero");
}
function DIV441(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 MOD892(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD892(a, b, "SafeMath: modulo by zero");
}
function MOD892(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
//
library Address {
function ISCONTRACT801(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 SENDVALUE836(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 FUNCTIONCALL845(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL845(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL845(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE585(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE855(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE855(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE855(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 _FUNCTIONCALLWITHVALUE585(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE585(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT801(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 SAFETRANSFER962(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN910(token, abi.encodeWithSelector(token.TRANSFER594.selector, to, value));
}
function SAFETRANSFERFROM908(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN910(token, abi.encodeWithSelector(token.TRANSFERFROM690.selector, from, to, value));
}
function SAFEAPPROVE801(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.ALLOWANCE637(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN910(token, abi.encodeWithSelector(token.APPROVE448.selector, spender, value));
}
function SAFEINCREASEALLOWANCE164(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE637(address(this), spender).ADD13(value);
_CALLOPTIONALRETURN910(token, abi.encodeWithSelector(token.APPROVE448.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE822(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE637(address(this), spender).SUB204(value, "SafeERC20: decreased allowance below zero");
_CALLOPTIONALRETURN910(token, abi.encodeWithSelector(token.APPROVE448.selector, spender, newAllowance));
}
function _CALLOPTIONALRETURN910(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).FUNCTIONCALL845(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 TokenTimelock {
using SafeERC20 for IERC20;
// ERC20 basic token contract being held
IERC20 private _token;
// beneficiary of tokens after they are released
address private _beneficiary;
// timestamp when token release is enabled
uint256 private _releaseTime;
constructor (IERC20 token, address beneficiary, uint256 releaseTime) public {
// solhint-disable-next-line not-rely-on-time
require(releaseTime > block.timestamp, "TokenTimelock: release time is before current time");
_token = token;
_beneficiary = beneficiary;
_releaseTime = releaseTime;
}
function TOKEN557() public view returns (IERC20) { //inject NONSTANDARD NAMING
return _token;
}
function BENEFICIARY333() public view returns (address) { //inject NONSTANDARD NAMING
return _beneficiary;
}
function RELEASETIME746() public view returns (uint256) { //inject NONSTANDARD NAMING
return _releaseTime;
}
function RELEASE742() public virtual { //inject NONSTANDARD NAMING
// solhint-disable-next-line not-rely-on-time
require(block.timestamp >= _releaseTime, "TokenTimelock: current time is before release time");
uint256 amount = _token.BALANCEOF629(address(this));
require(amount > 0, "TokenTimelock: no tokens to release");
_token.SAFETRANSFER962(_beneficiary, amount);
}
}
//
contract Stage2Lock is TokenTimelock {
constructor (address _honey, address _beneficiary, uint256 _releaseTime) public
TokenTimelock(IERC20(_honey), _beneficiary, _releaseTime) {
}
} | inject NONSTANDARD NAMING | function SAFETRANSFER962(IERC20 token, address to, uint256 value) internal { | 15,830,441 |
pragma solidity 0.6.12;
import "./ERC20.sol";
import "../interfaces/IMisoToken.sol";
// ---------------------------------------------------------------------
//
// From the MISO Token Factory
//
// Made for Sushi.com
//
// Enjoy. (c) Chef Gonpachi 2021
// <https://github.com/chefgonpachi/MISO/>
//
// ---------------------------------------------------------------------
// SPDX-License-Identifier: GPL-3.0
// ---------------------------------------------------------------------
contract FixedToken is ERC20, IMisoToken {
/// @notice Miso template id for the token factory.
/// @dev For different token types, this must be incremented.
uint256 public constant override tokenTemplate = 1;
/// @dev First set the token variables. This can only be done once
function initToken(string memory _name, string memory _symbol, address _owner, uint256 _initialSupply) public {
_initERC20(_name, _symbol);
_mint(msg.sender, _initialSupply);
}
function init(bytes calldata _data) external override payable {}
function initToken(
bytes calldata _data
) public override {
(string memory _name,
string memory _symbol,
address _owner,
uint256 _initialSupply) = abi.decode(_data, (string, string, address, uint256));
initToken(_name,_symbol,_owner,_initialSupply);
}
/**
* @dev Generates init data for Farm Factory
* @param _name - Token name
* @param _symbol - Token symbol
* @param _owner - Contract owner
* @param _initialSupply Amount of tokens minted on creation
*/
function getInitData(
string calldata _name,
string calldata _symbol,
address _owner,
uint256 _initialSupply
)
external
pure
returns (bytes memory _data)
{
return abi.encode(_name, _symbol, _owner, _initialSupply);
}
}
pragma solidity 0.6.12;
import "../OpenZeppelin/GSN/Context.sol";
import "../OpenZeppelin/math/SafeMath.sol";
import "../interfaces/IERC20.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 IERC20, Context {
using SafeMath for uint256;
bytes32 public DOMAIN_SEPARATOR;
mapping (address => uint256) private _balances;
mapping(address => uint256) public nonces;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
bool private _initialized;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function _initERC20(string memory name_, string memory symbol_) internal {
require(!_initialized, "ERC20: token has already been initialized!");
_name = name_;
_symbol = symbol_;
_decimals = 18;
uint256 chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(abi.encode(keccak256("EIP712Domain(uint256 chainId,address verifyingContract)"), chainId, address(this)));
_initialized = true;
}
/**
* @dev Returns the name of the token.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view 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 {_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 override 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 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;
}
// See https://eips.ethereum.org/EIPS/eip-191
string private constant EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA = "\x19\x01";
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @notice Approves `value` from `owner_` to be spend by `spender`.
/// @param owner_ Address of the owner.
/// @param spender The address of the spender that gets approved to draw from `owner_`.
/// @param value The maximum collective amount that `spender` can draw.
/// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds).
function permit(
address owner_,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(owner_ != address(0), "ERC20: Owner cannot be 0");
require(block.timestamp < deadline, "ERC20: Expired");
bytes32 digest =
keccak256(
abi.encodePacked(
EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA,
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress == owner_, "ERC20: Invalid Signature");
_approve(owner_, spender, value);
}
/**
* @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 returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
pragma solidity 0.6.12;
interface IMisoToken {
function init(bytes calldata data) external payable;
function initToken( bytes calldata data ) external;
function tokenTemplate() external view returns (uint256);
}
pragma solidity 0.6.12;
import "../utils/Context.sol";
pragma solidity 0.6.12;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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;
}
}
pragma solidity 0.6.12;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
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;
}
} | Miso template id for the token factory. For different token types, this must be incremented. First set the token variables. This can only be done once | function initToken(string memory _name, string memory _symbol, address _owner, uint256 _initialSupply) public {
_initERC20(_name, _symbol);
_mint(msg.sender, _initialSupply);
}
| 41,522 |
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.10;
import {IFollowNFT} from '../interfaces/IFollowNFT.sol';
import {IFollowModule} from '../interfaces/IFollowModule.sol';
import {ILensHub} from '../interfaces/ILensHub.sol';
import {Errors} from '../libraries/Errors.sol';
import {Events} from '../libraries/Events.sol';
import {DataTypes} from '../libraries/DataTypes.sol';
import {LensNFTBase} from './base/LensNFTBase.sol';
import {IERC721Metadata} from '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
/**
* @title FollowNFT
* @author Lens Protocol
*
* @notice This contract is the NFT that is minted upon following a given profile. It is cloned upon first follow for a
* given profile, and includes built-in governance power and delegation mechanisms.
*
* NOTE: This contract assumes total NFT supply for this follow NFT will never exceed 2^128 - 1
*/
contract FollowNFT is LensNFTBase, IFollowNFT {
struct Snapshot {
uint128 blockNumber;
uint128 value;
}
address public immutable HUB;
bytes32 internal constant DELEGATE_BY_SIG_TYPEHASH =
0xb8f190a57772800093f4e2b186099eb4f1df0ed7f5e2791e89a4a07678e0aeff;
// keccak256(
// 'DelegateBySig(address delegator,address delegatee,uint256 nonce,uint256 deadline)'
// );
mapping(address => mapping(uint256 => Snapshot)) internal _snapshots;
mapping(address => address) internal _delegates;
mapping(address => uint256) internal _snapshotCount;
mapping(uint256 => Snapshot) internal _delSupplySnapshots;
uint256 internal _delSupplySnapshotCount;
uint256 internal _profileId;
uint256 internal _tokenIdCounter;
bool private _initialized;
// We create the FollowNFT with the pre-computed HUB address before deploying the hub.
constructor(address hub) {
HUB = hub;
}
/// @inheritdoc IFollowNFT
function initialize(
uint256 profileId,
string calldata name,
string calldata symbol
) external override {
if (_initialized) revert Errors.Initialized();
_initialized = true;
_profileId = profileId;
super._initialize(name, symbol);
emit Events.FollowNFTInitialized(profileId, block.timestamp);
}
/// @inheritdoc IFollowNFT
function mint(address to) external override {
if (msg.sender != HUB) revert Errors.NotHub();
uint256 tokenId = ++_tokenIdCounter;
_mint(to, tokenId);
}
/// @inheritdoc IFollowNFT
function delegate(address delegatee) external override {
_delegate(msg.sender, delegatee);
}
/// @inheritdoc IFollowNFT
function delegateBySig(
address delegator,
address delegatee,
DataTypes.EIP712Signature calldata sig
) external override {
_validateRecoveredAddress(
_calculateDigest(
keccak256(
abi.encode(
DELEGATE_BY_SIG_TYPEHASH,
delegator,
delegatee,
sigNonces[delegator]++,
sig.deadline
)
)
),
delegator,
sig
);
_delegate(delegator, delegatee);
}
/// @inheritdoc IFollowNFT
function getPowerByBlockNumber(address user, uint256 blockNumber)
external
view
override
returns (uint256)
{
if (blockNumber > block.number) revert Errors.BlockNumberInvalid();
uint256 snapshotCount = _snapshotCount[user];
if (snapshotCount == 0) {
return 0; // Returning zero since this means the user never delegated and has no power
}
uint256 lower = 0;
uint256 upper = snapshotCount - 1;
// First check most recent balance
if (_snapshots[user][upper].blockNumber <= blockNumber) {
return _snapshots[user][upper].value;
}
// Next check implicit zero balance
if (_snapshots[user][lower].blockNumber > blockNumber) {
return 0;
}
while (upper > lower) {
uint256 center = upper - (upper - lower) / 2;
Snapshot memory snapshot = _snapshots[user][center];
if (snapshot.blockNumber == blockNumber) {
return snapshot.value;
} else if (snapshot.blockNumber < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return _snapshots[user][lower].value;
}
/// @inheritdoc IFollowNFT
function getDelegatedSupplyByBlockNumber(uint256 blockNumber)
external
view
override
returns (uint256)
{
if (blockNumber > block.number) revert Errors.BlockNumberInvalid();
uint256 snapshotCount = _delSupplySnapshotCount;
if (snapshotCount == 0) {
return 0; // Returning zero since this means a delegation has never occurred
}
uint256 lower = 0;
uint256 upper = snapshotCount - 1;
// First check most recent delegated supply
if (_delSupplySnapshots[upper].blockNumber <= blockNumber) {
return _delSupplySnapshots[upper].value;
}
// Next check implicit zero balance
if (_delSupplySnapshots[lower].blockNumber > blockNumber) {
return 0;
}
while (upper > lower) {
uint256 center = upper - (upper - lower) / 2;
Snapshot memory snapshot = _delSupplySnapshots[center];
if (snapshot.blockNumber == blockNumber) {
return snapshot.value;
} else if (snapshot.blockNumber < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return _delSupplySnapshots[lower].value;
}
/**
* @dev This returns the follow NFT URI fetched from the hub.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
if (!_exists(tokenId)) revert Errors.TokenDoesNotExist();
return ILensHub(HUB).getFollowNFTURI(_profileId);
}
/**
* @dev Upon transfers, we move the appropriate delegations, and emit the transfer event in the hub.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override {
address fromDelegatee = _delegates[from];
address toDelegatee = _delegates[to];
address followModule = ILensHub(HUB).getFollowModule(_profileId);
_moveDelegate(fromDelegatee, toDelegatee, 1);
super._beforeTokenTransfer(from, to, tokenId);
ILensHub(HUB).emitFollowNFTTransferEvent(_profileId, tokenId, from, to);
if (followModule != address(0)) {
IFollowModule(followModule).followModuleTransferHook(_profileId, from, to, tokenId);
}
}
function _delegate(address delegator, address delegatee) internal {
uint256 delegatorBalance = balanceOf(delegator);
address previousDelegate = _delegates[delegator];
_delegates[delegator] = delegatee;
_moveDelegate(previousDelegate, delegatee, delegatorBalance);
}
function _moveDelegate(
address from,
address to,
uint256 amount
) internal {
unchecked {
if (from != address(0)) {
uint256 fromSnapshotCount = _snapshotCount[from];
// Underflow is impossible since, if from != address(0), then a delegation must have occurred (at least 1 snapshot)
uint256 previous = _snapshots[from][fromSnapshotCount - 1].value;
uint128 newValue = uint128(previous - amount);
_writeSnapshot(from, newValue, fromSnapshotCount);
emit Events.FollowNFTDelegatedPowerChanged(from, newValue, block.timestamp);
}
if (to != address(0)) {
// if from == address(0) then this is an initial delegation (add amount to supply)
if (from == address(0)) {
// It is expected behavior that the `previousDelSupply` underflows upon the first delegation,
// returning the expected value of zero
uint256 delSupplySnapshotCount = _delSupplySnapshotCount;
uint128 previousDelSupply = _delSupplySnapshots[delSupplySnapshotCount - 1]
.value;
uint128 newDelSupply = uint128(previousDelSupply + amount);
_writeSupplySnapshot(newDelSupply, delSupplySnapshotCount);
}
// It is expected behavior that `previous` underflows upon the first delegation to an address,
// returning the expected value of zero
uint256 toSnapshotCount = _snapshotCount[to];
uint128 previous = _snapshots[to][toSnapshotCount - 1].value;
uint128 newValue = uint128(previous + amount);
_writeSnapshot(to, newValue, toSnapshotCount);
emit Events.FollowNFTDelegatedPowerChanged(to, newValue, block.timestamp);
} else {
// If from != address(0) then this is removing a delegation, otherwise we're dealing with a
// non-delegated burn of tokens and don't need to take any action
if (from != address(0)) {
// Upon removing delegation (from != address(0) && to == address(0)), supply calculations cannot
// underflow because if from != address(0), then a delegation must have previously occurred, so
// the snapshot count must be >= 1 and the previous delegated supply must be >= amount
uint256 delSupplySnapshotCount = _delSupplySnapshotCount;
uint128 previousDelSupply = _delSupplySnapshots[delSupplySnapshotCount - 1]
.value;
uint128 newDelSupply = uint128(previousDelSupply - amount);
_writeSupplySnapshot(newDelSupply, delSupplySnapshotCount);
}
}
}
}
function _writeSnapshot(
address owner,
uint128 newValue,
uint256 ownerSnapshotCount
) internal {
unchecked {
uint128 currentBlock = uint128(block.number);
mapping(uint256 => Snapshot) storage ownerSnapshots = _snapshots[owner];
// Doing multiple operations in the same block
if (
ownerSnapshotCount != 0 &&
ownerSnapshots[ownerSnapshotCount - 1].blockNumber == currentBlock
) {
ownerSnapshots[ownerSnapshotCount - 1].value = newValue;
} else {
ownerSnapshots[ownerSnapshotCount] = Snapshot(currentBlock, newValue);
_snapshotCount[owner] = ownerSnapshotCount + 1;
}
}
}
function _writeSupplySnapshot(uint128 newValue, uint256 supplySnapshotCount) internal {
unchecked {
uint128 currentBlock = uint128(block.number);
// Doing multiple operations in the same block
if (
supplySnapshotCount != 0 &&
_delSupplySnapshots[supplySnapshotCount - 1].blockNumber == currentBlock
) {
_delSupplySnapshots[supplySnapshotCount - 1].value = newValue;
} else {
_delSupplySnapshots[supplySnapshotCount] = Snapshot(currentBlock, newValue);
_delSupplySnapshotCount = supplySnapshotCount + 1;
}
}
}
}
| @inheritdoc IFollowNFT First check most recent balance Next check implicit zero balance | function getPowerByBlockNumber(address user, uint256 blockNumber)
external
view
override
returns (uint256)
{
if (blockNumber > block.number) revert Errors.BlockNumberInvalid();
uint256 snapshotCount = _snapshotCount[user];
if (snapshotCount == 0) {
}
uint256 lower = 0;
uint256 upper = snapshotCount - 1;
if (_snapshots[user][upper].blockNumber <= blockNumber) {
return _snapshots[user][upper].value;
}
if (_snapshots[user][lower].blockNumber > blockNumber) {
return 0;
}
while (upper > lower) {
uint256 center = upper - (upper - lower) / 2;
Snapshot memory snapshot = _snapshots[user][center];
if (snapshot.blockNumber == blockNumber) {
return snapshot.value;
lower = center;
upper = center - 1;
}
}
return _snapshots[user][lower].value;
}
| 6,345,857 |
./full_match/1/0x154DAc76755d2A372804a9C409683F2eeFa9e5e9/sources/lib/tl-sol-tools/src/upgradeable/royalties/EIP2981TLUpgradeable.sol | Query the default royalty receiver and percentage. return Tuple containing the default royalty recipient and percentage out of 10_000 | function getDefaultRoyaltyRecipientAndPercentage() external view returns (address, uint256) {
return (_defaultRecipient, _defaultPercentage);
}
Upgradeability Gap
| 4,979,382 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the Uniswap V3 Factory
/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees
interface IUniswapV3Factory {
/// @notice Emitted when the owner of the factory is changed
/// @param oldOwner The owner before the owner was changed
/// @param newOwner The owner after the owner was changed
event OwnerChanged(address indexed oldOwner, address indexed newOwner);
/// @notice Emitted when a pool is created
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param pool The address of the created pool
event PoolCreated(
address indexed token0,
address indexed token1,
uint24 indexed fee,
int24 tickSpacing,
address pool
);
/// @notice Emitted when a new fee amount is enabled for pool creation via the factory
/// @param fee The enabled fee, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee
event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);
/// @notice Returns the current owner of the factory
/// @dev Can be changed by the current owner via setOwner
/// @return The address of the factory owner
function owner() external view returns (address);
/// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled
/// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context
/// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee
/// @return The tick spacing
function feeAmountTickSpacing(uint24 fee) external view returns (int24);
/// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @return pool The pool address
function getPool(
address tokenA,
address tokenB,
uint24 fee
) external view returns (address pool);
/// @notice Creates a pool for the given two tokens and fee
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @param fee The desired fee for the pool
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
/// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
/// are invalid.
/// @return pool The address of the newly created pool
function createPool(
address tokenA,
address tokenB,
uint24 fee
) external returns (address pool);
/// @notice Updates the owner of the factory
/// @dev Must be called by the current owner
/// @param _owner The new owner of the factory
function setOwner(address _owner) external;
/// @notice Enables a fee amount with the given tickSpacing
/// @dev Fee amounts may never be removed once enabled
/// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)
/// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount
function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* @title Solidity Bytes Arrays Utils
* @author Gonçalo Sá <[email protected]>
*
* @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
* The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
*/
pragma solidity >=0.5.0 <0.8.0;
library BytesLib {
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, 'slice_overflow');
require(_start + _length >= _start, 'slice_overflow');
require(_bytes.length >= _start + _length, 'slice_outOfBounds');
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_start + 20 >= _start, 'toAddress_overflow');
require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {
require(_start + 3 >= _start, 'toUint24_overflow');
require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;
import './BytesLib.sol';
/// @title Functions for manipulating path data for multihop swaps
library Path {
using BytesLib for bytes;
/// @dev The length of the bytes encoded address
uint256 private constant ADDR_SIZE = 20;
/// @dev The length of the bytes encoded fee
uint256 private constant FEE_SIZE = 3;
/// @dev The offset of a single token address and pool fee
uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;
/// @dev The offset of an encoded pool key
uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;
/// @dev The minimum length of an encoding that contains 2 or more pools
uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET;
/// @notice Returns true iff the path contains two or more pools
/// @param path The encoded swap path
/// @return True if path contains two or more pools, otherwise false
function hasMultiplePools(bytes memory path) internal pure returns (bool) {
return path.length >= MULTIPLE_POOLS_MIN_LENGTH;
}
/// @notice Decodes the first pool in path
/// @param path The bytes encoded swap path
/// @return tokenA The first token of the given pool
/// @return tokenB The second token of the given pool
/// @return fee The fee level of the pool
function decodeFirstPool(bytes memory path)
internal
pure
returns (
address tokenA,
address tokenB,
uint24 fee
)
{
tokenA = path.toAddress(0);
fee = path.toUint24(ADDR_SIZE);
tokenB = path.toAddress(NEXT_OFFSET);
}
/// @notice Gets the segment corresponding to the first pool in the path
/// @param path The bytes encoded swap path
/// @return The segment containing all data necessary to target the first pool in the path
function getFirstPool(bytes memory path) internal pure returns (bytes memory) {
return path.slice(0, POP_OFFSET);
}
/// @notice Skips a token + fee element from the buffer and returns the remainder
/// @param path The swap path
/// @return The remaining token + fee elements in the path
function skipToken(bytes memory path) internal pure returns (bytes memory) {
return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
library TransferHelper {
/// @notice Transfers tokens from the targeted address to the given destination
/// @notice Errors with 'STF' if transfer fails
/// @param token The contract address of the token to be transferred
/// @param from The originating address from which the tokens will be transferred
/// @param to The destination address of the transfer
/// @param value The amount to be transferred
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
}
/// @notice Transfers tokens from msg.sender to a recipient
/// @dev Errors with ST if transfer fails
/// @param token The contract address of the token which will be transferred
/// @param to The recipient of the transfer
/// @param value The value of the transfer
function safeTransfer(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
}
/// @notice Approves the stipulated contract to spend the given allowance in the given token
/// @dev Errors with 'SA' if transfer fails
/// @param token The contract address of the token to be approved
/// @param to The target of the approval
/// @param value The amount of the given token the target will be allowed to spend
function safeApprove(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');
}
/// @notice Transfers ETH to the recipient address
/// @dev Fails with `STE`
/// @param to The destination of the transfer
/// @param value The value to be transferred
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'STE');
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.7.6;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol';
import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol';
import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol';
import './libraries/PathPrice.sol';
import './interfaces/IHotPotV3Fund.sol';
import './interfaces/IHotPot.sol';
import './interfaces/IHotPotV3FundController.sol';
import './base/Multicall.sol';
contract HotPotV3FundController is IHotPotV3FundController, Multicall {
using Path for bytes;
address public override immutable uniV3Factory;
address public override immutable uniV3Router;
address public override immutable hotpot;
address public override governance;
address public override immutable WETH9;
uint32 maxPIS = (100 << 16) + 9974;// MaxPriceImpact: 1%, MaxSwapSlippage: 0.5% = (1 - (sqrtSlippage/1e4)^2) * 100%
mapping (address => bool) public override verifiedToken;
mapping (address => bytes) public override harvestPath;
modifier onlyManager(address fund){
require(msg.sender == IHotPotV3Fund(fund).manager(), "OMC");
_;
}
modifier onlyGovernance{
require(msg.sender == governance, "OGC");
_;
}
modifier checkDeadline(uint deadline) {
require(block.timestamp <= deadline, 'CDL');
_;
}
constructor(
address _hotpot,
address _governance,
address _uniV3Router,
address _uniV3Factory,
address _weth9
) {
hotpot = _hotpot;
governance = _governance;
uniV3Router = _uniV3Router;
uniV3Factory = _uniV3Factory;
WETH9 = _weth9;
}
/// @inheritdoc IControllerState
function maxPriceImpact() external override view returns(uint32 priceImpact){
return maxPIS >> 16;
}
/// @inheritdoc IControllerState
function maxSqrtSlippage() external override view returns(uint32 sqrtSlippage){
return maxPIS & 0xffff;
}
/// @inheritdoc IGovernanceActions
function setHarvestPath(address token, bytes calldata path) external override onlyGovernance {
bytes memory _path = path;
while (true) {
(address tokenIn, address tokenOut, uint24 fee) = _path.decodeFirstPool();
// pool is exist
address pool = IUniswapV3Factory(uniV3Factory).getPool(tokenIn, tokenOut, fee);
require(pool != address(0), "PIE");
// at least 2 observations
(,,,uint16 observationCardinality,,,) = IUniswapV3Pool(pool).slot0();
require(observationCardinality >= 2, "OC");
if (_path.hasMultiplePools()) {
_path = _path.skipToken();
} else {
//最后一个交易对:输入WETH9, 输出hotpot
require(tokenIn == WETH9 && tokenOut == hotpot, "IOT");
break;
}
}
harvestPath[token] = path;
emit SetHarvestPath(token, path);
}
/// @inheritdoc IGovernanceActions
function setMaxPriceImpact(uint32 priceImpact) external override onlyGovernance {
require(priceImpact <= 1e4 ,"SPI");
maxPIS = (priceImpact << 16) | (maxPIS & 0xffff);
emit SetMaxPriceImpact(priceImpact);
}
/// @inheritdoc IGovernanceActions
function setMaxSqrtSlippage(uint32 sqrtSlippage) external override onlyGovernance {
require(sqrtSlippage <= 1e4 ,"SSS");
maxPIS = maxPIS & 0xffff0000 | sqrtSlippage;
emit SetMaxSqrtSlippage(sqrtSlippage);
}
/// @inheritdoc IHotPotV3FundController
function harvest(address token, uint amount) external override returns(uint burned) {
bytes memory path = harvestPath[token];
PathPrice.verifySlippage(path, uniV3Factory, maxPIS & 0xffff);
uint value = amount <= IERC20(token).balanceOf(address(this)) ? amount : IERC20(token).balanceOf(address(this));
TransferHelper.safeApprove(token, uniV3Router, value);
ISwapRouter.ExactInputParams memory args = ISwapRouter.ExactInputParams({
path: path,
recipient: address(this),
deadline: block.timestamp,
amountIn: value,
amountOutMinimum: 0
});
burned = ISwapRouter(uniV3Router).exactInput(args);
IHotPot(hotpot).burn(burned);
emit Harvest(token, amount, burned);
}
/// @inheritdoc IGovernanceActions
function setGovernance(address account) external override onlyGovernance {
require(account != address(0));
governance = account;
emit SetGovernance(account);
}
/// @inheritdoc IGovernanceActions
function setVerifiedToken(address token, bool isVerified) external override onlyGovernance {
verifiedToken[token] = isVerified;
emit ChangeVerifiedToken(token, isVerified);
}
/// @inheritdoc IManagerActions
function setDescriptor(address fund, bytes calldata _descriptor) external override onlyManager(fund) {
return IHotPotV3Fund(fund).setDescriptor(_descriptor);
}
/// @inheritdoc IManagerActions
function setDepositDeadline(address fund, uint deadline) external override onlyManager(fund) {
return IHotPotV3Fund(fund).setDepositDeadline(deadline);
}
/// @inheritdoc IManagerActions
function setPath(
address fund,
address distToken,
bytes memory path
) external override onlyManager(fund){
require(verifiedToken[distToken]);
address fundToken = IHotPotV3Fund(fund).token();
bytes memory _path = path;
bytes memory _reverse;
(address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();
_reverse = abi.encodePacked(tokenOut, fee, tokenIn);
bool isBuy;
// 第一个tokenIn是基金token,那么就是buy路径
if(tokenIn == fundToken){
isBuy = true;
}
// 如果是sellPath, 第一个需要是目标代币
else{
require(tokenIn == distToken);
}
while (true) {
require(verifiedToken[tokenIn], "VIT");
require(verifiedToken[tokenOut], "VOT");
// pool is exist
address pool = IUniswapV3Factory(uniV3Factory).getPool(tokenIn, tokenOut, fee);
require(pool != address(0), "PIE");
// at least 2 observations
(,,,uint16 observationCardinality,,,) = IUniswapV3Pool(pool).slot0();
require(observationCardinality >= 2, "OC");
if (path.hasMultiplePools()) {
path = path.skipToken();
(tokenIn, tokenOut, fee) = path.decodeFirstPool();
_reverse = abi.encodePacked(tokenOut, fee, _reverse);
} else {
/// @dev 如果是buy, 最后一个token要是目标代币;
/// @dev 如果是sell, 最后一个token要是基金token.
if(isBuy)
require(tokenOut == distToken, "OID");
else
require(tokenOut == fundToken, "OIF");
break;
}
}
if(!isBuy) (_path, _reverse) = (_reverse, _path);
IHotPotV3Fund(fund).setPath(distToken, _path, _reverse);
}
/// @inheritdoc IManagerActions
function init(
address fund,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint amount,
uint deadline
) external override checkDeadline(deadline) onlyManager(fund) returns(uint128 liquidity){
return IHotPotV3Fund(fund).init(token0, token1, fee, tickLower, tickUpper, amount, maxPIS);
}
/// @inheritdoc IManagerActions
function add(
address fund,
uint poolIndex,
uint positionIndex,
uint amount,
bool collect,
uint deadline
) external override checkDeadline(deadline) onlyManager(fund) returns(uint128 liquidity){
return IHotPotV3Fund(fund).add(poolIndex, positionIndex, amount, collect, maxPIS);
}
/// @inheritdoc IManagerActions
function sub(
address fund,
uint poolIndex,
uint positionIndex,
uint proportionX128,
uint deadline
) external override checkDeadline(deadline) onlyManager(fund) returns(uint amount){
return IHotPotV3Fund(fund).sub(poolIndex, positionIndex, proportionX128, maxPIS);
}
/// @inheritdoc IManagerActions
function move(
address fund,
uint poolIndex,
uint subIndex,
uint addIndex,
uint proportionX128,
uint deadline
) external override checkDeadline(deadline) onlyManager(fund) returns(uint128 liquidity){
return IHotPotV3Fund(fund).move(poolIndex, subIndex, addIndex, proportionX128, maxPIS);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;
import '../interfaces/IMulticall.sol';
/// @title Multicall
/// @notice Enables calling multiple methods in a single call to the contract
abstract contract Multicall is IMulticall {
/// @inheritdoc IMulticall
function multicall(bytes[] calldata data) external payable override returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
// Next 5 lines from https://ethereum.stackexchange.com/a/83577
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
results[i] = result;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title HPT (Hotpot Funds) 代币接口定义.
interface IHotPot is IERC20{
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function burn(uint value) external returns (bool) ;
function burnFrom(address from, uint value) external returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './IHotPotV3FundERC20.sol';
import './fund/IHotPotV3FundEvents.sol';
import './fund/IHotPotV3FundState.sol';
import './fund/IHotPotV3FundUserActions.sol';
import './fund/IHotPotV3FundManagerActions.sol';
/// @title Hotpot V3 基金接口
/// @notice 接口定义分散在多个接口文件
interface IHotPotV3Fund is
IHotPotV3FundERC20,
IHotPotV3FundEvents,
IHotPotV3FundState,
IHotPotV3FundUserActions,
IHotPotV3FundManagerActions
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './controller/IManagerActions.sol';
import './controller/IGovernanceActions.sol';
import './controller/IControllerState.sol';
import './controller/IControllerEvents.sol';
/// @title Hotpot V3 控制合约接口定义.
/// @notice 基金经理和治理均需通过控制合约进行操作.
interface IHotPotV3FundController is IManagerActions, IGovernanceActions, IControllerState, IControllerEvents {
/// @notice 基金分成全部用于销毁HPT
/// @dev 任何人都可以调用本函数
/// @param token 用于销毁时购买HPT的代币类型
/// @param amount 代币数量
/// @return burned 销毁数量
function harvest(address token, uint amount) external returns(uint burned);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title Hotpot V3 基金份额代币接口定义
interface IHotPotV3FundERC20 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: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Multicall
/// @notice Enables calling multiple methods in a single call to the contract
interface IMulticall {
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @param data The encoded function data for each of the calls to make to this contract
/// @return results The results from each of the calls passed in via data
/// @dev The `msg.value` should not be trusted for any method callable from multicall.
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title HotPotV3Controller 事件接口定义
interface IControllerEvents {
/// @notice 当设置受信任token时触发
event ChangeVerifiedToken(address indexed token, bool isVerified);
/// @notice 当调用Harvest时触发
event Harvest(address indexed token, uint amount, uint burned);
/// @notice 当调用setHarvestPath时触发
event SetHarvestPath(address indexed token, bytes path);
/// @notice 当调用setGovernance时触发
event SetGovernance(address indexed account);
/// @notice 当调用setMaxSqrtSlippage时触发
event SetMaxSqrtSlippage(uint sqrtSlippage);
/// @notice 当调用setMaxPriceImpact时触发
event SetMaxPriceImpact(uint priceImpact);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title HotPotV3Controller 状态变量及只读函数
interface IControllerState {
/// @notice Returns the address of the Uniswap V3 router
function uniV3Router() external view returns (address);
/// @notice Returns the address of the Uniswap V3 facotry
function uniV3Factory() external view returns (address);
/// @notice 本项目治理代币HPT的地址
function hotpot() external view returns (address);
/// @notice 治理账户地址
function governance() external view returns (address);
/// @notice Returns the address of WETH9
function WETH9() external view returns (address);
/// @notice 代币是否受信任
/// @dev The call will revert if the the token argument is address 0.
/// @param token 要查询的代币地址
function verifiedToken(address token) external view returns (bool);
/// @notice harvest时交易路径
/// @param token 要兑换的代币
function harvestPath(address token) external view returns (bytes memory);
/// @notice 获取swap时最大滑点,取值范围为 0-1e4, 计算公式为:MaxSwapSlippage = (1 - (sqrtSlippage/1e4)^2) * 100%
/// 如设置最大滑点 0.5%, 则 sqrtSlippage 应设置为9974,此时 MaxSwapSlippage = (1-(9974/1e4)^2)*100% = 0.5%
function maxSqrtSlippage() external view returns (uint32);
/// @notice 获取swap时最大价格影响,取值范围为 0-1e4
function maxPriceImpact() external view returns (uint32);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title 治理操作接口定义
interface IGovernanceActions {
/// @notice Change governance
/// @dev This function can only be called by governance
/// @param account 新的governance地址
function setGovernance(address account) external;
/// @notice Set the token to be verified for all fund, vice versa
/// @dev This function can only be called by governance
/// @param token 目标代币
/// @param isVerified 是否受信任
function setVerifiedToken(address token, bool isVerified) external;
/// @notice Set the swap path for harvest
/// @dev This function can only be called by governance
/// @param token 目标代币
/// @param path 路径
function setHarvestPath(address token, bytes calldata path) external;
/// @notice 设置swap时最大滑点,取值范围为 0-1e4, 计算公式为:MaxSwapSlippage = (1 - (sqrtSlippage/1e4)^2) * 100%
/// 如设置最大滑点 0.5%, 则 sqrtSlippage 应设置为9974,此时 MaxSwapSlippage = (1-(9974/1e4)^2)*100% = 0.5%
/// @dev This function can only be called by governance
/// @param sqrtSlippage 0-1e4
function setMaxSqrtSlippage(uint32 sqrtSlippage) external;
/// @notice Set the max price impact for swap
/// @dev This function can only be called by governance
/// @param priceImpact 0-1e4
function setMaxPriceImpact(uint32 priceImpact) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import '../fund/IHotPotV3FundManagerActions.sol';
/// @title 控制器合约基金经理操作接口定义
interface IManagerActions {
/// @notice 设置基金描述信息
/// @dev This function can only be called by manager
/// @param _descriptor 描述信息
function setDescriptor(address fund, bytes calldata _descriptor) external;
/// @notice 设置基金存入截止时间
/// @dev This function can only be called by manager
/// @param fund 基金地址
/// @param deadline 最晚存入截止时间
function setDepositDeadline(address fund, uint deadline) external;
/// @notice 设置代币交易路径
/// @dev This function can only be called by manager
/// @dev 设置路径时不能修改为0地址,且path路径里的token必须验证是否受信任
/// @param fund 基金地址
/// @param distToken 目标代币地址
/// @param path 符合uniswap v3格式的交易路径
function setPath(
address fund,
address distToken,
bytes memory path
) external;
/// @notice 初始化头寸, 允许投资额为0.
/// @dev This function can only be called by manager
/// @param fund 基金地址
/// @param token0 token0 地址
/// @param token1 token1 地址
/// @param fee 手续费率
/// @param tickLower 价格刻度下届
/// @param tickUpper 价格刻度上届
/// @param amount 初始化投入金额,允许为0, 为0表示仅初始化头寸,不作实质性投资
/// @param deadline 最晚交易时间
/// @return liquidity 添加的lp数量
function init(
address fund,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint amount,
uint deadline
) external returns(uint128 liquidity);
/// @notice 投资指定头寸,可选复投手续费
/// @dev This function can only be called by manager
/// @param fund 基金地址
/// @param poolIndex 池子索引号
/// @param positionIndex 头寸索引号
/// @param amount 投资金额
/// @param collect 是否收集已产生的手续费并复投
/// @param deadline 最晚交易时间
/// @return liquidity 添加的lp数量
function add(
address fund,
uint poolIndex,
uint positionIndex,
uint amount,
bool collect,
uint deadline
) external returns(uint128 liquidity);
/// @notice 撤资指定头寸
/// @dev This function can only be called by manager
/// @param fund 基金地址
/// @param poolIndex 池子索引号
/// @param positionIndex 头寸索引号
/// @param proportionX128 撤资比例,左移128位; 允许为0,为0表示只收集手续费
/// @param deadline 最晚交易时间
/// @return amount 撤资获得的基金本币数量
function sub(
address fund,
uint poolIndex,
uint positionIndex,
uint proportionX128,
uint deadline
) external returns(uint amount);
/// @notice 调整头寸投资
/// @dev This function can only be called by manager
/// @param fund 基金地址
/// @param poolIndex 池子索引号
/// @param subIndex 要移除的头寸索引号
/// @param addIndex 要添加的头寸索引号
/// @param proportionX128 调整比例,左移128位
/// @param deadline 最晚交易时间
/// @return liquidity 调整后添加的lp数量
function move(
address fund,
uint poolIndex,
uint subIndex,
uint addIndex,
uint proportionX128,
uint deadline
) external returns(uint128 liquidity);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Hotpot V3 事件接口定义
interface IHotPotV3FundEvents {
/// @notice 当存入基金token时,会触发该事件
event Deposit(address indexed owner, uint amount, uint share);
/// @notice 当取走基金token时,会触发该事件
event Withdraw(address indexed owner, uint amount, uint share);
/// @notice 当调用setDescriptor时触发
event SetDescriptor(bytes descriptor);
/// @notice 当调用setDepositDeadline时触发
event SetDeadline(uint deadline);
/// @notice 当调用setPath时触发
event SetPath(address distToken, bytes path);
/// @notice 当调用init时,会触发该事件
event Init(uint poolIndex, uint positionIndex, uint amount);
/// @notice 当调用add时,会触发该事件
event Add(uint poolIndex, uint positionIndex, uint amount, bool collect);
/// @notice 当调用sub时,会触发该事件
event Sub(uint poolIndex, uint positionIndex, uint proportionX128);
/// @notice 当调用move时,会触发该事件
event Move(uint poolIndex, uint subIndex, uint addIndex, uint proportionX128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @notice 基金经理操作接口定义
interface IHotPotV3FundManagerActions {
/// @notice 设置基金描述信息
/// @dev This function can only be called by controller
/// @param _descriptor 描述信息
function setDescriptor(bytes calldata _descriptor) external;
/// @notice 设置基金存入截止时间
/// @dev This function can only be called by controller
/// @param deadline 最晚存入截止时间
function setDepositDeadline(uint deadline) external;
/// @notice 设置代币交易路径
/// @dev This function can only be called by controller
/// @dev 设置路径时不能修改为0地址,且path路径里的token必须验证是否受信任
/// @param distToken 目标代币地址
/// @param buy 购买路径(本币->distToken)
/// @param sell 销售路径(distToken->本币)
function setPath(
address distToken,
bytes calldata buy,
bytes calldata sell
) external;
/// @notice 初始化头寸, 允许投资额为0.
/// @dev This function can only be called by controller
/// @param token0 token0 地址
/// @param token1 token1 地址
/// @param fee 手续费率
/// @param tickLower 价格刻度下届
/// @param tickUpper 价格刻度上届
/// @param amount 初始化投入金额,允许为0, 为0表示仅初始化头寸,不作实质性投资
/// @param maxPIS 最大价格影响和价格滑点
/// @return liquidity 添加的lp数量
function init(
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint amount,
uint32 maxPIS
) external returns(uint128 liquidity);
/// @notice 投资指定头寸,可选复投手续费
/// @dev This function can only be called by controller
/// @param poolIndex 池子索引号
/// @param positionIndex 头寸索引号
/// @param amount 投资金额
/// @param collect 是否收集已产生的手续费并复投
/// @param maxPIS 最大价格影响和价格滑点
/// @return liquidity 添加的lp数量
function add(
uint poolIndex,
uint positionIndex,
uint amount,
bool collect,
uint32 maxPIS
) external returns(uint128 liquidity);
/// @notice 撤资指定头寸
/// @dev This function can only be called by controller
/// @param poolIndex 池子索引号
/// @param positionIndex 头寸索引号
/// @param proportionX128 撤资比例,左移128位; 允许为0,为0表示只收集手续费
/// @param maxPIS 最大价格影响和价格滑点
/// @return amount 撤资获得的基金本币数量
function sub(
uint poolIndex,
uint positionIndex,
uint proportionX128,
uint32 maxPIS
) external returns(uint amount);
/// @notice 调整头寸投资
/// @dev This function can only be called by controller
/// @param poolIndex 池子索引号
/// @param subIndex 要移除的头寸索引号
/// @param addIndex 要添加的头寸索引号
/// @param proportionX128 调整比例,左移128位
/// @param maxPIS 最大价格影响和价格滑点
/// @return liquidity 调整后添加的lp数量
function move(
uint poolIndex,
uint subIndex,
uint addIndex,
uint proportionX128, //以前是按LP数量移除,现在改成按总比例移除,这样前端就不用管实际LP是多少了
uint32 maxPIS
) external returns(uint128 liquidity);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Hotpot V3 状态变量及只读函数
interface IHotPotV3FundState {
/// @notice 控制器合约地址
function controller() external view returns (address);
/// @notice 基金经理地址
function manager() external view returns (address);
/// @notice 基金本币地址
function token() external view returns (address);
/// @notice 32 bytes 基金经理 + 任意长度的简要描述
function descriptor() external view returns (bytes memory);
/// @notice 基金锁定期
function lockPeriod() external view returns (uint);
/// @notice 基金经理收费基线
function baseLine() external view returns (uint);
/// @notice 基金经理收费比例
function managerFee() external view returns (uint);
/// @notice 基金存入截止时间
function depositDeadline() external view returns (uint);
/// @notice 获取最新存入时间
/// @param account 目标地址
/// @return 最新存入时间
function lastDepositTime(address account) external view returns (uint);
/// @notice 总投入数量
function totalInvestment() external view returns (uint);
/// @notice owner的投入数量
/// @param owner 用户地址
/// @return 投入本币的数量
function investmentOf(address owner) external view returns (uint);
/// @notice 指定头寸的资产数量
/// @param poolIndex 池子索引号
/// @param positionIndex 头寸索引号
/// @return 以本币计价的头寸资产数量
function assetsOfPosition(uint poolIndex, uint positionIndex) external view returns(uint);
/// @notice 指定pool的资产数量
/// @param poolIndex 池子索引号
/// @return 以本币计价的池子资产数量
function assetsOfPool(uint poolIndex) external view returns(uint);
/// @notice 总资产数量
/// @return 以本币计价的总资产数量
function totalAssets() external view returns (uint);
/// @notice 基金本币->目标代币 的购买路径
/// @param _token 目标代币地址
/// @return 符合uniswap v3格式的目标代币购买路径
function buyPath(address _token) external view returns (bytes memory);
/// @notice 目标代币->基金本币 的购买路径
/// @param _token 目标代币地址
/// @return 符合uniswap v3格式的目标代币销售路径
function sellPath(address _token) external view returns (bytes memory);
/// @notice 获取池子地址
/// @param index 池子索引号
/// @return 池子地址
function pools(uint index) external view returns(address);
/// @notice 头寸信息
/// @dev 由于基金需要遍历头寸,所以用二维动态数组存储头寸
/// @param poolIndex 池子索引号
/// @param positionIndex 头寸索引号
/// @return isEmpty 是否空头寸,tickLower 价格刻度下届,tickUpper 价格刻度上届
function positions(uint poolIndex, uint positionIndex)
external
view
returns(
bool isEmpty,
int24 tickLower,
int24 tickUpper
);
/// @notice pool数组长度
function poolsLength() external view returns(uint);
/// @notice 指定池子的头寸数组长度
/// @param poolIndex 池子索引号
/// @return 头寸数组长度
function positionsLength(uint poolIndex) external view returns(uint);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Hotpot V3 用户操作接口定义
/// @notice 存入(deposit)函数适用于ERC20基金; 如果是ETH基金(内部会转换为WETH9),应直接向基金合约转账;
interface IHotPotV3FundUserActions {
/// @notice 用户存入基金本币
/// @param amount 存入数量
/// @return share 用户获得的基金份额
function deposit(uint amount) external returns(uint share);
/// @notice 用户取出指定份额的本币
/// @param share 取出的基金份额数量
/// @param amountMin 最小提取值
/// @param deadline 最晚交易时间
/// @return amount 返回本币数量
function withdraw(uint share, uint amountMin, uint deadline) external returns(uint amount);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint64
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint64 {
uint256 internal constant Q64 = 0x10000000000000000;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol";
import "@uniswap/v3-core/contracts/libraries/FixedPoint128.sol";
import "./FixedPoint64.sol";
import '@uniswap/v3-core/contracts/libraries/TickMath.sol';
import "@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol";
import "@uniswap/v3-periphery/contracts/libraries/Path.sol";
library PathPrice {
using Path for bytes;
/// @notice 获取目标代币当前价格的平方根
/// @param path 兑换路径
/// @return sqrtPriceX96 价格的平方根(X 2^96),给定兑换路径的 tokenOut / tokenIn 的价格
function getSqrtPriceX96(
bytes memory path,
address uniV3Factory
) internal view returns (uint sqrtPriceX96){
require(path.length > 0, "IPL");
sqrtPriceX96 = FixedPoint96.Q96;
uint _nextSqrtPriceX96;
uint32[] memory secondAges = new uint32[](2);
secondAges[0] = 0;
secondAges[1] = 1;
while (true) {
(address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();
IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(uniV3Factory, PoolAddress.getPoolKey(tokenIn, tokenOut, fee)));
(_nextSqrtPriceX96,,,,,,) = pool.slot0();
sqrtPriceX96 = tokenIn > tokenOut
? FullMath.mulDiv(sqrtPriceX96, FixedPoint96.Q96, _nextSqrtPriceX96)
: FullMath.mulDiv(sqrtPriceX96, _nextSqrtPriceX96, FixedPoint96.Q96);
// decide whether to continue or terminate
if (path.hasMultiplePools())
path = path.skipToken();
else
break;
}
}
/// @notice 获取目标代币预言机价格的平方根
/// @param path 兑换路径
/// @return sqrtPriceX96Last 预言机价格的平方根(X 2^96),给定兑换路径的 tokenOut / tokenIn 的价格
function getSqrtPriceX96Last(
bytes memory path,
address uniV3Factory
) internal view returns (uint sqrtPriceX96Last){
require(path.length > 0, "IPL");
sqrtPriceX96Last = FixedPoint96.Q96;
uint _nextSqrtPriceX96;
uint32[] memory secondAges = new uint32[](2);
secondAges[0] = 0;
secondAges[1] = 1;
while (true) {
(address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();
IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(uniV3Factory, PoolAddress.getPoolKey(tokenIn, tokenOut, fee)));
// sqrtPriceX96Last
(int56[] memory tickCumulatives,) = pool.observe(secondAges);
_nextSqrtPriceX96 = TickMath.getSqrtRatioAtTick(int24(tickCumulatives[0] - tickCumulatives[1]));
sqrtPriceX96Last = tokenIn > tokenOut
? FullMath.mulDiv(sqrtPriceX96Last, FixedPoint96.Q96, _nextSqrtPriceX96)
: FullMath.mulDiv(sqrtPriceX96Last, _nextSqrtPriceX96, FixedPoint96.Q96);
// decide whether to continue or terminate
if (path.hasMultiplePools())
path = path.skipToken();
else
break;
}
}
/// @notice 验证交易滑点是否满足条件
/// @param path 兑换路径
/// @param uniV3Factory uniswap v3 factory
/// @param maxSqrtSlippage 最大滑点,最大值: 1e4
/// @return 当前价
function verifySlippage(
bytes memory path,
address uniV3Factory,
uint32 maxSqrtSlippage
) internal view returns(uint) {
uint last = getSqrtPriceX96Last(path, uniV3Factory);
uint current = getSqrtPriceX96(path, uniV3Factory);
if(last > current) require(current > FullMath.mulDiv(maxSqrtSlippage, last, 1e4), "VS");
return current;
}
} | @inheritdoc IManagerActions | function init(
address fund,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint amount,
uint deadline
) external override checkDeadline(deadline) onlyManager(fund) returns(uint128 liquidity){
return IHotPotV3Fund(fund).init(token0, token1, fee, tickLower, tickUpper, amount, maxPIS);
}
| 416,960 |
./partial_match/1/0xEceec31C940e49C7557C530305DA1Ac3C3556569/sources/ZUSDImplementation.sol | Gets the balance of the specified address. addr The address to query the the balance of. Returns a uint256 representing the amount owned by the passed address./ | function balanceOf(address addr) external view override returns (uint256) {
return _balances[addr];
}
| 2,809,946 |
pragma solidity ^0.5.15;
interface IERC20 {
function TOTALSUPPLY265() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF676(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER585(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE478(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE401(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM799(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER297(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL288(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER981() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA870() internal view 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;
}
}
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED51(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = _MSGSENDER981();
emit OWNERSHIPTRANSFERRED51(address(0), _owner);
}
function OWNER52() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER947() { //inject NONSTANDARD NAMING
require(ISOWNER855(), "Ownable: caller is not the owner");
_;
}
function ISOWNER855() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER981() == _owner;
}
function RENOUNCEOWNERSHIP936() public ONLYOWNER947 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED51(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP177(address newOwner) public ONLYOWNER947 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP636(newOwner);
}
function _TRANSFEROWNERSHIP636(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED51(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function TOTALSUPPLY265() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF676(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER585(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER399(_MSGSENDER981(), recipient, amount);
return true;
}
function ALLOWANCE478(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE401(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE768(_MSGSENDER981(), spender, amount);
return true;
}
function TRANSFERFROM799(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER399(sender, recipient, amount);
_APPROVE768(sender, _MSGSENDER981(), _allowances[sender][_MSGSENDER981()].SUB171(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE254(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE768(_MSGSENDER981(), spender, _allowances[_MSGSENDER981()][spender].ADD125(addedValue));
return true;
}
function DECREASEALLOWANCE775(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE768(_MSGSENDER981(), spender, _allowances[_MSGSENDER981()][spender].SUB171(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER399(address sender, address recipient, uint256 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].SUB171(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD125(amount);
emit TRANSFER297(sender, recipient, amount);
}
function _MINT552(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD125(amount);
_balances[account] = _balances[account].ADD125(amount);
emit TRANSFER297(address(0), account, amount);
}
function _BURN908(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB171(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB171(amount);
emit TRANSFER297(account, address(0), amount);
}
function _APPROVE768(address owner, address spender, uint256 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 APPROVAL288(owner, spender, amount);
}
function _BURNFROM359(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
_BURN908(account, amount);
_APPROVE768(account, _MSGSENDER981(), _allowances[account][_MSGSENDER981()].SUB171(amount, "ERC20: burn amount exceeds allowance"));
}
}
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 NAME677() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL955() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS596() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
library SafeMath {
function ADD125(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB171(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB171(a, b, "SafeMath: subtraction overflow");
}
function SUB171(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 MUL207(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV619(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV619(a, b, "SafeMath: division by zero");
}
function DIV619(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;
return c;
}
function MOD550(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD550(a, b, "SafeMath: modulo by zero");
}
function MOD550(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT651(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE339(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE156(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");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER644(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.TRANSFER585.selector, to, value));
}
function SAFETRANSFERFROM18(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.TRANSFERFROM799.selector, from, to, value));
}
function SAFEAPPROVE229(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE478(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.APPROVE401.selector, spender, value));
}
function SAFEINCREASEALLOWANCE497(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE478(address(this), spender).ADD125(value);
CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.APPROVE401.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE975(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE478(address(this), spender).SUB171(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN428(token, abi.encodeWithSelector(token.APPROVE401.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN428(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT651(), "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");
}
}
}
interface Controller {
function WITHDRAW158(address, uint) external; //inject NONSTANDARD NAMING
function BALANCEOF676(address) external view returns (uint); //inject NONSTANDARD NAMING
function EARN532(address, uint) external; //inject NONSTANDARD NAMING
function REWARDS630() external view returns (address); //inject NONSTANDARD NAMING
}
// vault1111 111111111111
// abi1111: https://github.com/ystar-foundation/YstarFarming/blob/master/Vault/abi/vault.json
contract Vault {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
IERC20 public token;
IERC20 public YFToken; // YF1111
uint public min = 9500;
uint public constant max986 = 10000; //inject NONSTANDARD NAMING
uint public earnLowerlimit; //1111111111111earn
address public governance;
address public controller;
struct Player {
uint256 stake; // 1111
uint256 payout; // 11
uint256 total_out; // 1111111
}
mapping(address => Player) public player_; // (player => data) player data
struct Global {
uint256 total_stake; // 11111
uint256 total_out; // 11111
uint256 earnings_per_share; // 1111
}
mapping(uint256 => Global) public global_; // (global => data) global data
mapping (address => uint256) public deposittime;
uint256 constant internal magnitude720 = 10**40; // 1014011 //inject NONSTANDARD NAMING
address constant public yf82 = address(0x96F9632b25f874769969ff91219fCCb6ceDf26D2); //inject NONSTANDARD NAMING
string public getName;
constructor (address _token, uint256 _earnLowerlimit) public {
token = IERC20(_token);
getName = string(abi.encodePacked("yf:Vault:", ERC20Detailed(_token).NAME677()));
earnLowerlimit = _earnLowerlimit*1e18;
YFToken = IERC20(yf82);
governance = tx.origin;
controller = 0xcC8d36211374a08fC61d74ed2E48e22b922C9D7C;
}
function BALANCE265() public view returns (uint) { //inject NONSTANDARD NAMING
return token.BALANCEOF676(address(this))
.ADD125(Controller(controller).BALANCEOF676(address(token)));
}
function SETMIN245(uint _min) external { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
min = _min;
}
// 11111111111111111111
function SETGOVERNANCE992(address _governance) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
// 1111token
function SETTOKEN102(address _token) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
token = IERC20(_token);
}
// 1111111111111111111
function SETCONTROLLER604(address _controller) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
controller = _controller;
}
function SETEARNLOWERLIMIT476(uint256 _earnLowerlimit) public{ //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
earnLowerlimit = _earnLowerlimit;
}
// Custom logic in here for how much the vault allows to be borrowed
// Sets minimum required on-hand to keep small withdrawals cheap
// 11111111111
// 111111111111111111111
function AVAILABLE23() public view returns (uint) { //inject NONSTANDARD NAMING
return token.BALANCEOF676(address(this)).MUL207(min).DIV619(max986); // balance*min/max 1111111111111111111
}
// 11111Strategy1111111111111 vault->controller->strategy
function EARN532() public { //inject NONSTANDARD NAMING
uint _bal = AVAILABLE23(); // 1111111111111111111111
token.SAFETRANSFER644(controller, _bal); // 1111111
Controller(controller).EARN532(address(token), _bal); // 11111Strategy111111
}
// 11 111111
function DEPOSIT245(uint amount) external { //inject NONSTANDARD NAMING
// 111111111111111111appove1111111111111
token.SAFETRANSFERFROM18(msg.sender, address(this), amount);
// 1111111111
player_[msg.sender].stake = player_[msg.sender].stake.ADD125(amount);
// 11111110
if (global_[0].earnings_per_share != 0) {
player_[msg.sender].payout = player_[msg.sender].payout.ADD125(
global_[0].earnings_per_share.MUL207(amount).SUB171(1).DIV619(magnitude720).ADD125(1) // (((earnings_per_share*amount)-1)/magnitude)+1
);
}
// 1111111111
global_[0].total_stake = global_[0].total_stake.ADD125(amount);
// 111111111111111111111111111111111111111111111
if (token.BALANCEOF676(address(this)) > earnLowerlimit){
EARN532();
}
// 11111111
deposittime[msg.sender] = now;
}
// No rebalance implementation for lower fees and faster swaps
// 11
function WITHDRAW158(uint amount) external { //inject NONSTANDARD NAMING
CLAIM365(); // 111111111111
require(amount <= player_[msg.sender].stake, "!balance");
uint r = amount;
// Check balance
uint b = token.BALANCEOF676(address(this));
if (b < r) { // 11vault111111111111111111111Strategy11111111111
uint _withdraw = r.SUB171(b);
Controller(controller).WITHDRAW158(address(token), _withdraw); // 11
uint _after = token.BALANCEOF676(address(this));
uint _diff = _after.SUB171(b);
if (_diff < _withdraw) { // 111111111111111111111vault111111
r = b.ADD125(_diff);
}
}
// 111111111111111111111
player_[msg.sender].payout = player_[msg.sender].payout.SUB171(
global_[0].earnings_per_share.MUL207(amount).DIV619(magnitude720)
);
// 1111111111111
player_[msg.sender].stake = player_[msg.sender].stake.SUB171(amount);
global_[0].total_stake = global_[0].total_stake.SUB171(amount);
// 1111111111
token.SAFETRANSFER644(msg.sender, r);
}
// Strategy.harvest 111111
function MAKE_PROFIT788(uint256 amount) public { //inject NONSTANDARD NAMING
require(amount > 0, "not 0");
YFToken.SAFETRANSFERFROM18(msg.sender, address(this), amount); // 1111111111111110%1111190%1111111
global_[0].earnings_per_share = global_[0].earnings_per_share.ADD125(
amount.MUL207(magnitude720).DIV619(global_[0].total_stake)
);
global_[0].total_out = global_[0].total_out.ADD125(amount);
}
// 11111111
function CAL_OUT246(address user) public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 _cal = global_[0].earnings_per_share.MUL207(player_[user].stake).DIV619(magnitude720);
if (_cal < player_[user].payout) {
return 0;
} else {
return _cal.SUB171(player_[user].payout);
}
}
// 11111111111111111111111111.11111111111harvest1111111111
function CAL_OUT_PENDING918(uint256 _pendingBalance,address user) public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 _earnings_per_share = global_[0].earnings_per_share.ADD125(
_pendingBalance.MUL207(magnitude720).DIV619(global_[0].total_stake)
);
uint256 _cal = _earnings_per_share.MUL207(player_[user].stake).DIV619(magnitude720);
_cal = _cal.SUB171(CAL_OUT246(user));
if (_cal < player_[user].payout) {
return 0;
} else {
return _cal.SUB171(player_[user].payout);
}
}
// 111111
function CLAIM365() public { //inject NONSTANDARD NAMING
uint256 out = CAL_OUT246(msg.sender);
player_[msg.sender].payout = global_[0].earnings_per_share.MUL207(player_[msg.sender].stake).DIV619(magnitude720);
player_[msg.sender].total_out = player_[msg.sender].total_out.ADD125(out);
if (out > 0) {
uint256 _depositTime = now - deposittime[msg.sender];
if (_depositTime < 1 days){ // deposit in 24h
uint256 actually_out = _depositTime.MUL207(out).MUL207(1e18).DIV619(1 days).DIV619(1e18);
uint256 to_team = out.SUB171(actually_out);
YFToken.SAFETRANSFER644(Controller(controller).REWARDS630(), to_team);
out = actually_out;
}
YFToken.SAFETRANSFER644(msg.sender, out);
}
}
} | inject NONSTANDARD NAMING | function ADD125(uint256 a, uint256 b) internal pure returns (uint256) { | 12,634,625 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./OracleGetter.sol";
import "./ERC20.sol";
import "./Inflation.sol";
import "hardhat/console.sol";
/**
@author Tellor Inc.
@title Chorus
@dev Chorus is a structure for issuing semi-stablecoins as community currencies
**/
// slither-disable-next-line missing-inheritance
contract Chorus is Inflation, OracleGetter, ERC20 {
/*Events*/
event CollateralThreshold(uint256 _collateralThreshold);//emits if collateral threshold changes
event CollateralPriceAge(uint256 _collateralPriceAge);//emits if collateral price age changes
event Liquidate(
address _party,
uint256 _tokensAmnt,
uint256 _collateralAmnt,
uint256 _collateralPenalty
);//emits upon a liquidation
event LiquidationPenatly(uint256 _newPenalty);//emits when the liquidation penalty changes
event MintTokens(
address _holder,
uint256 _amount,
address _to,
uint256 _collateralRatio
);//emits when new tokens are minted
event NewAdmin(address _newAdmin);//emits when a new admin is set
event WithdrawCollateral(
address _holder,
uint256 _collateralAmnt,
uint256 _collateralRatio
);//emits when collateral is withdrawn
event WithdrawToken(address _holder, uint256 _tokenAmnt, uint256 _collateralAmnt);//emits when tokens are withdrawn
event WithdrawTokenRequest(address _user, uint256 _amount);
/*Variables*/
struct WithdrawDetails{
uint256 amount;
uint256 requestDate;
}
ERC20 public collateralToken;
address public admin = msg.sender;
uint256 private tknPrice = 1e18;
uint256 public collateralID; // The collateral id used to check the Tellor oracle for its USD price.
uint256 public collateralPriceGranularity; //usually 1000000 in the Tellor system
uint256 public collateralThreshold = 15e17; // 150%.
uint256 public collateralPriceAge = 3600; // e.g. 1hr. This is the delay in the feed from Tellor
uint256 public liquidationPenatly = 0;
uint256 public inflRatePerSec;// The rate at which the token decreases value. 1e18 precision. 100e18 is 100%.
uint256 public inflLastUpdate = block.timestamp;
address public inflBeneficiary; // Where to send the inflation tokens.
mapping(address => WithdrawDetails) withdrawRequested;
/*Modifiers*/
modifier onlyAdmin {
require(msg.sender == admin, "not an admin");
_;
}
modifier within100e18Range(uint256 _value) {
require(_value > 0 && _value < 100e18, "value not within allowed limits");
_;
}
/*Functions*/
/**
* @dev This is the constructor, sets the inital paramaters in the system
* The parameters include, the Tellor Address, collateral token's address,
* collateral token's requestID, the price granualrity, the token name,
* token's symbol, inflation rate per year, and the inflation beneficiary
*/
constructor(
address payable _tellorAddress,
address _collateralToken,
uint256 _collateralID,
uint256 _collateralPriceGranularity,
string memory _tokenName,
string memory _tokenSymbol,
uint256 _inflRatePerYear,
address _inflBeneficiary,
bool _isWhitelisted
)
OracleGetter(_tellorAddress)
ERC20(_tokenName, _tokenSymbol,_isWhitelisted)
within100e18Range(_inflRatePerYear)
{
collateralID = _collateralID;
collateralToken = ERC20(_collateralToken);
collateralPriceGranularity = _collateralPriceGranularity;
require(_collateralPriceGranularity > 0 && _collateralPriceGranularity <= 1e18, "value not within allowed limits");
require(_inflBeneficiary != address(0), "benificiary address not set");
inflBeneficiary = _inflBeneficiary;
inflRatePerSec = yearlyRateToPerSec(_inflRatePerYear);
}
/**
* @dev Returns the current token price in USD reduced by the current inflation.
* @return uint256 token price
*/
function collateralBalance() external view returns (uint256) {
return collateralToken.balanceOf(address(this));
}
/**
* @dev Checks the Tellor oracle and gets the collateral price
* @return uint256 collateral price in USD upscaled to e18 precision.
*/
// slither-disable-next-line timestamp
function collateralPrice() public view returns (uint256) {
(bool _didGet, uint256 _collateralPrice, ) =
_getDataBefore(collateralID, block.timestamp - collateralPriceAge);
require(_didGet, "getting oracle price");
return mul(_collateralPrice, div(1e18, collateralPriceGranularity));
}
/**
* @dev A view funciton to look at the collateralization of the system
* @return uint256 collateral token balance of this address / totalSupply
*/
function collateralRatio() public view returns (uint256) {
uint256 _collateralBalance = collateralToken.balanceOf(address(this));
// slither-disable-next-line incorrect-equality
if(totalSupply() == 0 || _collateralBalance == 0) {
return 0;
}
uint256 _collateralValue = wmul(collateralPrice(), _collateralBalance);
uint256 tokenSupplyWithInflInterest =
accrueInterest(totalSupply(), inflRatePerSec, block.timestamp - inflLastUpdate);
uint256 _tokenValue = wmul(tokenPrice(), tokenSupplyWithInflInterest);
if(_tokenValue == 0){
return 100e18;
}
return wdiv(_collateralValue,_tokenValue);
}
/**
* @dev Allows the admin to deposit collateral
* @param _amount the amount of collateral token to deposit
*/
function depositCollateral(uint256 _amount) external onlyAdmin {
require(_amount > 0, "deposit amount 0");
require(
collateralToken.transferFrom(msg.sender, address(this), _amount),
"failed collateral deposit transfer"
);
}
/**
* @dev Function to allow anyone to liquidate the system if it is undercollateralized
*/
function liquidate() external {
require(
collateralRatio() < collateralThreshold,
"collateral utilizatoin is above threshold"
);
require(balanceOf(msg.sender) > 0, "msg sender doesn't own any tokens");
uint256 _tknSuplyRatio =
wdiv(collateralToken.balanceOf(address(this)), totalSupply());
uint256 _tokensToBurn = balanceOf(msg.sender);
uint256 _collatAmt = wmul(_tokensToBurn, _tknSuplyRatio);
uint256 _collatPenalty = wmul(_collatAmt, liquidationPenatly);
emit Liquidate(msg.sender, _tokensToBurn, _collatAmt, _collatPenalty);
_burn(msg.sender, _tokensToBurn);
require(
collateralToken.transfer(msg.sender, sub(_collatAmt, _collatPenalty)),
"collateral liquidation transfer fails"
);
require(
collateralToken.transfer(inflBeneficiary, _collatPenalty),
"collateral liquidation penalty transfer fails"
);
}
/**
* @dev Allows the admin to mint tokens up to the collateral threshold
* @param _amount the amount of collateral tokens to mint
* @param _to the address to mint them to;
*/
function mintToken(uint256 _amount, address _to) external onlyAdmin {
_mint(_to, _amount);
uint256 _cRatio = collateralRatio();
require(
_cRatio >= collateralThreshold,
"collateral utilization below the threshold"
);
emit MintTokens(msg.sender, _amount, _to, _cRatio);
}
/**
* @dev Allows a user to request to withdraw tokens
* @param _amount the amount of tokens to withdraw
*/
function requestWithdrawToken(uint256 _amount) external {
require(_amount > 0, "amount should be greater than 0");
require(balanceOf(msg.sender) >= _amount, "not enough balance");
withdrawRequested[msg.sender].requestDate = block.timestamp;
withdrawRequested[msg.sender].amount = _amount;
_transfer(msg.sender, address(this), _amount);
emit WithdrawTokenRequest(msg.sender, _amount);
}
/**
* @dev Allows the user to set a new admin address
* @param _newAdmin the address of the new admin address
*/
function setAdmin(address _newAdmin) external onlyAdmin {
require(_newAdmin != address(0), "cannot send to the zero address");
admin = _newAdmin;
emit NewAdmin(_newAdmin);
}
/**
* @dev Allows the admin to set the collateral price Age (delay in feed from Tellor)
* @param _amount the amount of delay in the price feed (we want to wait for disputes)
*/
function setCollateralPriceAge(uint256 _amount) external onlyAdmin {
collateralPriceAge = _amount;
emit CollateralPriceAge(_amount);
}
/**
* @dev Allows the admin to set the Collateral threshold
* @param _amount new collateral threshold
*/
function setCollateralThreshold(uint256 _amount)
external
onlyAdmin
within100e18Range(_amount)
{
collateralThreshold = _amount;
emit CollateralThreshold(_amount);
}
/**
* @dev Allows the admin to set the liquidation penalty
* @param _amount the amount of the liquidation penalty
*/
function setLiquidationPenatly(uint256 _amount)
external
onlyAdmin
within100e18Range(_amount)
{
liquidationPenatly = wdiv(_amount, 100e18); // Convert to a fraction.
emit LiquidationPenatly(liquidationPenatly);
}
/**
* @dev Returns the current token price in USD reduced by the current inflation.
* @return uint256 token price
*/
function tokenPrice() public view returns (uint256) {
return
accrueInflation(
tknPrice,
inflRatePerSec,
block.timestamp - inflLastUpdate
);
}
/**
* @dev Function to reduce token price by the inflation rate,
* increases the total supply by the inflation rate and
* sends the new tokens to the inflation beneficiary.
*/
// slither-disable-next-line timestamp
function updateInflation() external {
uint256 secsPassed = block.timestamp - inflLastUpdate;
require(secsPassed > 0, "no inflation increase yet");
inflLastUpdate = block.timestamp;
tknPrice = accrueInflation(tknPrice, inflRatePerSec, secsPassed);
uint256 _tokensToMint =
sub(
accrueInterest(totalSupply(), inflRatePerSec, secsPassed),
totalSupply()
);
_mint(inflBeneficiary, _tokensToMint);
}
/**
* @dev Allows the admin to withdraw collateral above the threshold
* @param _amount the amount of collateral token to deposit
*/
function withdrawCollateral(uint256 _amount) external onlyAdmin {
require(
collateralToken.transfer(msg.sender, _amount),
"collateral transfer fails"
);
uint256 _cRatio = collateralRatio();
require(
_cRatio >= collateralThreshold,
"collateral utilization below the threshold"
);
// slither-disable-next-line reentrancy-events
emit WithdrawCollateral(msg.sender, _amount, _cRatio);
}
/**
* @dev Allows a user to withdraw tokens
*/
function withdrawToken() external {
WithdrawDetails memory wd = withdrawRequested[msg.sender];
uint256 _amount = withdrawRequested[msg.sender].amount;
require(_amount > 0, "amount should be greater than 0");
uint256 _waitPeriod = 1 + 100 * _amount / totalSupply() / 5; //increases by 1 day for every 5 percent
// slither-disable-next-line timestamp
require(block.timestamp - wd.requestDate >= 86400 * _waitPeriod, "must wait to withdraw");
withdrawRequested[msg.sender].amount = 0;
uint256 _collatPrice = collateralPrice();
uint256 _priceRatio = wdiv(tokenPrice(), _collatPrice);
uint256 _collateralAmnt = wmul(_priceRatio, _amount);
_burn(address(this), _amount);
require(
collateralToken.transfer(msg.sender, _collateralAmnt),
"collateral transfer fail"
);
// slither-disable-next-line reentrancy-events
emit WithdrawToken(msg.sender, _amount, _collateralAmnt);
}
}
| Allows the admin to withdraw collateral above the threshold _amount the amount of collateral token to deposit/ slither-disable-next-line reentrancy-events | function withdrawCollateral(uint256 _amount) external onlyAdmin {
require(
collateralToken.transfer(msg.sender, _amount),
"collateral transfer fails"
);
uint256 _cRatio = collateralRatio();
require(
_cRatio >= collateralThreshold,
"collateral utilization below the threshold"
);
emit WithdrawCollateral(msg.sender, _amount, _cRatio);
}
| 6,418,389 |
./partial_match/1/0x235b25f9f56B39eFD8293C0d2A9Ee70719E25B85/sources/src/ButtonswapPair.sol | @inheritdoc IButtonswapPair/ | function setMovingAverageWindow(uint32 newMovingAverageWindow) external onlyFactory {
movingAverageWindow = newMovingAverageWindow;
emit MovingAverageWindowUpdated(newMovingAverageWindow);
}
| 4,108,389 |
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
interface IWeth {
function DEPOSIT413() external payable; //inject NONSTANDARD NAMING
function WITHDRAW1000(uint256 wad) external; //inject NONSTANDARD NAMING
}
contract IERC20 {
string public name;
uint8 public decimals;
string public symbol;
function TOTALSUPPLY320() public view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF760(address _who) public view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE148(address _owner, address _spender) public view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE600(address _spender, uint256 _value) public returns (bool); //inject NONSTANDARD NAMING
function TRANSFER238(address _to, uint256 _value) public returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM597(address _from, address _to, uint256 _value) public returns (bool); //inject NONSTANDARD NAMING
event TRANSFER322(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL667(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract IWethERC20 is IWeth, IERC20 {}
contract Constants {
uint256 internal constant wei_precision427 = 10**18; //inject NONSTANDARD NAMING
uint256 internal constant wei_percent_precision736 = 10**20; //inject NONSTANDARD NAMING
uint256 internal constant days_in_a_year553 = 365; //inject NONSTANDARD NAMING
uint256 internal constant one_month196 = 2628000; // approx. seconds in a month //inject NONSTANDARD NAMING
string internal constant userrewardsid759 = "UserRewards"; //inject NONSTANDARD NAMING
IWethERC20 public constant wethtoken696 = IWethERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); //inject NONSTANDARD NAMING
address public constant bzrxtokenaddress831 = 0x56d811088235F11C8920698a204A5010a788f4b3; //inject NONSTANDARD NAMING
address public constant vbzrxtokenaddress602 = 0xB72B31907C1C95F3650b64b2469e08EdACeE5e8F; //inject NONSTANDARD NAMING
}
library EnumerableBytes32Set {
struct Bytes32Set {
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) index;
bytes32[] values;
}
function ADDADDRESS118(Bytes32Set storage set, address addrvalue) //inject NONSTANDARD NAMING
internal
returns (bool)
{
bytes32 value;
assembly {
value := addrvalue
}
return ADDBYTES32720(set, value);
}
function ADDBYTES32720(Bytes32Set storage set, bytes32 value) //inject NONSTANDARD NAMING
internal
returns (bool)
{
if (!CONTAINS194(set, value)){
set.index[value] = set.values.push(value);
return true;
} else {
return false;
}
}
function REMOVEADDRESS815(Bytes32Set storage set, address addrvalue) //inject NONSTANDARD NAMING
internal
returns (bool)
{
bytes32 value;
assembly {
value := addrvalue
}
return REMOVEBYTES32129(set, value);
}
function REMOVEBYTES32129(Bytes32Set storage set, bytes32 value) //inject NONSTANDARD NAMING
internal
returns (bool)
{
if (CONTAINS194(set, value)){
uint256 toDeleteIndex = set.index[value] - 1;
uint256 lastIndex = set.values.length - 1;
// If the element we're deleting is the last one, we can just remove it without doing a swap
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set.values[lastIndex];
// Move the last value to the index where the deleted value is
set.values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set.index[lastValue] = toDeleteIndex + 1; // All indexes are 1-based
}
// Delete the index entry for the deleted value
delete set.index[value];
// Delete the old entry for the moved value
set.values.pop();
return true;
} else {
return false;
}
}
function CONTAINS194(Bytes32Set storage set, bytes32 value) //inject NONSTANDARD NAMING
internal
view
returns (bool)
{
return set.index[value] != 0;
}
function CONTAINSADDRESS180(Bytes32Set storage set, address addrvalue) //inject NONSTANDARD NAMING
internal
view
returns (bool)
{
bytes32 value;
assembly {
value := addrvalue
}
return set.index[value] != 0;
}
function ENUMERATE547(Bytes32Set storage set, uint256 start, uint256 count) //inject NONSTANDARD NAMING
internal
view
returns (bytes32[] memory output)
{
uint256 end = start + count;
require(end >= start, "addition overflow");
end = set.values.length < end ? set.values.length : end;
if (end == 0 || start >= end) {
return output;
}
output = new bytes32[](end-start);
for (uint256 i = start; i < end; i++) {
output[i-start] = set.values[i];
}
return output;
}
function LENGTH537(Bytes32Set storage set) //inject NONSTANDARD NAMING
internal
view
returns (uint256)
{
return set.values.length;
}
function GET436(Bytes32Set storage set, uint256 index) //inject NONSTANDARD NAMING
internal
view
returns (bytes32)
{
return set.values[index];
}
function GETADDRESS452(Bytes32Set storage set, uint256 index) //inject NONSTANDARD NAMING
internal
view
returns (address)
{
bytes32 value = set.values[index];
address addrvalue;
assembly {
addrvalue := value
}
return addrvalue;
}
}
contract ReentrancyGuard {
uint256 internal constant reentrancy_guard_free973 = 1; //inject NONSTANDARD NAMING
uint256 internal constant reentrancy_guard_locked356 = 2; //inject NONSTANDARD NAMING
uint256 internal reentrancyLock = reentrancy_guard_free973;
modifier NONREENTRANT587() { //inject NONSTANDARD NAMING
require(reentrancyLock == reentrancy_guard_free973, "nonReentrant");
reentrancyLock = reentrancy_guard_locked356;
_;
reentrancyLock = reentrancy_guard_free973;
}
}
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER414() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA879() internal view 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;
}
}
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED809(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER414();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED809(address(0), msgSender);
}
function OWNER514() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER855() { //inject NONSTANDARD NAMING
require(ISOWNER719(), "unauthorized");
_;
}
function ISOWNER719() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER414() == _owner;
}
function TRANSFEROWNERSHIP334(address newOwner) public ONLYOWNER855 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP592(newOwner);
}
function _TRANSFEROWNERSHIP592(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED809(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMath {
function ADD350(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB395(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB395(a, b, "SafeMath: subtraction overflow");
}
function SUB395(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 MUL0(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 DIV729(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV729(a, b, "SafeMath: division by zero");
}
function DIV729(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 DIVCEIL360(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIVCEIL360(a, b, "SafeMath: division by zero");
}
function DIVCEIL360(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);
if (a == 0) {
return 0;
}
uint256 c = ((a - 1) / b) + 1;
return c;
}
function MOD504(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD504(a, b, "SafeMath: modulo by zero");
}
function MOD504(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
function MIN256991(uint256 _a, uint256 _b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return _a < _b ? _a : _b;
}
}
library Address {
function ISCONTRACT390(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 TOPAYABLE724(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
function SENDVALUE363(address 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");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER502(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN109(token, abi.encodeWithSelector(token.TRANSFER238.selector, to, value));
}
function SAFETRANSFERFROM715(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN109(token, abi.encodeWithSelector(token.TRANSFERFROM597.selector, from, to, value));
}
function SAFEAPPROVE311(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.ALLOWANCE148(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN109(token, abi.encodeWithSelector(token.APPROVE600.selector, spender, value));
}
function SAFEINCREASEALLOWANCE505(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE148(address(this), spender).ADD350(value);
CALLOPTIONALRETURN109(token, abi.encodeWithSelector(token.APPROVE600.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE766(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE148(address(this), spender).SUB395(value, "SafeERC20: decreased allowance below zero");
CALLOPTIONALRETURN109(token, abi.encodeWithSelector(token.APPROVE600.selector, spender, newAllowance));
}
function CALLOPTIONALRETURN109(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).ISCONTRACT390(), "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 LoanStruct {
struct Loan {
bytes32 id; // id of the loan
bytes32 loanParamsId; // the linked loan params id
bytes32 pendingTradesId; // the linked pending trades id
uint256 principal; // total borrowed amount outstanding
uint256 collateral; // total collateral escrowed for the loan
uint256 startTimestamp; // loan start time
uint256 endTimestamp; // for active loans, this is the expected loan end time, for in-active loans, is the actual (past) end time
uint256 startMargin; // initial margin when the loan opened
uint256 startRate; // reference rate when the loan opened for converting collateralToken to loanToken
address borrower; // borrower of this loan
address lender; // lender of this loan
bool active; // if false, the loan has been fully closed
}
}
contract LoanParamsStruct {
struct LoanParams {
bytes32 id; // id of loan params object
bool active; // if false, this object has been disabled by the owner and can't be used for future loans
address owner; // owner of this object
address loanToken; // the token being loaned
address collateralToken; // the required collateral token
uint256 minInitialMargin; // the minimum allowed initial margin
uint256 maintenanceMargin; // an unhealthy loan when current margin is at or below this value
uint256 maxLoanTerm; // the maximum term for new loans (0 means there's no max term)
}
}
contract OrderStruct {
struct Order {
uint256 lockedAmount; // escrowed amount waiting for a counterparty
uint256 interestRate; // interest rate defined by the creator of this order
uint256 minLoanTerm; // minimum loan term allowed
uint256 maxLoanTerm; // maximum loan term allowed
uint256 createdTimestamp; // timestamp when this order was created
uint256 expirationTimestamp; // timestamp when this order expires
}
}
contract LenderInterestStruct {
struct LenderInterest {
uint256 principalTotal; // total borrowed amount outstanding of asset
uint256 owedPerDay; // interest owed per day for all loans of asset
uint256 owedTotal; // total interest owed for all loans of asset (assuming they go to full term)
uint256 paidTotal; // total interest paid so far for asset
uint256 updatedTimestamp; // last update
}
}
contract LoanInterestStruct {
struct LoanInterest {
uint256 owedPerDay; // interest owed per day for loan
uint256 depositTotal; // total escrowed interest for loan
uint256 updatedTimestamp; // last update
}
}
contract Objects is
LoanStruct,
LoanParamsStruct,
OrderStruct,
LenderInterestStruct,
LoanInterestStruct
{}
contract State is Constants, Objects, ReentrancyGuard, Ownable {
using SafeMath for uint256;
using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;
address public priceFeeds; // handles asset reference price lookups
address public swapsImpl; // handles asset swaps using dex liquidity
mapping (bytes4 => address) public logicTargets; // implementations of protocol functions
mapping (bytes32 => Loan) public loans; // loanId => Loan
mapping (bytes32 => LoanParams) public loanParams; // loanParamsId => LoanParams
mapping (address => mapping (bytes32 => Order)) public lenderOrders; // lender => orderParamsId => Order
mapping (address => mapping (bytes32 => Order)) public borrowerOrders; // borrower => orderParamsId => Order
mapping (bytes32 => mapping (address => bool)) public delegatedManagers; // loanId => delegated => approved
// Interest
mapping (address => mapping (address => LenderInterest)) public lenderInterest; // lender => loanToken => LenderInterest object
mapping (bytes32 => LoanInterest) public loanInterest; // loanId => LoanInterest object
// Internals
EnumerableBytes32Set.Bytes32Set internal logicTargetsSet; // implementations set
EnumerableBytes32Set.Bytes32Set internal activeLoansSet; // active loans set
mapping (address => EnumerableBytes32Set.Bytes32Set) internal lenderLoanSets; // lender loans set
mapping (address => EnumerableBytes32Set.Bytes32Set) internal borrowerLoanSets; // borrow loans set
mapping (address => EnumerableBytes32Set.Bytes32Set) internal userLoanParamSets; // user loan params set
address public feesController; // address controlling fee withdrawals
uint256 public lendingFeePercent = 10 ether; // 10% fee // fee taken from lender interest payments
mapping (address => uint256) public lendingFeeTokensHeld; // total interest fees received and not withdrawn per asset
mapping (address => uint256) public lendingFeeTokensPaid; // total interest fees withdraw per asset (lifetime fees = lendingFeeTokensHeld + lendingFeeTokensPaid)
uint256 public tradingFeePercent = 0.15 ether; // 0.15% fee // fee paid for each trade
mapping (address => uint256) public tradingFeeTokensHeld; // total trading fees received and not withdrawn per asset
mapping (address => uint256) public tradingFeeTokensPaid; // total trading fees withdraw per asset (lifetime fees = tradingFeeTokensHeld + tradingFeeTokensPaid)
uint256 public borrowingFeePercent = 0.09 ether; // 0.09% fee // origination fee paid for each loan
mapping (address => uint256) public borrowingFeeTokensHeld; // total borrowing fees received and not withdrawn per asset
mapping (address => uint256) public borrowingFeeTokensPaid; // total borrowing fees withdraw per asset (lifetime fees = borrowingFeeTokensHeld + borrowingFeeTokensPaid)
uint256 public protocolTokenHeld; // current protocol token deposit balance
uint256 public protocolTokenPaid; // lifetime total payout of protocol token
uint256 public affiliateFeePercent = 30 ether; // 30% fee share // fee share for affiliate program
mapping (address => mapping (address => uint256)) public liquidationIncentivePercent; // percent discount on collateral for liquidators per loanToken and collateralToken
mapping (address => address) public loanPoolToUnderlying; // loanPool => underlying
mapping (address => address) public underlyingToLoanPool; // underlying => loanPool
EnumerableBytes32Set.Bytes32Set internal loanPoolsSet; // loan pools set
mapping (address => bool) public supportedTokens; // supported tokens for swaps
uint256 public maxDisagreement = 5 ether; // % disagreement between swap rate and reference rate
uint256 public sourceBufferPercent = 5 ether; // used to estimate kyber swap source amount
uint256 public maxSwapSize = 1500 ether; // maximum supported swap size in ETH
function _SETTARGET405( //inject NONSTANDARD NAMING
bytes4 sig,
address target)
internal
{
logicTargets[sig] = target;
if (target != address(0)) {
logicTargetsSet.ADDBYTES32720(bytes32(sig));
} else {
logicTargetsSet.REMOVEBYTES32129(bytes32(sig));
}
}
}
interface IPriceFeeds {
function QUERYRATE923( //inject NONSTANDARD NAMING
address sourceToken,
address destToken)
external
view
returns (uint256 rate, uint256 precision);
function QUERYPRECISION662( //inject NONSTANDARD NAMING
address sourceToken,
address destToken)
external
view
returns (uint256 precision);
function QUERYRETURN272( //inject NONSTANDARD NAMING
address sourceToken,
address destToken,
uint256 sourceAmount)
external
view
returns (uint256 destAmount);
function CHECKPRICEDISAGREEMENT80( //inject NONSTANDARD NAMING
address sourceToken,
address destToken,
uint256 sourceAmount,
uint256 destAmount,
uint256 maxSlippage)
external
view
returns (uint256 sourceToDestSwapRate);
function AMOUNTINETH718( //inject NONSTANDARD NAMING
address Token,
uint256 amount)
external
view
returns (uint256 ethAmount);
function GETMAXDRAWDOWN818( //inject NONSTANDARD NAMING
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount,
uint256 maintenanceMargin)
external
view
returns (uint256);
function GETCURRENTMARGINANDCOLLATERALSIZE534( //inject NONSTANDARD NAMING
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount)
external
view
returns (uint256 currentMargin, uint256 collateralInEthAmount);
function GETCURRENTMARGIN887( //inject NONSTANDARD NAMING
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount)
external
view
returns (uint256 currentMargin, uint256 collateralToLoanRate);
function SHOULDLIQUIDATE902( //inject NONSTANDARD NAMING
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount,
uint256 maintenanceMargin)
external
view
returns (bool);
function GETFASTGASPRICE944( //inject NONSTANDARD NAMING
address payToken)
external
view
returns (uint256);
}
contract FeesEvents {
event PAYLENDINGFEE908( //inject NONSTANDARD NAMING
address indexed payer,
address indexed token,
uint256 amount
);
event PAYTRADINGFEE956( //inject NONSTANDARD NAMING
address indexed payer,
address indexed token,
bytes32 indexed loanId,
uint256 amount
);
event PAYBORROWINGFEE80( //inject NONSTANDARD NAMING
address indexed payer,
address indexed token,
bytes32 indexed loanId,
uint256 amount
);
event EARNREWARD21( //inject NONSTANDARD NAMING
address indexed receiver,
address indexed token,
bytes32 indexed loanId,
uint256 amount
);
}
contract FeesHelper is State, FeesEvents {
using SafeERC20 for IERC20;
// calculate trading fee
function _GETTRADINGFEE787( //inject NONSTANDARD NAMING
uint256 feeTokenAmount)
internal
view
returns (uint256)
{
return feeTokenAmount
.MUL0(tradingFeePercent)
.DIVCEIL360(wei_percent_precision736);
}
// calculate loan origination fee
function _GETBORROWINGFEE631( //inject NONSTANDARD NAMING
uint256 feeTokenAmount)
internal
view
returns (uint256)
{
return feeTokenAmount
.MUL0(borrowingFeePercent)
.DIVCEIL360(wei_percent_precision736);
}
// settle trading fee
function _PAYTRADINGFEE747( //inject NONSTANDARD NAMING
address user,
bytes32 loanId,
address feeToken,
uint256 tradingFee)
internal
{
if (tradingFee != 0) {
tradingFeeTokensHeld[feeToken] = tradingFeeTokensHeld[feeToken]
.ADD350(tradingFee);
emit PAYTRADINGFEE956(
user,
feeToken,
loanId,
tradingFee
);
_PAYFEEREWARD533(
user,
loanId,
feeToken,
tradingFee
);
}
}
// settle loan origination fee
function _PAYBORROWINGFEE445( //inject NONSTANDARD NAMING
address user,
bytes32 loanId,
address feeToken,
uint256 borrowingFee)
internal
{
if (borrowingFee != 0) {
borrowingFeeTokensHeld[feeToken] = borrowingFeeTokensHeld[feeToken]
.ADD350(borrowingFee);
emit PAYBORROWINGFEE80(
user,
feeToken,
loanId,
borrowingFee
);
_PAYFEEREWARD533(
user,
loanId,
feeToken,
borrowingFee
);
}
}
// settle lender (interest) fee
function _PAYLENDINGFEE461( //inject NONSTANDARD NAMING
address user,
address feeToken,
uint256 lendingFee)
internal
{
if (lendingFee != 0) {
lendingFeeTokensHeld[feeToken] = lendingFeeTokensHeld[feeToken]
.ADD350(lendingFee);
emit PAYLENDINGFEE908(
user,
feeToken,
lendingFee
);
}
}
// settles and pays borrowers based on the fees generated by their interest payments
function _SETTLEFEEREWARDFORINTERESTEXPENSE273( //inject NONSTANDARD NAMING
LoanInterest storage loanInterestLocal,
bytes32 loanId,
address feeToken,
address user,
uint256 interestTime)
internal
{
uint256 updatedTimestamp = loanInterestLocal.updatedTimestamp;
uint256 interestExpenseFee;
if (updatedTimestamp != 0) {
// this represents the fee generated by a borrower's interest payment
interestExpenseFee = interestTime
.SUB395(updatedTimestamp)
.MUL0(loanInterestLocal.owedPerDay)
.MUL0(lendingFeePercent)
.DIV729(1 days * wei_percent_precision736);
}
loanInterestLocal.updatedTimestamp = interestTime;
if (interestExpenseFee != 0) {
_PAYFEEREWARD533(
user,
loanId,
feeToken,
interestExpenseFee
);
}
}
// pay protocolToken reward to user
function _PAYFEEREWARD533( //inject NONSTANDARD NAMING
address user,
bytes32 loanId,
address feeToken,
uint256 feeAmount)
internal
{
// The protocol is designed to allow positions and loans to be closed, if for whatever reason
// the price lookup is failing, returning 0, or is otherwise paused. Therefore, we allow this
// call to fail silently, rather than revert, to allow the transaction to continue without a
// BZRX token reward.
uint256 rewardAmount;
address _priceFeeds = priceFeeds;
(bool success, bytes memory data) = _priceFeeds.staticcall(
abi.encodeWithSelector(
IPriceFeeds(_priceFeeds).QUERYRETURN272.selector,
feeToken,
bzrxtokenaddress831, // price rewards using BZRX price rather than vesting token price
feeAmount / 2 // 50% of fee value
)
);
assembly {
if eq(success, 1) {
rewardAmount := mload(add(data, 32))
}
}
if (rewardAmount != 0) {
uint256 tokenBalance = protocolTokenHeld;
if (rewardAmount > tokenBalance) {
rewardAmount = tokenBalance;
}
if (rewardAmount != 0) {
protocolTokenHeld = tokenBalance
.SUB395(rewardAmount);
bytes32 slot = keccak256(abi.encodePacked(user, userrewardsid759));
assembly {
sstore(slot, add(sload(slot), rewardAmount))
}
emit EARNREWARD21(
user,
vbzrxtokenaddress602, // rewardToken
loanId,
rewardAmount
);
}
}
}
}
contract VaultController is Constants {
using SafeERC20 for IERC20;
event VAULTDEPOSIT514( //inject NONSTANDARD NAMING
address indexed asset,
address indexed from,
uint256 amount
);
event VAULTWITHDRAW726( //inject NONSTANDARD NAMING
address indexed asset,
address indexed to,
uint256 amount
);
function VAULTETHERDEPOSIT545( //inject NONSTANDARD NAMING
address from,
uint256 value)
internal
{
IWethERC20 _wethToken = wethtoken696;
_wethToken.DEPOSIT413.value(value)();
emit VAULTDEPOSIT514(
address(_wethToken),
from,
value
);
}
function VAULTETHERWITHDRAW1( //inject NONSTANDARD NAMING
address to,
uint256 value)
internal
{
if (value != 0) {
IWethERC20 _wethToken = wethtoken696;
uint256 balance = address(this).balance;
if (value > balance) {
_wethToken.WITHDRAW1000(value - balance);
}
Address.SENDVALUE363(to, value);
emit VAULTWITHDRAW726(
address(_wethToken),
to,
value
);
}
}
function VAULTDEPOSIT722( //inject NONSTANDARD NAMING
address token,
address from,
uint256 value)
internal
{
if (value != 0) {
IERC20(token).SAFETRANSFERFROM715(
from,
address(this),
value
);
emit VAULTDEPOSIT514(
token,
from,
value
);
}
}
function VAULTWITHDRAW131( //inject NONSTANDARD NAMING
address token,
address to,
uint256 value)
internal
{
if (value != 0) {
IERC20(token).SAFETRANSFER502(
to,
value
);
emit VAULTWITHDRAW726(
token,
to,
value
);
}
}
function VAULTTRANSFER888( //inject NONSTANDARD NAMING
address token,
address from,
address to,
uint256 value)
internal
{
if (value != 0) {
if (from == address(this)) {
IERC20(token).SAFETRANSFER502(
to,
value
);
} else {
IERC20(token).SAFETRANSFERFROM715(
from,
to,
value
);
}
}
}
function VAULTAPPROVE996( //inject NONSTANDARD NAMING
address token,
address to,
uint256 value)
internal
{
if (value != 0 && IERC20(token).ALLOWANCE148(address(this), to) != 0) {
IERC20(token).SAFEAPPROVE311(to, 0);
}
IERC20(token).SAFEAPPROVE311(to, value);
}
}
contract InterestUser is State, VaultController, FeesHelper {
using SafeERC20 for IERC20;
function _PAYINTEREST683( //inject NONSTANDARD NAMING
address lender,
address interestToken)
internal
{
LenderInterest storage lenderInterestLocal = lenderInterest[lender][interestToken];
uint256 interestOwedNow = 0;
if (lenderInterestLocal.owedPerDay != 0 && lenderInterestLocal.updatedTimestamp != 0) {
interestOwedNow = block.timestamp
.SUB395(lenderInterestLocal.updatedTimestamp)
.MUL0(lenderInterestLocal.owedPerDay)
.DIV729(1 days);
lenderInterestLocal.updatedTimestamp = block.timestamp;
if (interestOwedNow > lenderInterestLocal.owedTotal)
interestOwedNow = lenderInterestLocal.owedTotal;
if (interestOwedNow != 0) {
lenderInterestLocal.paidTotal = lenderInterestLocal.paidTotal
.ADD350(interestOwedNow);
lenderInterestLocal.owedTotal = lenderInterestLocal.owedTotal
.SUB395(interestOwedNow);
_PAYINTERESTTRANSFER995(
lender,
interestToken,
interestOwedNow
);
}
} else {
lenderInterestLocal.updatedTimestamp = block.timestamp;
}
}
function _PAYINTERESTTRANSFER995( //inject NONSTANDARD NAMING
address lender,
address interestToken,
uint256 interestOwedNow)
internal
{
uint256 lendingFee = interestOwedNow
.MUL0(lendingFeePercent)
.DIVCEIL360(wei_percent_precision736);
_PAYLENDINGFEE461(
lender,
interestToken,
lendingFee
);
// transfers the interest to the lender, less the interest fee
VAULTWITHDRAW131(
interestToken,
lender,
interestOwedNow
.SUB395(lendingFee)
);
}
}
contract LiquidationHelper is State {
function _GETLIQUIDATIONAMOUNTS758( //inject NONSTANDARD NAMING
uint256 principal,
uint256 collateral,
uint256 currentMargin,
uint256 maintenanceMargin,
uint256 collateralToLoanRate,
uint256 incentivePercent)
internal
pure
returns (uint256 maxLiquidatable, uint256 maxSeizable)
{
if (currentMargin > maintenanceMargin || collateralToLoanRate == 0) {
return (maxLiquidatable, maxSeizable);
} else if (currentMargin <= incentivePercent) {
return (principal, collateral);
}
uint256 desiredMargin = maintenanceMargin
.ADD350(5 ether); // 5 percentage points above maintenance
// maxLiquidatable = ((1 + desiredMargin)*principal - collateralToLoanRate*collateral) / (desiredMargin - incentivePercent)
maxLiquidatable = desiredMargin
.ADD350(wei_percent_precision736)
.MUL0(principal)
.DIV729(wei_percent_precision736);
maxLiquidatable = maxLiquidatable
.SUB395(
collateral
.MUL0(collateralToLoanRate)
.DIV729(wei_precision427)
);
maxLiquidatable = maxLiquidatable
.MUL0(wei_percent_precision736)
.DIV729(
desiredMargin
.SUB395(incentivePercent)
);
if (maxLiquidatable > principal) {
maxLiquidatable = principal;
}
// maxSeizable = maxLiquidatable * (1 + incentivePercent) / collateralToLoanRate
maxSeizable = maxLiquidatable
.MUL0(
incentivePercent
.ADD350(wei_percent_precision736)
);
maxSeizable = maxSeizable
.DIV729(collateralToLoanRate)
.DIV729(100);
if (maxSeizable > collateral) {
maxSeizable = collateral;
}
return (maxLiquidatable, maxSeizable);
}
}
contract SwapsEvents {
event LOANSWAP63( //inject NONSTANDARD NAMING
bytes32 indexed loanId,
address indexed sourceToken,
address indexed destToken,
address borrower,
uint256 sourceAmount,
uint256 destAmount
);
event EXTERNALSWAP169( //inject NONSTANDARD NAMING
address indexed user,
address indexed sourceToken,
address indexed destToken,
uint256 sourceAmount,
uint256 destAmount
);
}
interface ISwapsImpl {
function DEXSWAP890( //inject NONSTANDARD NAMING
address sourceTokenAddress,
address destTokenAddress,
address receiverAddress,
address returnToSenderAddress,
uint256 minSourceTokenAmount,
uint256 maxSourceTokenAmount,
uint256 requiredDestTokenAmount)
external
returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed);
function DEXEXPECTEDRATE181( //inject NONSTANDARD NAMING
address sourceTokenAddress,
address destTokenAddress,
uint256 sourceTokenAmount)
external
view
returns (uint256);
}
contract SwapsUser is State, SwapsEvents, FeesHelper {
function _LOANSWAP802( //inject NONSTANDARD NAMING
bytes32 loanId,
address sourceToken,
address destToken,
address user,
uint256 minSourceTokenAmount,
uint256 maxSourceTokenAmount,
uint256 requiredDestTokenAmount,
bool bypassFee,
bytes memory loanDataBytes)
internal
returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed, uint256 sourceToDestSwapRate)
{
(destTokenAmountReceived, sourceTokenAmountUsed) = _SWAPSCALL433(
[
sourceToken,
destToken,
address(this), // receiver
address(this), // returnToSender
user
],
[
minSourceTokenAmount,
maxSourceTokenAmount,
requiredDestTokenAmount
],
loanId,
bypassFee,
loanDataBytes
);
// will revert if swap size too large
_CHECKSWAPSIZE456(sourceToken, sourceTokenAmountUsed);
// will revert if disagreement found
sourceToDestSwapRate = IPriceFeeds(priceFeeds).CHECKPRICEDISAGREEMENT80(
sourceToken,
destToken,
sourceTokenAmountUsed,
destTokenAmountReceived,
maxDisagreement
);
emit LOANSWAP63(
loanId,
sourceToken,
destToken,
user,
sourceTokenAmountUsed,
destTokenAmountReceived
);
}
function _SWAPSCALL433( //inject NONSTANDARD NAMING
address[5] memory addrs,
uint256[3] memory vals,
bytes32 loanId,
bool miscBool, // bypassFee
bytes memory loanDataBytes)
internal
returns (uint256, uint256)
{
//addrs[0]: sourceToken
//addrs[1]: destToken
//addrs[2]: receiver
//addrs[3]: returnToSender
//addrs[4]: user
//vals[0]: minSourceTokenAmount
//vals[1]: maxSourceTokenAmount
//vals[2]: requiredDestTokenAmount
require(vals[0] != 0, "sourceAmount == 0");
uint256 destTokenAmountReceived;
uint256 sourceTokenAmountUsed;
uint256 tradingFee;
if (!miscBool) { // bypassFee
if (vals[2] == 0) {
// condition: vals[0] will always be used as sourceAmount
tradingFee = _GETTRADINGFEE787(vals[0]);
if (tradingFee != 0) {
_PAYTRADINGFEE747(
addrs[4], // user
loanId,
addrs[0], // sourceToken
tradingFee
);
vals[0] = vals[0]
.SUB395(tradingFee);
}
} else {
// condition: unknown sourceAmount will be used
tradingFee = _GETTRADINGFEE787(vals[2]);
if (tradingFee != 0) {
vals[2] = vals[2]
.ADD350(tradingFee);
}
}
}
if (vals[1] == 0) {
vals[1] = vals[0];
} else {
require(vals[0] <= vals[1], "min greater than max");
}
require(loanDataBytes.length == 0, "invalid state");
(destTokenAmountReceived, sourceTokenAmountUsed) = _SWAPSCALL_INTERNAL704(
addrs,
vals
);
if (vals[2] == 0) {
// there's no minimum destTokenAmount, but all of vals[0] (minSourceTokenAmount) must be spent, and amount spent can't exceed vals[0]
require(sourceTokenAmountUsed == vals[0], "swap too large to fill");
if (tradingFee != 0) {
sourceTokenAmountUsed = sourceTokenAmountUsed + tradingFee; // will never overflow
}
} else {
// there's a minimum destTokenAmount required, but sourceTokenAmountUsed won't be greater than vals[1] (maxSourceTokenAmount)
require(sourceTokenAmountUsed <= vals[1], "swap fill too large");
require(destTokenAmountReceived >= vals[2], "insufficient swap liquidity");
if (tradingFee != 0) {
_PAYTRADINGFEE747(
addrs[4], // user
loanId, // loanId,
addrs[1], // destToken
tradingFee
);
destTokenAmountReceived = destTokenAmountReceived - tradingFee; // will never overflow
}
}
return (destTokenAmountReceived, sourceTokenAmountUsed);
}
function _SWAPSCALL_INTERNAL704( //inject NONSTANDARD NAMING
address[5] memory addrs,
uint256[3] memory vals)
internal
returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed)
{
bytes memory data = abi.encodeWithSelector(
ISwapsImpl(swapsImpl).DEXSWAP890.selector,
addrs[0], // sourceToken
addrs[1], // destToken
addrs[2], // receiverAddress
addrs[3], // returnToSenderAddress
vals[0], // minSourceTokenAmount
vals[1], // maxSourceTokenAmount
vals[2] // requiredDestTokenAmount
);
bool success;
(success, data) = swapsImpl.delegatecall(data);
require(success, "swap failed");
(destTokenAmountReceived, sourceTokenAmountUsed) = abi.decode(data, (uint256, uint256));
}
function _SWAPSEXPECTEDRETURN731( //inject NONSTANDARD NAMING
address sourceToken,
address destToken,
uint256 sourceTokenAmount)
internal
view
returns (uint256)
{
uint256 tradingFee = _GETTRADINGFEE787(sourceTokenAmount);
if (tradingFee != 0) {
sourceTokenAmount = sourceTokenAmount
.SUB395(tradingFee);
}
uint256 sourceToDestRate = ISwapsImpl(swapsImpl).DEXEXPECTEDRATE181(
sourceToken,
destToken,
sourceTokenAmount
);
uint256 sourceToDestPrecision = IPriceFeeds(priceFeeds).QUERYPRECISION662(
sourceToken,
destToken
);
return sourceTokenAmount
.MUL0(sourceToDestRate)
.DIV729(sourceToDestPrecision);
}
function _CHECKSWAPSIZE456( //inject NONSTANDARD NAMING
address tokenAddress,
uint256 amount)
internal
view
{
uint256 _maxSwapSize = maxSwapSize;
if (_maxSwapSize != 0) {
uint256 amountInEth;
if (tokenAddress == address(wethtoken696)) {
amountInEth = amount;
} else {
amountInEth = IPriceFeeds(priceFeeds).AMOUNTINETH718(tokenAddress, amount);
}
require(amountInEth <= _maxSwapSize, "swap too large");
}
}
}
interface ILoanPool {
function TOKENPRICE528() //inject NONSTANDARD NAMING
external
view
returns (uint256 price);
function BORROWINTERESTRATE911() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function TOTALASSETSUPPLY606() //inject NONSTANDARD NAMING
external
view
returns (uint256);
}
contract ITokenHolderLike {
function BALANCEOF760(address _who) public view returns (uint256); //inject NONSTANDARD NAMING
function FREEUPTO522(uint256 value) public returns (uint256); //inject NONSTANDARD NAMING
function FREEFROMUPTO607(address from, uint256 value) public returns (uint256); //inject NONSTANDARD NAMING
}
contract GasTokenUser {
ITokenHolderLike constant public gastoken34 = ITokenHolderLike(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c); //inject NONSTANDARD NAMING
ITokenHolderLike constant public tokenholder491 = ITokenHolderLike(0x55Eb3DD3f738cfdda986B8Eff3fa784477552C61); //inject NONSTANDARD NAMING
modifier USESGASTOKEN390(address holder) { //inject NONSTANDARD NAMING
if (holder == address(0)) {
holder = address(tokenholder491);
}
if (gastoken34.BALANCEOF760(holder) != 0) {
uint256 gasCalcValue = gasleft();
_;
gasCalcValue = (_GASUSED486(gasCalcValue) + 14154) / 41947;
if (holder == address(tokenholder491)) {
tokenholder491.FREEUPTO522(
gasCalcValue
);
} else {
tokenholder491.FREEFROMUPTO607(
holder,
gasCalcValue
);
}
} else {
_;
}
}
function _GASUSED486( //inject NONSTANDARD NAMING
uint256 startingGas)
internal
view
returns (uint256)
{
return 21000 +
startingGas -
gasleft() +
16 *
msg.data.length;
}
}
contract LoanClosingsEvents {
event CLOSEWITHDEPOSIT137( //inject NONSTANDARD NAMING
address indexed user,
address indexed lender,
bytes32 indexed loanId,
address closer,
address loanToken,
address collateralToken,
uint256 repayAmount,
uint256 collateralWithdrawAmount,
uint256 collateralToLoanRate,
uint256 currentMargin
);
event CLOSEWITHSWAP232( //inject NONSTANDARD NAMING
address indexed user,
address indexed lender,
bytes32 indexed loanId,
address collateralToken,
address loanToken,
address closer,
uint256 positionCloseSize,
uint256 loanCloseAmount,
uint256 exitPrice, // one unit of collateralToken, denominated in loanToken
uint256 currentLeverage
);
event LIQUIDATE807( //inject NONSTANDARD NAMING
address indexed user,
address indexed liquidator,
bytes32 indexed loanId,
address lender,
address loanToken,
address collateralToken,
uint256 repayAmount,
uint256 collateralWithdrawAmount,
uint256 collateralToLoanRate,
uint256 currentMargin
);
event ROLLOVER791( //inject NONSTANDARD NAMING
address indexed user,
address indexed caller,
bytes32 indexed loanId,
address lender,
address loanToken,
address collateralToken,
uint256 collateralAmountUsed,
uint256 interestAmountAdded,
uint256 loanEndTimestamp,
uint256 gasRebate
);
}
contract LoanClosingsBase is State, LoanClosingsEvents, VaultController, InterestUser, GasTokenUser, SwapsUser, LiquidationHelper {
enum CloseTypes {
Deposit,
Swap,
Liquidation
}
function _LIQUIDATE208( //inject NONSTANDARD NAMING
bytes32 loanId,
address receiver,
uint256 closeAmount)
internal
returns (
uint256 loanCloseAmount,
uint256 seizedAmount,
address seizedToken
)
{
Loan memory loanLocal = loans[loanId];
require(loanLocal.active, "loan is closed");
LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId];
(uint256 currentMargin, uint256 collateralToLoanRate) = IPriceFeeds(priceFeeds).GETCURRENTMARGIN887(
loanParamsLocal.loanToken,
loanParamsLocal.collateralToken,
loanLocal.principal,
loanLocal.collateral
);
require(
currentMargin <= loanParamsLocal.maintenanceMargin,
"healthy position"
);
if (receiver == address(0)) {
receiver = msg.sender;
}
loanCloseAmount = closeAmount;
(uint256 maxLiquidatable, uint256 maxSeizable) = _GETLIQUIDATIONAMOUNTS758(
loanLocal.principal,
loanLocal.collateral,
currentMargin,
loanParamsLocal.maintenanceMargin,
collateralToLoanRate,
liquidationIncentivePercent[loanParamsLocal.loanToken][loanParamsLocal.collateralToken]
);
if (loanCloseAmount < maxLiquidatable) {
seizedAmount = maxSeizable
.MUL0(loanCloseAmount)
.DIV729(maxLiquidatable);
} else {
if (loanCloseAmount > maxLiquidatable) {
// adjust down the close amount to the max
loanCloseAmount = maxLiquidatable;
}
seizedAmount = maxSeizable;
}
require(loanCloseAmount != 0, "nothing to liquidate");
// liquidator deposits the principal being closed
_RETURNPRINCIPALWITHDEPOSIT767(
loanParamsLocal.loanToken,
address(this),
loanCloseAmount
);
// a portion of the principal is repaid to the lender out of interest refunded
uint256 loanCloseAmountLessInterest = _SETTLEINTERESTTOPRINCIPAL473(
loanLocal,
loanParamsLocal,
loanCloseAmount,
loanLocal.borrower
);
if (loanCloseAmount > loanCloseAmountLessInterest) {
// full interest refund goes to the borrower
_WITHDRAWASSET523(
loanParamsLocal.loanToken,
loanLocal.borrower,
loanCloseAmount - loanCloseAmountLessInterest
);
}
if (loanCloseAmountLessInterest != 0) {
// The lender always gets back an ERC20 (even WETH), so we call withdraw directly rather than
// use the _withdrawAsset helper function
VAULTWITHDRAW131(
loanParamsLocal.loanToken,
loanLocal.lender,
loanCloseAmountLessInterest
);
}
seizedToken = loanParamsLocal.collateralToken;
if (seizedAmount != 0) {
loanLocal.collateral = loanLocal.collateral
.SUB395(seizedAmount);
_WITHDRAWASSET523(
seizedToken,
receiver,
seizedAmount
);
}
_EMITCLOSINGEVENTS670(
loanParamsLocal,
loanLocal,
loanCloseAmount,
seizedAmount,
collateralToLoanRate,
0, // collateralToLoanSwapRate
currentMargin,
CloseTypes.Liquidation
);
_CLOSELOAN770(
loanLocal,
loanCloseAmount
);
}
function _ROLLOVER360( //inject NONSTANDARD NAMING
bytes32 loanId,
uint256 startingGas,
bytes memory loanDataBytes)
internal
{
Loan memory loanLocal = loans[loanId];
require(loanLocal.active, "loan is closed");
require(
block.timestamp > loanLocal.endTimestamp.SUB395(1 hours),
"healthy position"
);
require(
loanPoolToUnderlying[loanLocal.lender] != address(0),
"invalid lender"
);
LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId];
// pay outstanding interest to lender
_PAYINTEREST683(
loanLocal.lender,
loanParamsLocal.loanToken
);
LoanInterest storage loanInterestLocal = loanInterest[loanLocal.id];
LenderInterest storage lenderInterestLocal = lenderInterest[loanLocal.lender][loanParamsLocal.loanToken];
_SETTLEFEEREWARDFORINTERESTEXPENSE273(
loanInterestLocal,
loanLocal.id,
loanParamsLocal.loanToken,
loanLocal.borrower,
block.timestamp
);
// Handle back interest: calculates interest owned since the loan endtime passed but the loan remained open
uint256 backInterestTime;
uint256 backInterestOwed;
if (block.timestamp > loanLocal.endTimestamp) {
backInterestTime = block.timestamp
.SUB395(loanLocal.endTimestamp);
backInterestOwed = backInterestTime
.MUL0(loanInterestLocal.owedPerDay);
backInterestOwed = backInterestOwed
.DIV729(24 hours);
}
uint256 maxDuration = loanParamsLocal.maxLoanTerm;
if (maxDuration != 0) {
// fixed-term loan, so need to query iToken for latest variable rate
uint256 owedPerDay = loanLocal.principal
.MUL0(ILoanPool(loanLocal.lender).BORROWINTERESTRATE911())
.DIV729(days_in_a_year553 * wei_percent_precision736);
lenderInterestLocal.owedPerDay = lenderInterestLocal.owedPerDay
.ADD350(owedPerDay);
lenderInterestLocal.owedPerDay = lenderInterestLocal.owedPerDay
.SUB395(loanInterestLocal.owedPerDay);
loanInterestLocal.owedPerDay = owedPerDay;
} else {
// loanInterestLocal.owedPerDay doesn't change
maxDuration = one_month196;
}
if (backInterestTime >= maxDuration) {
maxDuration = backInterestTime
.ADD350(24 hours); // adds an extra 24 hours
}
// update loan end time
loanLocal.endTimestamp = loanLocal.endTimestamp
.ADD350(maxDuration);
uint256 interestAmountRequired = loanLocal.endTimestamp
.SUB395(block.timestamp);
interestAmountRequired = interestAmountRequired
.MUL0(loanInterestLocal.owedPerDay);
interestAmountRequired = interestAmountRequired
.DIV729(24 hours);
loanInterestLocal.depositTotal = loanInterestLocal.depositTotal
.ADD350(interestAmountRequired);
lenderInterestLocal.owedTotal = lenderInterestLocal.owedTotal
.ADD350(interestAmountRequired);
// add backInterestOwed
interestAmountRequired = interestAmountRequired
.ADD350(backInterestOwed);
// collect interest
(,uint256 sourceTokenAmountUsed,) = _DOCOLLATERALSWAP473(
loanLocal,
loanParamsLocal,
loanLocal.collateral,
interestAmountRequired,
true, // returnTokenIsCollateral
loanDataBytes
);
loanLocal.collateral = loanLocal.collateral
.SUB395(sourceTokenAmountUsed);
if (backInterestOwed != 0) {
// pay out backInterestOwed
_PAYINTERESTTRANSFER995(
loanLocal.lender,
loanParamsLocal.loanToken,
backInterestOwed
);
}
uint256 gasRebate = _GETREBATE222(
loanLocal,
loanParamsLocal,
startingGas
);
if (gasRebate != 0) {
// pay out gas rebate to caller
// the preceeding logic should ensure gasRebate <= collateral, but just in case, will use SafeMath here
loanLocal.collateral = loanLocal.collateral
.SUB395(gasRebate, "gasRebate too high");
_WITHDRAWASSET523(
loanParamsLocal.collateralToken,
msg.sender,
gasRebate
);
}
_ROLLOVEREVENT507(
loanLocal,
loanParamsLocal,
sourceTokenAmountUsed,
interestAmountRequired,
gasRebate
);
loans[loanId] = loanLocal;
}
function _CLOSEWITHDEPOSIT462( //inject NONSTANDARD NAMING
bytes32 loanId,
address receiver,
uint256 depositAmount) // denominated in loanToken
internal
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
)
{
require(depositAmount != 0, "depositAmount == 0");
Loan memory loanLocal = loans[loanId];
_CHECKAUTHORIZED85(
loanLocal.id,
loanLocal.active,
loanLocal.borrower
);
if (receiver == address(0)) {
receiver = msg.sender;
}
LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId];
// can't close more than the full principal
loanCloseAmount = depositAmount > loanLocal.principal ?
loanLocal.principal :
depositAmount;
uint256 loanCloseAmountLessInterest = _SETTLEINTERESTTOPRINCIPAL473(
loanLocal,
loanParamsLocal,
loanCloseAmount,
receiver
);
if (loanCloseAmountLessInterest != 0) {
_RETURNPRINCIPALWITHDEPOSIT767(
loanParamsLocal.loanToken,
loanLocal.lender,
loanCloseAmountLessInterest
);
}
uint256 withdrawAmount;
if (loanCloseAmount == loanLocal.principal) {
// collateral is only withdrawn if the loan is closed in full
withdrawAmount = loanLocal.collateral;
withdrawToken = loanParamsLocal.collateralToken;
loanLocal.collateral = 0;
_WITHDRAWASSET523(
withdrawToken,
receiver,
withdrawAmount
);
}
_FINALIZECLOSE273(
loanLocal,
loanParamsLocal,
loanCloseAmount,
withdrawAmount, // collateralCloseAmount
0, // collateralToLoanSwapRate
CloseTypes.Deposit
);
}
function _CLOSEWITHSWAP962( //inject NONSTANDARD NAMING
bytes32 loanId,
address receiver,
uint256 swapAmount,
bool returnTokenIsCollateral,
bytes memory loanDataBytes)
internal
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
)
{
require(swapAmount != 0, "swapAmount == 0");
Loan memory loanLocal = loans[loanId];
_CHECKAUTHORIZED85(
loanLocal.id,
loanLocal.active,
loanLocal.borrower
);
if (receiver == address(0)) {
receiver = msg.sender;
}
LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId];
if (swapAmount > loanLocal.collateral) {
swapAmount = loanLocal.collateral;
}
loanCloseAmount = loanLocal.principal;
if (swapAmount != loanLocal.collateral) {
loanCloseAmount = loanCloseAmount
.MUL0(swapAmount)
.DIV729(loanLocal.collateral);
}
require(loanCloseAmount != 0, "loanCloseAmount == 0");
uint256 loanCloseAmountLessInterest = _SETTLEINTERESTTOPRINCIPAL473(
loanLocal,
loanParamsLocal,
loanCloseAmount,
receiver
);
uint256 usedCollateral;
uint256 collateralToLoanSwapRate;
(usedCollateral, withdrawAmount, collateralToLoanSwapRate) = _COVERPRINCIPALWITHSWAP500(
loanLocal,
loanParamsLocal,
swapAmount,
loanCloseAmountLessInterest,
returnTokenIsCollateral,
loanDataBytes
);
if (loanCloseAmountLessInterest != 0) {
// Repays principal to lender
// The lender always gets back an ERC20 (even WETH), so we call withdraw directly rather than
// use the _withdrawAsset helper function
VAULTWITHDRAW131(
loanParamsLocal.loanToken,
loanLocal.lender,
loanCloseAmountLessInterest
);
}
if (usedCollateral != 0) {
loanLocal.collateral = loanLocal.collateral
.SUB395(usedCollateral);
}
withdrawToken = returnTokenIsCollateral ?
loanParamsLocal.collateralToken :
loanParamsLocal.loanToken;
if (withdrawAmount != 0) {
_WITHDRAWASSET523(
withdrawToken,
receiver,
withdrawAmount
);
}
_FINALIZECLOSE273(
loanLocal,
loanParamsLocal,
loanCloseAmount,
usedCollateral,
collateralToLoanSwapRate,
CloseTypes.Swap
);
}
function _CHECKAUTHORIZED85( //inject NONSTANDARD NAMING
bytes32 _id,
bool _active,
address _borrower)
internal
view
{
require(_active, "loan is closed");
require(
msg.sender == _borrower ||
delegatedManagers[_id][msg.sender],
"unauthorized"
);
}
function _SETTLEINTERESTTOPRINCIPAL473( //inject NONSTANDARD NAMING
Loan memory loanLocal,
LoanParams memory loanParamsLocal,
uint256 loanCloseAmount,
address receiver)
internal
returns (uint256)
{
uint256 loanCloseAmountLessInterest = loanCloseAmount;
uint256 interestRefundToBorrower = _SETTLEINTEREST436(
loanParamsLocal,
loanLocal,
loanCloseAmountLessInterest
);
uint256 interestAppliedToPrincipal;
if (loanCloseAmountLessInterest >= interestRefundToBorrower) {
// apply all of borrower interest refund torwards principal
interestAppliedToPrincipal = interestRefundToBorrower;
// principal needed is reduced by this amount
loanCloseAmountLessInterest -= interestRefundToBorrower;
// no interest refund remaining
interestRefundToBorrower = 0;
} else {
// principal fully covered by excess interest
interestAppliedToPrincipal = loanCloseAmountLessInterest;
// amount refunded is reduced by this amount
interestRefundToBorrower -= loanCloseAmountLessInterest;
// principal fully covered by excess interest
loanCloseAmountLessInterest = 0;
// refund overage
_WITHDRAWASSET523(
loanParamsLocal.loanToken,
receiver,
interestRefundToBorrower
);
}
if (interestAppliedToPrincipal != 0) {
// The lender always gets back an ERC20 (even WETH), so we call withdraw directly rather than
// use the _withdrawAsset helper function
VAULTWITHDRAW131(
loanParamsLocal.loanToken,
loanLocal.lender,
interestAppliedToPrincipal
);
}
return loanCloseAmountLessInterest;
}
// The receiver always gets back an ERC20 (even WETH)
function _RETURNPRINCIPALWITHDEPOSIT767( //inject NONSTANDARD NAMING
address loanToken,
address receiver,
uint256 principalNeeded)
internal
{
if (principalNeeded != 0) {
if (msg.value == 0) {
VAULTTRANSFER888(
loanToken,
msg.sender,
receiver,
principalNeeded
);
} else {
require(loanToken == address(wethtoken696), "wrong asset sent");
require(msg.value >= principalNeeded, "not enough ether");
wethtoken696.DEPOSIT413.value(principalNeeded)();
if (receiver != address(this)) {
VAULTTRANSFER888(
loanToken,
address(this),
receiver,
principalNeeded
);
}
if (msg.value > principalNeeded) {
// refund overage
Address.SENDVALUE363(
msg.sender,
msg.value - principalNeeded
);
}
}
} else {
require(msg.value == 0, "wrong asset sent");
}
}
function _COVERPRINCIPALWITHSWAP500( //inject NONSTANDARD NAMING
Loan memory loanLocal,
LoanParams memory loanParamsLocal,
uint256 swapAmount,
uint256 principalNeeded,
bool returnTokenIsCollateral,
bytes memory loanDataBytes)
internal
returns (uint256 usedCollateral, uint256 withdrawAmount, uint256 collateralToLoanSwapRate)
{
uint256 destTokenAmountReceived;
uint256 sourceTokenAmountUsed;
(destTokenAmountReceived, sourceTokenAmountUsed, collateralToLoanSwapRate) = _DOCOLLATERALSWAP473(
loanLocal,
loanParamsLocal,
swapAmount,
principalNeeded,
returnTokenIsCollateral,
loanDataBytes
);
if (returnTokenIsCollateral) {
if (destTokenAmountReceived > principalNeeded) {
// better fill than expected, so send excess to borrower
_WITHDRAWASSET523(
loanParamsLocal.loanToken,
loanLocal.borrower,
destTokenAmountReceived - principalNeeded
);
}
withdrawAmount = swapAmount > sourceTokenAmountUsed ?
swapAmount - sourceTokenAmountUsed :
0;
} else {
require(sourceTokenAmountUsed == swapAmount, "swap error");
withdrawAmount = destTokenAmountReceived - principalNeeded;
}
usedCollateral = sourceTokenAmountUsed > swapAmount ?
sourceTokenAmountUsed :
swapAmount;
}
function _DOCOLLATERALSWAP473( //inject NONSTANDARD NAMING
Loan memory loanLocal,
LoanParams memory loanParamsLocal,
uint256 swapAmount,
uint256 principalNeeded,
bool returnTokenIsCollateral,
bytes memory loanDataBytes)
internal
returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed, uint256 collateralToLoanSwapRate)
{
(destTokenAmountReceived, sourceTokenAmountUsed, collateralToLoanSwapRate) = _LOANSWAP802(
loanLocal.id,
loanParamsLocal.collateralToken,
loanParamsLocal.loanToken,
loanLocal.borrower,
swapAmount, // minSourceTokenAmount
loanLocal.collateral, // maxSourceTokenAmount
returnTokenIsCollateral ?
principalNeeded : // requiredDestTokenAmount
0,
false, // bypassFee
loanDataBytes
);
require(destTokenAmountReceived >= principalNeeded, "insufficient dest amount");
require(sourceTokenAmountUsed <= loanLocal.collateral, "excessive source amount");
}
// withdraws asset to receiver
function _WITHDRAWASSET523( //inject NONSTANDARD NAMING
address assetToken,
address receiver,
uint256 assetAmount)
internal
{
if (assetAmount != 0) {
if (assetToken == address(wethtoken696)) {
VAULTETHERWITHDRAW1(
receiver,
assetAmount
);
} else {
VAULTWITHDRAW131(
assetToken,
receiver,
assetAmount
);
}
}
}
function _FINALIZECLOSE273( //inject NONSTANDARD NAMING
Loan memory loanLocal,
LoanParams memory loanParamsLocal,
uint256 loanCloseAmount,
uint256 collateralCloseAmount,
uint256 collateralToLoanSwapRate,
CloseTypes closeType)
internal
{
_CLOSELOAN770(
loanLocal,
loanCloseAmount
);
address _priceFeeds = priceFeeds;
uint256 currentMargin;
uint256 collateralToLoanRate;
// this is still called even with full loan close to return collateralToLoanRate
(bool success, bytes memory data) = _priceFeeds.staticcall(
abi.encodeWithSelector(
IPriceFeeds(_priceFeeds).GETCURRENTMARGIN887.selector,
loanParamsLocal.loanToken,
loanParamsLocal.collateralToken,
loanLocal.principal,
loanLocal.collateral
)
);
assembly {
if eq(success, 1) {
currentMargin := mload(add(data, 32))
collateralToLoanRate := mload(add(data, 64))
}
}
require(
closeType == CloseTypes.Deposit ||
loanLocal.principal == 0 || // loan fully closed
currentMargin > loanParamsLocal.maintenanceMargin,
"unhealthy position"
);
_EMITCLOSINGEVENTS670(
loanParamsLocal,
loanLocal,
loanCloseAmount,
collateralCloseAmount,
collateralToLoanRate,
collateralToLoanSwapRate,
currentMargin,
closeType
);
}
function _CLOSELOAN770( //inject NONSTANDARD NAMING
Loan memory loanLocal,
uint256 loanCloseAmount)
internal
returns (uint256)
{
require(loanCloseAmount != 0, "nothing to close");
if (loanCloseAmount == loanLocal.principal) {
loanLocal.principal = 0;
loanLocal.active = false;
loanLocal.endTimestamp = block.timestamp;
loanLocal.pendingTradesId = 0;
activeLoansSet.REMOVEBYTES32129(loanLocal.id);
lenderLoanSets[loanLocal.lender].REMOVEBYTES32129(loanLocal.id);
borrowerLoanSets[loanLocal.borrower].REMOVEBYTES32129(loanLocal.id);
} else {
loanLocal.principal = loanLocal.principal
.SUB395(loanCloseAmount);
}
loans[loanLocal.id] = loanLocal;
}
function _SETTLEINTEREST436( //inject NONSTANDARD NAMING
LoanParams memory loanParamsLocal,
Loan memory loanLocal,
uint256 closePrincipal)
internal
returns (uint256)
{
// pay outstanding interest to lender
_PAYINTEREST683(
loanLocal.lender,
loanParamsLocal.loanToken
);
LoanInterest storage loanInterestLocal = loanInterest[loanLocal.id];
LenderInterest storage lenderInterestLocal = lenderInterest[loanLocal.lender][loanParamsLocal.loanToken];
uint256 interestTime = block.timestamp;
if (interestTime > loanLocal.endTimestamp) {
interestTime = loanLocal.endTimestamp;
}
_SETTLEFEEREWARDFORINTERESTEXPENSE273(
loanInterestLocal,
loanLocal.id,
loanParamsLocal.loanToken,
loanLocal.borrower,
interestTime
);
uint256 owedPerDayRefund;
if (closePrincipal < loanLocal.principal) {
owedPerDayRefund = loanInterestLocal.owedPerDay
.MUL0(closePrincipal)
.DIV729(loanLocal.principal);
} else {
owedPerDayRefund = loanInterestLocal.owedPerDay;
}
// update stored owedPerDay
loanInterestLocal.owedPerDay = loanInterestLocal.owedPerDay
.SUB395(owedPerDayRefund);
lenderInterestLocal.owedPerDay = lenderInterestLocal.owedPerDay
.SUB395(owedPerDayRefund);
// update borrower interest
uint256 interestRefundToBorrower = loanLocal.endTimestamp
.SUB395(interestTime);
interestRefundToBorrower = interestRefundToBorrower
.MUL0(owedPerDayRefund);
interestRefundToBorrower = interestRefundToBorrower
.DIV729(24 hours);
if (closePrincipal < loanLocal.principal) {
loanInterestLocal.depositTotal = loanInterestLocal.depositTotal
.SUB395(interestRefundToBorrower);
} else {
loanInterestLocal.depositTotal = 0;
}
// update remaining lender interest values
lenderInterestLocal.principalTotal = lenderInterestLocal.principalTotal
.SUB395(closePrincipal);
uint256 owedTotal = lenderInterestLocal.owedTotal;
lenderInterestLocal.owedTotal = owedTotal > interestRefundToBorrower ?
owedTotal - interestRefundToBorrower :
0;
return interestRefundToBorrower;
}
function _GETREBATE222( //inject NONSTANDARD NAMING
Loan memory loanLocal,
LoanParams memory loanParamsLocal,
uint256 startingGas)
internal
returns (uint256 gasRebate)
{
// the amount of collateral drop needed to reach the maintenanceMargin level of the loan
uint256 maxDrawdown = IPriceFeeds(priceFeeds).GETMAXDRAWDOWN818(
loanParamsLocal.loanToken,
loanParamsLocal.collateralToken,
loanLocal.principal,
loanLocal.collateral,
loanParamsLocal.maintenanceMargin
);
require(maxDrawdown != 0, "unhealthy position");
// gets the gas rebate denominated in collateralToken
gasRebate = SafeMath.MUL0(
IPriceFeeds(priceFeeds).GETFASTGASPRICE944(loanParamsLocal.collateralToken) * 2,
_GASUSED486(startingGas)
);
// ensures the gas rebate will not drop the current margin below the maintenance level
gasRebate = gasRebate
.MIN256991(maxDrawdown);
}
function _ROLLOVEREVENT507( //inject NONSTANDARD NAMING
Loan memory loanLocal,
LoanParams memory loanParamsLocal,
uint256 sourceTokenAmountUsed,
uint256 interestAmountRequired,
uint256 gasRebate)
internal
{
emit ROLLOVER791(
loanLocal.borrower, // user (borrower)
msg.sender, // caller
loanLocal.id, // loanId
loanLocal.lender, // lender
loanParamsLocal.loanToken, // loanToken
loanParamsLocal.collateralToken, // collateralToken
sourceTokenAmountUsed, // collateralAmountUsed
interestAmountRequired, // interestAmountAdded
loanLocal.endTimestamp, // loanEndTimestamp
gasRebate // gasRebate
);
}
function _EMITCLOSINGEVENTS670( //inject NONSTANDARD NAMING
LoanParams memory loanParamsLocal,
Loan memory loanLocal,
uint256 loanCloseAmount,
uint256 collateralCloseAmount,
uint256 collateralToLoanRate,
uint256 collateralToLoanSwapRate,
uint256 currentMargin,
CloseTypes closeType)
internal
{
if (closeType == CloseTypes.Deposit) {
emit CLOSEWITHDEPOSIT137(
loanLocal.borrower, // user (borrower)
loanLocal.lender, // lender
loanLocal.id, // loanId
msg.sender, // closer
loanParamsLocal.loanToken, // loanToken
loanParamsLocal.collateralToken, // collateralToken
loanCloseAmount, // loanCloseAmount
collateralCloseAmount, // collateralCloseAmount
collateralToLoanRate, // collateralToLoanRate
currentMargin // currentMargin
);
} else if (closeType == CloseTypes.Swap) {
// exitPrice = 1 / collateralToLoanSwapRate
if (collateralToLoanSwapRate != 0) {
collateralToLoanSwapRate = SafeMath.DIV729(wei_precision427 * wei_precision427, collateralToLoanSwapRate);
}
// currentLeverage = 100 / currentMargin
if (currentMargin != 0) {
currentMargin = SafeMath.DIV729(10**38, currentMargin);
}
emit CLOSEWITHSWAP232(
loanLocal.borrower, // user (trader)
loanLocal.lender, // lender
loanLocal.id, // loanId
loanParamsLocal.collateralToken, // collateralToken
loanParamsLocal.loanToken, // loanToken
msg.sender, // closer
collateralCloseAmount, // positionCloseSize
loanCloseAmount, // loanCloseAmount
collateralToLoanSwapRate, // exitPrice (1 / collateralToLoanSwapRate)
currentMargin // currentLeverage
);
} else { // closeType == CloseTypes.Liquidation
emit LIQUIDATE807(
loanLocal.borrower, // user (borrower)
msg.sender, // liquidator
loanLocal.id, // loanId
loanLocal.lender, // lender
loanParamsLocal.loanToken, // loanToken
loanParamsLocal.collateralToken, // collateralToken
loanCloseAmount, // loanCloseAmount
collateralCloseAmount, // collateralCloseAmount
collateralToLoanRate, // collateralToLoanRate
currentMargin // currentMargin
);
}
}
}
contract LoanClosingsWithGasToken is LoanClosingsBase {
function INITIALIZE821( //inject NONSTANDARD NAMING
address target)
external
ONLYOWNER855
{
_SETTARGET405(this.LIQUIDATEWITHGASTOKEN944.selector, target);
_SETTARGET405(this.ROLLOVERWITHGASTOKEN936.selector, target);
_SETTARGET405(this.CLOSEWITHDEPOSITWITHGASTOKEN57.selector, target);
_SETTARGET405(this.CLOSEWITHSWAPWITHGASTOKEN662.selector, target);
}
function LIQUIDATEWITHGASTOKEN944( //inject NONSTANDARD NAMING
bytes32 loanId,
address receiver,
address gasTokenUser,
uint256 closeAmount) // denominated in loanToken
external
payable
USESGASTOKEN390(gasTokenUser)
NONREENTRANT587
returns (
uint256 loanCloseAmount,
uint256 seizedAmount,
address seizedToken
)
{
return _LIQUIDATE208(
loanId,
receiver,
closeAmount
);
}
function ROLLOVERWITHGASTOKEN936( //inject NONSTANDARD NAMING
bytes32 loanId,
address gasTokenUser,
bytes calldata ) // for future use
external
USESGASTOKEN390(gasTokenUser)
NONREENTRANT587
{
uint256 startingGas = 21000 + gasleft() + 16 * msg.data.length;
// restrict to EOAs to prevent griefing attacks, during interest rate recalculation
require(msg.sender == tx.origin, "only EOAs can call");
return _ROLLOVER360(
loanId,
startingGas,
"" // loanDataBytes
);
}
function CLOSEWITHDEPOSITWITHGASTOKEN57( //inject NONSTANDARD NAMING
bytes32 loanId,
address receiver,
address gasTokenUser,
uint256 depositAmount) // denominated in loanToken
public
payable
USESGASTOKEN390(gasTokenUser)
NONREENTRANT587
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
)
{
return _CLOSEWITHDEPOSIT462(
loanId,
receiver,
depositAmount
);
}
function CLOSEWITHSWAPWITHGASTOKEN662( //inject NONSTANDARD NAMING
bytes32 loanId,
address receiver,
address gasTokenUser,
uint256 swapAmount, // denominated in collateralToken
bool returnTokenIsCollateral, // true: withdraws collateralToken, false: withdraws loanToken
bytes memory ) // for future use
public
USESGASTOKEN390(gasTokenUser)
NONREENTRANT587
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
)
{
return _CLOSEWITHSWAP962(
loanId,
receiver,
swapAmount,
returnTokenIsCollateral,
"" // loanDataBytes
);
}
} | inject NONSTANDARD NAMING | function SUB395(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { | 6,465,415 |
pragma solidity 0.5.17;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol";
import "./TokenStaking.sol";
import "./cryptography/BLS.sol";
import "./utils/AddressArrayUtils.sol";
import "./utils/PercentUtils.sol";
import "./libraries/operator/GroupSelection.sol";
import "./libraries/operator/Groups.sol";
import "./libraries/operator/DKGResultVerification.sol";
import "./libraries/operator/Reimbursements.sol";
interface ServiceContract {
function entryCreated(uint256 requestId, bytes calldata entry, address payable submitter) external;
function fundRequestSubsidyFeePool() external payable;
function fundDkgFeePool() external payable;
}
/**
* @title KeepRandomBeaconOperator
* @dev Keep client facing contract for random beacon security-critical operations.
* Handles group creation and expiration, BLS signature verification and incentives.
* The contract is not upgradeable. New functionality can be implemented by deploying
* new versions following Keep client update and re-authorization by the stakers.
*/
contract KeepRandomBeaconOperator is ReentrancyGuard {
using SafeMath for uint256;
using PercentUtils for uint256;
using AddressArrayUtils for address[];
using GroupSelection for GroupSelection.Storage;
using Groups for Groups.Storage;
using DKGResultVerification for DKGResultVerification.Storage;
event OnGroupRegistered(bytes groupPubKey);
event DkgResultSubmittedEvent(
uint256 memberIndex,
bytes groupPubKey,
bytes misbehaved
);
event RelayEntryRequested(bytes previousEntry, bytes groupPublicKey);
event RelayEntrySubmitted();
event GroupSelectionStarted(uint256 newEntry);
event GroupMemberRewardsWithdrawn(address indexed beneficiary, address operator, uint256 amount, uint256 groupIndex);
event RelayEntryTimeoutReported(uint256 indexed groupIndex);
event UnauthorizedSigningReported(uint256 indexed groupIndex);
GroupSelection.Storage groupSelection;
Groups.Storage groups;
DKGResultVerification.Storage dkgResultVerification;
// Contract owner.
address internal owner;
address[] internal serviceContracts;
// TODO: replace with a secure authorization protocol (addressed in RFC 11).
TokenStaking internal stakingContract;
// Each signing group member reward expressed in wei.
uint256 public groupMemberBaseReward = 145*1e11; // 14500 Gwei, 10% of operational cost
// Gas price ceiling value used to calculate the gas price for reimbursement
// next to the actual gas price from the transaction. We use gas price
// ceiling to defend against malicious miner-submitters who can manipulate
// transaction gas price.
uint256 public gasPriceCeiling = 30*1e9; // (30 Gwei = 30 * 10^9 wei)
// Size of a group in the threshold relay.
uint256 public groupSize = 64;
// Minimum number of group members needed to interact according to the
// protocol to produce a relay entry.
uint256 public groupThreshold = 33;
// Time in blocks after which the next group member is eligible
// to submit the result.
uint256 public resultPublicationBlockStep = 3;
// Timeout in blocks for a relay entry to appear on the chain. Blocks are
// counted from the moment relay request occur.
//
// Timeout is never shorter than the time needed by clients to generate
// relay entry and the time it takes for the last group member to become
// eligible to submit the result plus at least one block to submit it.
uint256 public relayEntryTimeout = groupSize.mul(resultPublicationBlockStep);
// Gas required to verify BLS signature and produce successful relay
// entry. Excludes callback and DKG gas. The worst case (most expensive)
// scenario.
uint256 public entryVerificationGasEstimate = 280000;
// Gas required to submit DKG result. Excludes initiation of group selection.
uint256 public dkgGasEstimate = 1740000;
// Gas required to trigger DKG (starting group selection).
uint256 public groupSelectionGasEstimate = 200000;
// Reimbursement for the submitter of the DKG result. This value is set when
// a new DKG request comes to the operator contract.
//
// When submitting DKG result, the submitter is reimbursed with the actual cost
// and some part of the fee stored in this field may be returned to the service
// contract.
uint256 public dkgSubmitterReimbursementFee;
uint256 internal currentEntryStartBlock;
// Seed value used for the genesis group selection.
// https://www.wolframalpha.com/input/?i=pi+to+78+digits
uint256 internal constant _genesisGroupSeed = 31415926535897932384626433832795028841971693993751058209749445923078164062862;
// Service contract that triggered current group selection.
ServiceContract internal groupSelectionStarterContract;
struct SigningRequest {
uint256 relayRequestId;
uint256 entryVerificationAndProfitFee;
uint256 callbackFee;
uint256 groupIndex;
bytes previousEntry;
address serviceContract;
}
SigningRequest internal signingRequest;
/**
* @dev Triggers the first group selection. Genesis can be called only when
* there are no groups on the operator contract.
*/
function genesis() public payable {
require(numberOfGroups() == 0, "Groups exist");
// Set latest added service contract as a group selection starter to receive any DKG fee surplus.
groupSelectionStarterContract = ServiceContract(serviceContracts[serviceContracts.length.sub(1)]);
startGroupSelection(_genesisGroupSeed, msg.value);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner == msg.sender, "Caller is not the owner");
_;
}
/**
* @dev Checks if sender is authorized.
*/
modifier onlyServiceContract() {
require(
serviceContracts.contains(msg.sender),
"Caller is not an authorized contract"
);
_;
}
constructor(address _serviceContract, address _stakingContract) public {
owner = msg.sender;
serviceContracts.push(_serviceContract);
stakingContract = TokenStaking(_stakingContract);
groups.stakingContract = TokenStaking(_stakingContract);
groups.groupActiveTime = TokenStaking(_stakingContract).undelegationPeriod();
// There are 39 blocks to submit group selection tickets. To minimize
// the submitter's cost by minimizing the number of redundant tickets
// that are not selected into the group, the following approach is
// recommended:
//
// Tickets are submitted in 11 rounds, each round taking 3 blocks.
// As the basic principle, the number of leading zeros in the ticket
// value is subtracted from the number of rounds to determine the round
// the ticket should be submitted in:
// - in round 0, tickets with 11 or more leading zeros are submitted
// - in round 1, tickets with 10 or more leading zeros are submitted
// (...)
// - in round 11, tickets with no leading zeros are submitted.
//
// In each round, group member candidate needs to monitor tickets
// submitted by other candidates and compare them against tickets of
// the candidate not yet submitted to determine if continuing with
// ticket submission still makes sense.
//
// After 33 blocks, there is a 6 blocks mining lag allowing all
// outstanding ticket submissions to have a higher chance of being
// mined before the deadline.
groupSelection.ticketSubmissionTimeout = 3 * 11 + 6;
groupSelection.groupSize = groupSize;
dkgResultVerification.timeDKG = 5*(1+5) + 2*(1+10) + 20;
dkgResultVerification.resultPublicationBlockStep = resultPublicationBlockStep;
dkgResultVerification.groupSize = groupSize;
// TODO: For now, the required number of signatures is equal to group
// threshold. This should be updated to keep a safety margin for
// participants misbehaving during signing.
dkgResultVerification.signatureThreshold = groupThreshold;
}
/**
* @dev Adds service contract
* @param serviceContract Address of the service contract.
*/
function addServiceContract(address serviceContract) public onlyOwner {
serviceContracts.push(serviceContract);
}
/**
* @dev Removes service contract
* @param serviceContract Address of the service contract.
*/
function removeServiceContract(address serviceContract) public onlyOwner {
serviceContracts.removeAddress(serviceContract);
}
/**
* @dev Triggers the selection process of a new candidate group.
* @param _newEntry New random beacon value that stakers will use to
* generate their tickets.
* @param submitter Operator of this contract.
*/
function createGroup(uint256 _newEntry, address payable submitter) public payable onlyServiceContract {
uint256 groupSelectionStartFee = groupSelectionGasEstimate.mul(gasPriceCeiling);
groupSelectionStarterContract = ServiceContract(msg.sender);
startGroupSelection(_newEntry, msg.value.sub(groupSelectionStartFee));
// reimbursing a submitter that triggered group selection
(bool success, ) = stakingContract.magpieOf(submitter).call.value(groupSelectionStartFee)("");
require(success, "Failed reimbursing submitter for starting a group selection");
}
function startGroupSelection(uint256 _newEntry, uint256 _payment) internal {
require(
_payment >= gasPriceCeiling.mul(dkgGasEstimate),
"Insufficient DKG fee"
);
require(isGroupSelectionPossible(), "Group selection in progress");
// If previous group selection failed and there is reimbursement left
// return it to the DKG fee pool.
if (dkgSubmitterReimbursementFee > 0) {
uint256 surplus = dkgSubmitterReimbursementFee;
dkgSubmitterReimbursementFee = 0;
ServiceContract(msg.sender).fundDkgFeePool.value(surplus)();
}
groupSelection.minimumStake = stakingContract.minimumStake();
groupSelection.start(_newEntry);
emit GroupSelectionStarted(_newEntry);
dkgSubmitterReimbursementFee = _payment;
}
function isGroupSelectionPossible() public view returns (bool) {
if (!groupSelection.inProgress) {
return true;
}
// dkgTimeout is the time after key generation protocol is expected to
// be complete plus the expected time to submit the result.
uint256 dkgTimeout = groupSelection.ticketSubmissionStartBlock +
groupSelection.ticketSubmissionTimeout +
dkgResultVerification.timeDKG +
groupSize * resultPublicationBlockStep;
return block.number > dkgTimeout;
}
/**
* @dev Submits ticket to request to participate in a new candidate group.
* @param ticket Bytes representation of a ticket that holds the following:
* - ticketValue: first 8 bytes of a result of keccak256 cryptography hash
* function on the combination of the group selection seed (previous
* beacon output), staker-specific value (address) and virtual staker index.
* - stakerValue: a staker-specific value which is the address of the staker.
* - virtualStakerIndex: 4-bytes number within a range of 1 to staker's weight;
* has to be unique for all tickets submitted by the given staker for the
* current candidate group selection.
*/
function submitTicket(bytes32 ticket) public {
uint256 stakingWeight = stakingContract.eligibleStake(msg.sender, address(this)).div(groupSelection.minimumStake);
groupSelection.submitTicket(ticket, stakingWeight);
}
/**
* @dev Gets the timeout in blocks after which group candidate ticket
* submission is finished.
*/
function ticketSubmissionTimeout() public view returns (uint256) {
return groupSelection.ticketSubmissionTimeout;
}
/**
* @dev Gets the submitted group candidate tickets so far.
*/
function submittedTickets() public view returns (uint64[] memory) {
return groupSelection.tickets;
}
/**
* @dev Gets selected participants in ascending order of their tickets.
*/
function selectedParticipants() public view returns (address[] memory) {
return groupSelection.selectedParticipants();
}
/**
* @dev Submits result of DKG protocol. It is on-chain part of phase 14 of
* the protocol.
*
* @param submitterMemberIndex Claimed submitter candidate group member index
* @param groupPubKey Generated candidate group public key
* @param misbehaved Bytes array of misbehaved (disqualified or inactive)
* group members indexes in ascending order; Indexes reflect positions of
* members in the group as outputted by the group selection protocol.
* @param signatures Concatenation of signatures from members supporting the
* result.
* @param signingMembersIndexes Indices of members corresponding to each
* signature.
*/
function submitDkgResult(
uint256 submitterMemberIndex,
bytes memory groupPubKey,
bytes memory misbehaved,
bytes memory signatures,
uint[] memory signingMembersIndexes
) public {
address[] memory members = selectedParticipants();
dkgResultVerification.verify(
submitterMemberIndex,
groupPubKey,
misbehaved,
signatures,
signingMembersIndexes,
members,
groupSelection.ticketSubmissionStartBlock + groupSelection.ticketSubmissionTimeout
);
groups.setGroupMembers(groupPubKey, members, misbehaved);
groups.addGroup(groupPubKey);
reimburseDkgSubmitter();
emit DkgResultSubmittedEvent(submitterMemberIndex, groupPubKey, misbehaved);
groupSelection.stop();
}
/**
* @dev Compare the reimbursement fee calculated based on the current transaction gas
* price and the current price feed estimate with the DKG reimbursement fee calculated
* and paid at the moment when the DKG was requested. If there is any surplus, it will
* be returned to the DKG fee pool of the service contract which triggered the DKG.
*/
function reimburseDkgSubmitter() internal {
uint256 gasPrice = gasPriceCeiling;
// We need to check if tx.gasprice is non-zero as a workaround to a bug
// in go-ethereum:
// https://github.com/ethereum/go-ethereum/pull/20189
if (tx.gasprice > 0 && tx.gasprice < gasPriceCeiling) {
gasPrice = tx.gasprice;
}
uint256 reimbursementFee = dkgGasEstimate.mul(gasPrice);
address payable magpie = stakingContract.magpieOf(msg.sender);
if (reimbursementFee < dkgSubmitterReimbursementFee) {
uint256 surplus = dkgSubmitterReimbursementFee.sub(reimbursementFee);
dkgSubmitterReimbursementFee = 0;
// Reimburse submitter with actual DKG cost.
magpie.call.value(reimbursementFee)("");
// Return surplus to the contract that started DKG.
groupSelectionStarterContract.fundDkgFeePool.value(surplus)();
} else {
// If submitter used higher gas price reimburse only dkgSubmitterReimbursementFee max.
reimbursementFee = dkgSubmitterReimbursementFee;
dkgSubmitterReimbursementFee = 0;
magpie.call.value(reimbursementFee)("");
}
}
/**
* @dev Creates a request to generate a new relay entry, which will include a
* random number (by signing the previous entry's random number).
* @param requestId Request Id trackable by service contract
* @param previousEntry Previous relay entry
*/
function sign(
uint256 requestId,
bytes memory previousEntry
) public payable onlyServiceContract {
uint256 entryVerificationAndProfitFee = groupProfitFee().add(
entryVerificationFee()
);
require(
msg.value >= entryVerificationAndProfitFee,
"Insufficient new entry fee"
);
uint256 callbackFee = msg.value.sub(entryVerificationAndProfitFee);
signRelayEntry(
requestId, previousEntry, msg.sender,
entryVerificationAndProfitFee, callbackFee
);
}
function signRelayEntry(
uint256 requestId,
bytes memory previousEntry,
address serviceContract,
uint256 entryVerificationAndProfitFee,
uint256 callbackFee
) internal {
require(!isEntryInProgress() || hasEntryTimedOut(), "Beacon is busy");
currentEntryStartBlock = block.number;
uint256 groupIndex = groups.selectGroup(uint256(keccak256(previousEntry)));
signingRequest = SigningRequest(
requestId,
entryVerificationAndProfitFee,
callbackFee,
groupIndex,
previousEntry,
serviceContract
);
bytes memory groupPubKey = groups.getGroupPublicKey(groupIndex);
emit RelayEntryRequested(previousEntry, groupPubKey);
}
/**
* @dev Creates a new relay entry and stores the associated data on the chain.
* @param _groupSignature Group BLS signature over the concatenation of the
* previous entry and seed.
*/
function relayEntry(bytes memory _groupSignature) public nonReentrant {
require(isEntryInProgress(), "Entry was submitted");
require(!hasEntryTimedOut(), "Entry timed out");
bytes memory groupPubKey = groups.getGroupPublicKey(signingRequest.groupIndex);
require(
BLS.verify(
groupPubKey,
signingRequest.previousEntry,
_groupSignature
),
"Invalid signature"
);
emit RelayEntrySubmitted();
// Spend no more than groupSelectionGasEstimate + 40000 gas max
// This will prevent relayEntry failure in case the service contract is compromised
signingRequest.serviceContract.call.gas(groupSelectionGasEstimate.add(40000))(
abi.encodeWithSignature(
"entryCreated(uint256,bytes,address)",
signingRequest.relayRequestId,
_groupSignature,
msg.sender
)
);
if (signingRequest.callbackFee > 0) {
executeCallback(signingRequest, uint256(keccak256(_groupSignature)));
}
(uint256 groupMemberReward, uint256 submitterReward, uint256 subsidy) = newEntryRewardsBreakdown();
groups.addGroupMemberReward(groupPubKey, groupMemberReward);
stakingContract.magpieOf(msg.sender).call.value(submitterReward)("");
if (subsidy > 0) {
signingRequest.serviceContract.call.gas(35000).value(subsidy)(abi.encodeWithSignature("fundRequestSubsidyFeePool()"));
}
currentEntryStartBlock = 0;
}
/**
* @dev Executes customer specified callback for the relay entry request.
* @param signingRequest Request data tracked internally by this contract.
* @param entry The generated random number.
*/
function executeCallback(SigningRequest memory signingRequest, uint256 entry) internal {
uint256 callbackFee = signingRequest.callbackFee;
// Make sure not to spend more than what was received from the service
// contract for the callback
uint256 gasLimit = callbackFee.div(gasPriceCeiling);
bytes memory callbackReturnData;
uint256 gasBeforeCallback = gasleft();
(, callbackReturnData) = signingRequest.serviceContract.call.gas(
gasLimit
)(abi.encodeWithSignature(
"executeCallback(uint256,uint256)",
signingRequest.relayRequestId,
entry
));
uint256 gasAfterCallback = gasleft();
uint256 gasSpent = gasBeforeCallback.sub(gasAfterCallback);
Reimbursements.reimburseCallback(
stakingContract,
gasPriceCeiling,
gasLimit,
gasSpent,
callbackFee,
callbackReturnData
);
}
/**
* @dev Get rewards breakdown in wei for successful entry for the current signing request.
*/
function newEntryRewardsBreakdown() internal view returns(uint256 groupMemberReward, uint256 submitterReward, uint256 subsidy) {
uint256 decimals = 1e16; // Adding 16 decimals to perform float division.
uint256 delayFactor = getDelayFactor();
groupMemberReward = groupMemberBaseReward.mul(delayFactor).div(decimals);
// delay penalty = base reward * (1 - delay factor)
uint256 groupMemberDelayPenalty = groupMemberBaseReward.mul(decimals.sub(delayFactor));
// The submitter reward consists of:
// The callback gas expenditure (reimbursed by the service contract)
// The entry verification fee to cover the cost of verifying the submission,
// paid regardless of their gas expenditure
// Submitter extra reward - 5% of the delay penalties of the entire group
uint256 submitterExtraReward = groupMemberDelayPenalty.mul(groupSize).percent(5).div(decimals);
uint256 entryVerificationFee = signingRequest.entryVerificationAndProfitFee.sub(groupProfitFee());
submitterReward = entryVerificationFee.add(submitterExtraReward);
// Rewards not paid out to the operators are paid out to requesters to subsidize new requests.
subsidy = groupProfitFee().sub(groupMemberReward.mul(groupSize)).sub(submitterExtraReward);
}
/**
* @dev Gets delay factor for rewards calculation.
* @return Integer representing floating-point number with 16 decimals places.
*/
function getDelayFactor() internal view returns(uint256 delayFactor) {
uint256 decimals = 1e16; // Adding 16 decimals to perform float division.
// T_deadline is the earliest block when no submissions are accepted
// and an entry timed out. The last block the entry can be published in is
// currentEntryStartBlock + relayEntryTimeout
// and submission are no longer accepted from block
// currentEntryStartBlock + relayEntryTimeout + 1.
uint256 deadlineBlock = currentEntryStartBlock.add(relayEntryTimeout).add(1);
// T_begin is the earliest block the result can be published in.
// Relay entry can be generated instantly after relay request is
// registered on-chain so a new entry can be published at the next
// block the earliest.
uint256 submissionStartBlock = currentEntryStartBlock.add(1);
// Use submissionStartBlock block as entryReceivedBlock if entry submitted earlier than expected.
uint256 entryReceivedBlock = block.number <= submissionStartBlock ? submissionStartBlock:block.number;
// T_remaining = T_deadline - T_received
uint256 remainingBlocks = deadlineBlock.sub(entryReceivedBlock);
// T_deadline - T_begin
uint256 submissionWindow = deadlineBlock.sub(submissionStartBlock);
// delay factor = [ T_remaining / (T_deadline - T_begin)]^2
//
// Since we add 16 decimal places to perform float division, we do:
// delay factor = [ T_temaining * decimals / (T_deadline - T_begin)]^2 / decimals =
// = [T_remaining / (T_deadline - T_begin) ]^2 * decimals
delayFactor = ((remainingBlocks.mul(decimals).div(submissionWindow))**2).div(decimals);
}
/**
* @dev Returns true if generation of a new relay entry is currently in
* progress.
*/
function isEntryInProgress() internal view returns (bool) {
return currentEntryStartBlock != 0;
}
/**
* @dev Returns true if the currently ongoing new relay entry generation
* operation timed out. There is a certain timeout for a new relay entry
* to be produced, see `relayEntryTimeout` value.
*/
function hasEntryTimedOut() internal view returns (bool) {
return currentEntryStartBlock != 0 && block.number > currentEntryStartBlock + relayEntryTimeout;
}
/**
* @dev Function used to inform about the fact the currently ongoing
* new relay entry generation operation timed out. As a result, the group
* which was supposed to produce a new relay entry is immediately
* terminated and a new group is selected to produce a new relay entry.
* All members of the group are punished by seizing minimum stake of
* their tokens. The submitter of the transaction is rewarded with a
* tattletale reward which is limited to min(1, 20 / group_size) of the
* maximum tattletale reward.
*/
function reportRelayEntryTimeout() public {
require(hasEntryTimedOut(), "Entry did not time out");
uint256 minimumStake = stakingContract.minimumStake();
groups.reportRelayEntryTimeout(signingRequest.groupIndex, groupSize, minimumStake);
// We could terminate the last active group. If that's the case,
// do not try to execute signing again because there is no group
// which can handle it.
if (numberOfGroups() > 0) {
signRelayEntry(
signingRequest.relayRequestId,
signingRequest.previousEntry,
signingRequest.serviceContract,
signingRequest.entryVerificationAndProfitFee,
signingRequest.callbackFee
);
}
emit RelayEntryTimeoutReported(signingRequest.groupIndex);
}
/**
* @dev Gets group profit fee expressed in wei.
*/
function groupProfitFee() public view returns(uint256) {
return groupMemberBaseReward.mul(groupSize);
}
/**
* @dev Checks if the specified account has enough active stake to become
* network operator and that this contract has been authorized for potential
* slashing.
*
* Having the required minimum of active stake makes the operator eligible
* to join the network. If the active stake is not currently undelegating,
* operator is also eligible for work selection.
*
* @param staker Staker's address
* @return True if has enough active stake to participate in the network,
* false otherwise.
*/
function hasMinimumStake(address staker) public view returns(bool) {
return stakingContract.hasMinimumStake(staker, address(this));
}
/**
* @dev Checks if group with the given public key is registered.
*/
function isGroupRegistered(bytes memory groupPubKey) public view returns(bool) {
return groups.isGroupRegistered(groupPubKey);
}
/**
* @dev Checks if a group with the given public key is a stale group.
* Stale group is an expired group which is no longer performing any
* operations. It is important to understand that an expired group may
* still perform some operations for which it was selected when it was still
* active. We consider a group to be stale when it's expired and when its
* expiration time and potentially executed operation timeout are both in
* the past.
*/
function isStaleGroup(bytes memory groupPubKey) public view returns(bool) {
return groups.isStaleGroup(groupPubKey);
}
/**
* @dev Gets the number of active groups. Expired and terminated groups are
* not counted as active.
*/
function numberOfGroups() public view returns(uint256) {
return groups.numberOfGroups();
}
/**
* @dev Returns accumulated group member rewards for provided group.
*/
function getGroupMemberRewards(bytes memory groupPubKey) public view returns (uint256) {
return groups.groupMemberRewards[groupPubKey];
}
/**
* @dev Gets all indices in the provided group for a member.
*/
function getGroupMemberIndices(bytes memory groupPubKey, address member) public view returns (uint256[] memory indices) {
return groups.getGroupMemberIndices(groupPubKey, member);
}
/**
* @dev Withdraws accumulated group member rewards for operator
* using the provided group index and member indices. Once the
* accumulated reward is withdrawn from the selected group, member is
* removed from it. Rewards can be withdrawn only from stale group.
* @param operator Operator address.
* @param groupIndex Group index.
* @param groupMemberIndices Array of member indices for the group member.
*/
function withdrawGroupMemberRewards(address operator, uint256 groupIndex, uint256[] memory groupMemberIndices) public nonReentrant {
uint256 accumulatedRewards = groups.withdrawFromGroup(operator, groupIndex, groupMemberIndices);
(bool success, ) = stakingContract.magpieOf(operator).call.value(accumulatedRewards)("");
if (success) {
emit GroupMemberRewardsWithdrawn(stakingContract.magpieOf(operator), operator, accumulatedRewards, groupIndex);
}
}
/**
* @dev Gets the index of the first active group.
*/
function getFirstActiveGroupIndex() public view returns (uint256) {
return groups.expiredGroupOffset;
}
/**
* @dev Gets group public key.
*/
function getGroupPublicKey(uint256 groupIndex) public view returns (bytes memory) {
return groups.getGroupPublicKey(groupIndex);
}
/**
* @dev Returns fee for entry verification in wei. Does not include group
* profit fee, DKG contribution or callback fee.
*/
function entryVerificationFee() public view returns (uint256) {
return entryVerificationGasEstimate.mul(gasPriceCeiling);
}
/**
* @dev Returns fee for group creation in wei. Includes the cost of DKG
* and the cost of triggering group selection.
*/
function groupCreationFee() public view returns (uint256) {
return dkgGasEstimate.add(groupSelectionGasEstimate).mul(gasPriceCeiling);
}
/**
* @dev Returns members of the given group by group public key.
*/
function getGroupMembers(bytes memory groupPubKey) public view returns (address[] memory members) {
return groups.getGroupMembers(groupPubKey);
}
/**
* @dev Reports unauthorized signing for the provided group. Must provide
* a valid signature of the tattletale address as a message. Successful signature
* verification means the private key has been leaked and all group members
* should be punished by seizing their tokens. The submitter of this proof is
* rewarded with 5% of the total seized amount scaled by the reward adjustment
* parameter and the rest 95% is burned.
*/
function reportUnauthorizedSigning(
uint256 groupIndex,
bytes memory signedMsgSender
) public {
uint256 minimumStake = stakingContract.minimumStake();
groups.reportUnauthorizedSigning(groupIndex, signedMsgSender, minimumStake);
emit UnauthorizedSigningReported(groupIndex);
}
}
| Function used to inform about the fact the currently ongoing new relay entry generation operation timed out. As a result, the group which was supposed to produce a new relay entry is immediately terminated and a new group is selected to produce a new relay entry. All members of the group are punished by seizing minimum stake of their tokens. The submitter of the transaction is rewarded with a tattletale reward which is limited to min(1, 20 / group_size) of the maximum tattletale reward./ We could terminate the last active group. If that's the case, do not try to execute signing again because there is no group which can handle it. | function reportRelayEntryTimeout() public {
require(hasEntryTimedOut(), "Entry did not time out");
uint256 minimumStake = stakingContract.minimumStake();
groups.reportRelayEntryTimeout(signingRequest.groupIndex, groupSize, minimumStake);
if (numberOfGroups() > 0) {
signRelayEntry(
signingRequest.relayRequestId,
signingRequest.previousEntry,
signingRequest.serviceContract,
signingRequest.entryVerificationAndProfitFee,
signingRequest.callbackFee
);
}
emit RelayEntryTimeoutReported(signingRequest.groupIndex);
}
| 1,840,291 |
pragma solidity 0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public 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);
}
/**
* Safe unsigned safe math.
*
* https://blog.aragon.one/library-driven-development-in-solidity-2bebcaf88736#.750gwtwli
*
* Originally from https://raw.githubusercontent.com/AragonOne/zeppelin-solidity/master/contracts/SafeMathLib.sol
*
* Maintained here until merged to mainline zeppelin-solidity.
*
*/
library SafeMathLibExt {
function times(uint a, uint b) public pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function divides(uint a, uint b) public pure returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function minus(uint a, uint b) public pure returns (uint) {
assert(b <= a);
return a - b;
}
function plus(uint a, uint b) public pure returns (uint) {
uint 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) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Allocatable is Ownable {
/** List of agents that are allowed to allocate new tokens */
mapping (address => bool) public allocateAgents;
event AllocateAgentChanged(address addr, bool state );
/**
* Owner can allow a crowdsale contract to allocate new tokens.
*/
function setAllocateAgent(address addr, bool state) public onlyOwner
{
allocateAgents[addr] = state;
emit AllocateAgentChanged(addr, state);
}
modifier onlyAllocateAgent() {
//Only crowdsale contracts are allowed to allocate new tokens
require(allocateAgents[msg.sender]);
_;
}
}
/**
* Contract to enforce Token Vesting
*/
contract TokenVesting is Allocatable {
using SafeMathLibExt for uint;
address public crowdSaleTokenAddress;
/** keep track of total tokens yet to be released,
* this should be less than or equal to UTIX tokens held by this contract.
*/
uint256 public totalUnreleasedTokens;
// default vesting parameters
uint256 private startAt = 0;
uint256 private cliff = 1;
uint256 private duration = 4;
uint256 private step = 300; //15778463; //2592000;
bool private changeFreezed = false;
struct VestingSchedule {
uint256 startAt;
uint256 cliff;
uint256 duration;
uint256 step;
uint256 amount;
uint256 amountReleased;
bool changeFreezed;
}
mapping (address => VestingSchedule) public vestingMap;
event VestedTokensReleased(address _adr, uint256 _amount);
constructor(address _tokenAddress) public {
crowdSaleTokenAddress = _tokenAddress;
}
/** Modifier to check if changes to vesting is freezed */
modifier changesToVestingFreezed(address _adr) {
require(vestingMap[_adr].changeFreezed);
_;
}
/** Modifier to check if changes to vesting is not freezed yet */
modifier changesToVestingNotFreezed(address adr) {
require(!vestingMap[adr].changeFreezed); // if vesting not set then also changeFreezed will be false
_;
}
/** Function to set default vesting schedule parameters. */
function setDefaultVestingParameters(
uint256 _startAt, uint256 _cliff, uint256 _duration,
uint256 _step, bool _changeFreezed) public onlyAllocateAgent {
// data validation
require(_step != 0);
require(_duration != 0);
require(_cliff <= _duration);
startAt = _startAt;
cliff = _cliff;
duration = _duration;
step = _step;
changeFreezed = _changeFreezed;
}
/** Function to set vesting with default schedule. */
function setVestingWithDefaultSchedule(address _adr, uint256 _amount)
public
changesToVestingNotFreezed(_adr) onlyAllocateAgent {
setVesting(_adr, startAt, cliff, duration, step, _amount, changeFreezed);
}
/** Function to set/update vesting schedule. PS - Amount cannot be changed once set */
function setVesting(
address _adr,
uint256 _startAt,
uint256 _cliff,
uint256 _duration,
uint256 _step,
uint256 _amount,
bool _changeFreezed)
public changesToVestingNotFreezed(_adr) onlyAllocateAgent {
VestingSchedule storage vestingSchedule = vestingMap[_adr];
// data validation
require(_step != 0);
require(_amount != 0 || vestingSchedule.amount > 0);
require(_duration != 0);
require(_cliff <= _duration);
//if startAt is zero, set current time as start time.
if (_startAt == 0)
_startAt = block.timestamp;
vestingSchedule.startAt = _startAt;
vestingSchedule.cliff = _cliff;
vestingSchedule.duration = _duration;
vestingSchedule.step = _step;
// special processing for first time vesting setting
if (vestingSchedule.amount == 0) {
// check if enough tokens are held by this contract
ERC20 token = ERC20(crowdSaleTokenAddress);
require(token.balanceOf(this) >= totalUnreleasedTokens.plus(_amount));
totalUnreleasedTokens = totalUnreleasedTokens.plus(_amount);
vestingSchedule.amount = _amount;
}
vestingSchedule.amountReleased = 0;
vestingSchedule.changeFreezed = _changeFreezed;
}
function isVestingSet(address adr) public view returns (bool isSet) {
return vestingMap[adr].amount != 0;
}
function freezeChangesToVesting(address _adr) public changesToVestingNotFreezed(_adr) onlyAllocateAgent {
require(isVestingSet(_adr)); // first check if vesting is set
vestingMap[_adr].changeFreezed = true;
}
/** Release tokens as per vesting schedule, called by contributor */
function releaseMyVestedTokens() public changesToVestingFreezed(msg.sender) {
releaseVestedTokens(msg.sender);
}
/** Release tokens as per vesting schedule, called by anyone */
function releaseVestedTokens(address _adr) public changesToVestingFreezed(_adr) {
VestingSchedule storage vestingSchedule = vestingMap[_adr];
// check if all tokens are not vested
require(vestingSchedule.amount.minus(vestingSchedule.amountReleased) > 0);
// calculate total vested tokens till now
uint256 totalTime = block.timestamp - vestingSchedule.startAt;
uint256 totalSteps = totalTime / vestingSchedule.step;
// check if cliff is passed
require(vestingSchedule.cliff <= totalSteps);
uint256 tokensPerStep = vestingSchedule.amount / vestingSchedule.duration;
// check if amount is divisble by duration
if (tokensPerStep * vestingSchedule.duration != vestingSchedule.amount) tokensPerStep++;
uint256 totalReleasableAmount = tokensPerStep.times(totalSteps);
// handle the case if user has not claimed even after vesting period is over or amount was not divisible
if (totalReleasableAmount > vestingSchedule.amount) totalReleasableAmount = vestingSchedule.amount;
uint256 amountToRelease = totalReleasableAmount.minus(vestingSchedule.amountReleased);
vestingSchedule.amountReleased = vestingSchedule.amountReleased.plus(amountToRelease);
// transfer vested tokens
ERC20 token = ERC20(crowdSaleTokenAddress);
token.transfer(_adr, amountToRelease);
// decrement overall unreleased token count
totalUnreleasedTokens = totalUnreleasedTokens.minus(amountToRelease);
emit VestedTokensReleased(_adr, amountToRelease);
}
/**
* Allow to (re)set Token.
*/
function setCrowdsaleTokenExtv1(address _token) public onlyAllocateAgent {
crowdSaleTokenAddress = _token;
}
} | Release tokens as per vesting schedule, called by contributor / | function releaseMyVestedTokens() public changesToVestingFreezed(msg.sender) {
releaseVestedTokens(msg.sender);
}
| 2,251,383 |
./full_match/1/0xD7134e2265B78DFCF4e9FA4DC65b18F4D5C03220/sources/contracts/bridgeERC20/layerZero/utils/NonblockingLzAppERC20.sol | Sends a message to the LZ endpoint and process it _dstChainId L0 defined chain id to send tokens too _payload Data: recipient address and amount _refundAddress Address LayerZero refunds if too much message fee is sent _zroPaymentAddress Set to address(0x0) if not paying in ZRO (LayerZero Token) _adapterParams Flexible bytes array to indicate messaging adapter services in L0solhint-disable-next-line | function _lzSend(
uint16 _dstChainId,
bytes memory _payload,
address payable _refundAddress,
address _zroPaymentAddress,
bytes memory _adapterParams
) internal virtual {
bytes memory trustedRemote = trustedRemoteLookup[_dstChainId];
if (trustedRemote.length == 0) revert InvalidSource();
_dstChainId,
trustedRemote,
_payload,
_refundAddress,
_zroPaymentAddress,
_adapterParams
);
}
| 3,182,986 |
./partial_match/3/0xdfcA02f5989efC6Ec7EcE748Ca1c11f0bb88aEFF/sources/VEROX_MAKER.sol | function to allow owner to transfer any ERC20 tokens from this contract | function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner {
if (_tokenAddr == tokenAddress) {
totalClaimedRewards = totalClaimedRewards.add(_amount);
}
require(_tokenAddr != address(tokenAddress));
Token(_tokenAddr).transfer(_to, _amount);
}
| 16,623,919 |
pragma solidity ^0.4.0;
import 'zeppelin-solidity/contracts/ownership/Ownable.sol';
import 'zeppelin-solidity/contracts/math/SafeMath.sol';
import './Coupon.sol';
import './GetTogether.sol';
/**
* @title GetTogetherCoupon
* @dev Implementation of the Coupon interface for use with the BlockTogether contract.
*/
// TODO decide whether the contract can be paused
contract GetTogetherCoupon is Ownable, Coupon {
using SafeMath for uint256;
mapping (address => uint) internal balances;
mapping (address => mapping(address => uint)) internal stakes;
modifier hasLargeEnoughBalance(uint _amount) {
require(balances[msg.sender] >= _amount);
_;
}
function deposit() public payable {
balances[msg.sender] = balances[msg.sender].add(msg.value);
Deposited(msg.sender, msg.value);
}
function withdraw(uint _amount) public hasLargeEnoughBalance(_amount) {
require(_amount > 0);
balances[msg.sender] = balances[msg.sender].sub(_amount);
msg.sender.transfer(_amount);
Withdrawn(msg.sender, _amount);
}
function balanceOf(address _account) public view returns (uint) {
return balances[_account];
}
function totalStaked(address _getTogether) public view returns (uint) {
return stakes[_getTogether][address(0)];
}
function stakedAmount(address _getTogether, address _account) public view returns (uint) {
return stakes[_getTogether][_account];
}
function registerForGetTogether(address _getTogether) public {
require(_getTogether != address(0));
GetTogether getTogether = GetTogether(_getTogether);
require(getTogether.getTogetherDate() > now);
require(getTogether.numberOfAttendees() < getTogether.maxCapacity());
stake(getTogether.stakeRequired(), _getTogether);
}
function stake(uint _amount, address _getTogether) internal hasLargeEnoughBalance(_amount) {
// Require that the msg.sender has not already registered / staked a balance for the get-together
require(stakes[_getTogether][msg.sender] == 0);
// Very unlikely - if someone owned the address 0x0 then they would own
require(msg.sender != address(0));
balances[msg.sender] = balances[msg.sender].sub(_amount);
stakes[_getTogether][msg.sender] = _amount;
// Keep track of the total amount staked
stakes[_getTogether][address(0)] = stakes[_getTogether][address(0)].add(_amount);
}
// TODO how to keep track of the total balance that has been staked to an address
function redeemStake(address _getTogether, address _to, uint256 _value, uint8 _v, bytes32 _r, bytes32 _s) public {
require(_getTogether != address(0));
require(stakes[_getTogether][_to] != 0);
require(_value > 0);
GetTogether getTogether = GetTogether(_getTogether);
require(now >= getTogether.whenStakeCanBeReturned());
require(getTogether.owner() != address(0));
address recoveredSignerAddress = recoverAddressOfSigner(_getTogether, _to, _value, _v, _r, _s);
require(recoveredSignerAddress == getTogether.owner());
stakes[_getTogether][_to] = 0;
balances[_to] = balances[_to].add(_value);
stakes[_getTogether][address(0)] = stakes[_getTogether][address(0)].sub(_value);
}
function recoverAddressOfSigner(address _getTogether, address _to, uint256 _value, uint8 _v, bytes32 _r, bytes32 _s) internal pure returns (address) {
require(_to != address(0));
bytes32 hash = keccak256(_getTogether, _to, _value);
return recover(hash, _v, _r, _s);
}
function recover(bytes32 h, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(prefix, h);
return ecrecover(prefixedHash, v, r, s);
}
}
| Require that the msg.sender has not already registered / staked a balance for the get-together Very unlikely - if someone owned the address 0x0 then they would own Keep track of the total amount staked | function stake(uint _amount, address _getTogether) internal hasLargeEnoughBalance(_amount) {
require(stakes[_getTogether][msg.sender] == 0);
require(msg.sender != address(0));
balances[msg.sender] = balances[msg.sender].sub(_amount);
stakes[_getTogether][msg.sender] = _amount;
stakes[_getTogether][address(0)] = stakes[_getTogether][address(0)].add(_amount);
}
| 13,036,855 |
pragma solidity ^0.4.19;
//pragma experimental ABIEncoderV2;
import "./ownable.sol";
import "./safemath.sol";
contract FactualNews {
// Parameters
uint percentageAuditors = 10; // in %
uint percentageCompany = 5; // in %
struct newsRequestContractType {
string retMsg;
string _statusTemp;
// Request Status
string requestStatus; // This status can be "Blank", "Requested", "Approve Reviewer", "Reviewing" , "Auditing" , "Approved" or "Denied"
// Data structures associated to originators
//mapping (address => uint) originatorToId; // links originator, person who created the request, address to id in the fundAmount array
uint[] fundAmount; // carries the actual ammount
address[] originatorsList;
uint totalFundAmount;
uint requestReviewId; // carries the request Id
// Data structures associated to reviewers
//mapping (address => uint) reviewerToId; // links reviewer to id in reviewStatus array
bool[] reviewStatus; // status of revision - true is done and false is in progress
address[] reviewersList;
// Data structures associated to auditors
//mapping (address => uint) auditorToId; // links auditor to id in auditorStatus array
string[] auditorStatus; // status of auditing - "Not initiated" , "Approved" or "Denied"
address[] auditorsList;
uint totalAuditors;
}
mapping (uint => newsRequestContractType) news; // links news to contract data
// Iniitate a review request
function createRequest(uint _id,uint _requestReviewId) public {
news[_id].requestStatus = "Requested";
news[_id].requestReviewId = _requestReviewId;
news[_id].totalFundAmount = 0;
news[_id].totalAuditors = 0;
}
// Get to total amount committed in this request
function getTotalRequestInfo(uint _id) external view returns(
string _requestStatus,
uint _requestReviewId,
uint _totalFundAmount,
uint[] _fundAmount,
address[] _originatorsList) {
_requestStatus = news[_id].requestStatus;
_requestReviewId = news[_id].requestReviewId;
_totalFundAmount = news[_id].totalFundAmount;
_fundAmount = news[_id].fundAmount;
_originatorsList = news[_id].originatorsList;
}
modifier nonZeroValue() { if (!(msg.value > 0)) revert(); _; }
function findOriginator(uint _id,address addr) internal view returns (uint) {
uint i;
uint len;
len = news[_id].originatorsList.length;
for (i=0;i<len;i++) {
if (addr == news[_id].originatorsList[i]) {
return (i+1);
}
}
return 0;
}
// Add funds
function addReviewFunds(uint _id) public payable {
if (keccak256(news[_id].requestStatus) == keccak256("Requested")) {
uint id = findOriginator(_id,msg.sender);
if (id == 0) {
id = news[_id].fundAmount.push(msg.value);
news[_id].originatorsList.push(msg.sender);
}
else {
news[_id].fundAmount[id-1] += msg.value;
news[_id].originatorsList[id-1] = msg.sender;
}
news[_id].totalFundAmount += msg.value;
}
else {
revert();
}
}
// Withdrawal all money
function withdrawal(uint _id,uint _amount, address _recipient) external {
uint transferAmount;
transferAmount = _amount;
if ( (_amount > news[_id].totalFundAmount) || (_amount == 0) ) {
transferAmount = news[_id].totalFundAmount;
}
news[_id].totalFundAmount -= transferAmount;
_recipient.send(transferAmount);
}
//demo only allows ANYONE to withdraw
function withdrawAll(uint _id) external {
news[_id].totalFundAmount = 0;
require(msg.sender.send(this.balance));
}
function findReviewer(uint _id,address addr) internal view returns (uint) {
uint i;
uint len;
len = news[_id].reviewersList.length;
for (i=0;i<len;i++) {
if (addr == news[_id].reviewersList[i]) {
return (i+1);
}
}
return 0;
}
// Reviewers candidatate apply to review.
function applyForReview(uint _id) public {
if (keccak256(news[_id].requestStatus) == keccak256("Requested")) {
news[_id].requestStatus = "Approve Reviewer";
uint id = findReviewer(_id,msg.sender);
if (id == 0) {
id = news[_id].reviewStatus.push(false);
news[_id].reviewersList.push(msg.sender);
}
else {
news[_id].reviewStatus[id-1] = false;
news[_id].reviewersList[id-1] = msg.sender;
}
}
else {
revert();
}
}
// Get review status
function getReviewStatusInfo(uint _id) external view returns(bool[] _reviewStatus, address[] _reviewersList) {
_reviewStatus = news[_id].reviewStatus;
_reviewersList = news[_id].reviewersList;
}
function findAuditor(uint _id,address addr) internal view returns (uint) {
uint i;
uint len;
len = news[_id].auditorsList.length;
for (i=0;i<len;i++) {
if (addr == news[_id].auditorsList[i]) {
return (i+1);
}
}
return 0;
}
// Apply for Auditors
function applyForAuditing(uint _id) external {
if ((keccak256(news[_id].requestStatus) == keccak256("Requested")) ||
(keccak256(news[_id].requestStatus) == keccak256("Approve Reviewer")) ) {
uint id = findAuditor(_id,msg.sender);
if (id == 0) {
id = news[_id].auditorStatus.push("Not initiated");
news[_id].auditorsList.push(msg.sender);
news[_id].totalAuditors++;
}
else {
news[_id].auditorStatus[id-1] = "Not initiated";
news[_id].auditorsList[id-1] = msg.sender;
}
}
else {
revert();
}
}
// Get auditor status
function getAuditorStatusInfo(uint _id) external view returns(uint _totalAuditors, address[] _auditorsList) {
_totalAuditors = news[_id].totalAuditors;
_auditorsList = news[_id].auditorsList;
}
// Only the originator can approve Reviewers and Auditors
function approveReviewerAuditors(uint _id) {
if ((keccak256(news[_id].requestStatus) == keccak256("Approve Reviewer")) &&
(news[_id].totalAuditors > 0) ) {
news[_id].requestStatus = "Reviewing";
}
else {
revert();
}
}
// Only first reviewer can trigger the auditing
function finishReview(uint _id) public {
if ((keccak256(news[_id].requestStatus) == keccak256("Reviewing")) &&
(news[_id].reviewersList[0] == msg.sender) ) {
news[_id].requestStatus = "Auditing";
}
else {
revert();
}
}
// Counts how many auditors have already approved
function _countStatus(uint _id,string _status) private view returns (uint) {
uint count = 0;
for (uint i=0; i < news[_id].totalAuditors; i++) {
if (keccak256(news[_id].auditorStatus[i]) == keccak256(_status)) {
count++;
}
}
return count;
}
//Check the outcome of auditing - Approved, Denied, Undefined
function _checkAuditingStatus(uint _id) private view returns (string) {
uint _countApproved;
uint _countDenied;
uint tempTotalAuditors;
_countApproved = _countStatus(_id,"Approved");
_countDenied = _countStatus(_id,"Denied");
// case which is tied
if ( ((news[_id].totalAuditors % 2) == 0) &&
(news[_id].totalAuditors == (_countApproved + _countDenied)) &&
(_countApproved == _countDenied) ) {
return "Denied";
}
if ((news[_id].totalAuditors % 2) != 0) {
tempTotalAuditors = news[_id].totalAuditors + 1;
}
else {
tempTotalAuditors = news[_id].totalAuditors;
}
// Majority denied
if (_countDenied >= (tempTotalAuditors/2)) {
return "Denied";
}
// Majority Approved
if (_countApproved >= (tempTotalAuditors/2)) {
return "Approved";
}
return "Undefined";
}
// This function process all payments refering to the end o review process
function _finalizeRequestReview(uint _id,string _status) private {
uint auditorsValue;
uint i;
uint remainder;
uint remainderOriginators;
uint totalOriginators;
uint originatorPart;
uint totalReviewers;
uint reviewerPart;
if (news[_id].totalAuditors == 0) {
auditorsValue = 0;
}
else {
auditorsValue = (news[_id].totalFundAmount * percentageAuditors / 100) / news[_id].totalAuditors;
}
remainder = news[_id].totalFundAmount;
for (i=0; i < news[_id].totalAuditors; i++) {
news[_id].auditorsList[i].transfer(auditorsValue);
remainder -= auditorsValue;
}
// Company should get paid here
remainder -= (news[_id].totalFundAmount * percentageCompany / 100) / news[_id].totalAuditors;
// Pay the reviewers in case that review was approved
if (keccak256(_status) == keccak256("Approved")) {
totalReviewers = news[_id].reviewersList.length;
reviewerPart = remainder / totalReviewers;
for (i=0; i < totalReviewers; i++) {
news[_id].reviewersList[i].transfer(reviewerPart);
remainder -= reviewerPart;
}
}
// Or return the funds to the originators
else {
totalOriginators = news[_id].originatorsList.length;
remainderOriginators = remainder;
for (i=0; i < totalOriginators; i++) {
originatorPart = news[_id].fundAmount[i]*remainderOriginators/news[_id].totalFundAmount;
news[_id].originatorsList[i].transfer(originatorPart);
remainder -= originatorPart;
}
}
news[_id].totalFundAmount = remainder;
}
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 uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint length;
while (j != 0){
length++;
j /= 10;
}
bytes memory bstr = new bytes(length);
uint k = length - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
// Auditors give their appreciation on the review
function auditReview(uint _id,string _decision) external payable returns (string) {
news[_id].retMsg = "";
if ((keccak256(news[_id].requestStatus) == keccak256("Auditing"))
&& (findAuditor(_id,msg.sender) != 0)
) {
uint id = findAuditor(_id,msg.sender) - 1;
if (keccak256(_decision) == keccak256("Approved")) {
news[_id].auditorStatus[id] = "Approved";
}
else {
news[_id].auditorStatus[id] = "Denied";
}
// Check auditing status
news[_id]._statusTemp = string(_checkAuditingStatus(_id));
if (keccak256(news[_id]._statusTemp) != keccak256("Undefined")) {
_finalizeRequestReview(_id,news[_id]._statusTemp);
news[_id].requestStatus = news[_id]._statusTemp;
}
}
else {
news[_id].retMsg = string(strConcat(toString(msg.sender), " - ", uint2str(findAuditor(_id,msg.sender)), "",""));
}
return string(news[_id].retMsg);
}
} | Check the outcome of auditing - Approved, Denied, Undefined case which is tied Majority denied Majority Approved | function _checkAuditingStatus(uint _id) private view returns (string) {
uint _countApproved;
uint _countDenied;
uint tempTotalAuditors;
_countApproved = _countStatus(_id,"Approved");
_countDenied = _countStatus(_id,"Denied");
if ( ((news[_id].totalAuditors % 2) == 0) &&
(news[_id].totalAuditors == (_countApproved + _countDenied)) &&
(_countApproved == _countDenied) ) {
return "Denied";
}
if ((news[_id].totalAuditors % 2) != 0) {
tempTotalAuditors = news[_id].totalAuditors + 1;
}
else {
tempTotalAuditors = news[_id].totalAuditors;
}
if (_countDenied >= (tempTotalAuditors/2)) {
return "Denied";
}
if (_countApproved >= (tempTotalAuditors/2)) {
return "Approved";
}
return "Undefined";
}
| 2,518,949 |
./full_match/5/0x4Ecdd1450710Aa7059A1BC549bB98Ab0143C568F/sources/contracts/StakingContract5.sol | Iterate through all user's deposits to withdraw all funds Create an array for all msg.senders deposits Iterate through the list and withdraw all | function withdrawAll() public virtual {
uint256[] memory depositIds = allUsersDeposits[msg.sender].values();
require(depositIds.length > 0, "No Withdrawals Avaialable");
uint256 _currentId = currentId[msg.sender];
StakeVault storage staker = checkDeposit[msg.sender][_currentId];
uint256 lockedUntil = staker.startTime + secondsLocked;
require(
(staker.depositAmount > 1) && (block.timestamp >= lockedUntil),
"Funds are still locked!"
);
for (uint256 i = 1; i < depositIds.length; i++) {
StakeVault storage stakerIteration = checkDeposit[msg.sender][i];
if (stakerIteration.depositAmount > 1) {
withdrawPosition(i, type(uint256).max);
}
}
}
| 1,880,255 |
./full_match/1/0x8eb5bD8c9Ab0F8ad28e94693F3c889F490bE2aB0/sources/contracts/POS32.sol | Change the minimum contract ACAP balance before `_swap` gets invoked _minTokenBalance The new minimum balance | function setMinTokenBalance(uint256 _minTokenBalance) external onlyOwner {
minTokenBalance = _minTokenBalance;
}
| 4,876,247 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
import "./interfaces/IArtworkStore.sol";
import "./interfaces/ITRLabCore.sol";
import "./base/ERC2981Upgradeable.sol";
import "./lib/LibArtwork.sol";
/// @title Interface of TRLab NFT core contract
/// @author Joe
/// @notice This is the interface of TRLab NFT core contract
contract TRLabCore is
ITRLabCore,
Initializable,
ERC2981Upgradeable,
ERC721Upgradeable,
ERC721URIStorageUpgradeable,
PausableUpgradeable,
OwnableUpgradeable,
UUPSUpgradeable
{
using CountersUpgradeable for CountersUpgradeable.Counter;
using SafeERC20Upgradeable for IERC20Upgradeable;
using StringsUpgradeable for uint256;
// ---------------- params -----------------
/// @dev internal id counter, do not use directly, use _getNextTokenId()
CountersUpgradeable.Counter private _tokenIdCounter;
/// @dev account address => approved or not
mapping(address => bool) public override approvedTokenCreators;
/// @dev token id => ArtworkRelease
mapping(uint256 => LibArtwork.ArtworkRelease) public tokenIdToArtworkRelease;
/// @dev artwork store contract address
IArtworkStore public artworkStore;
/// @dev reentrancy constants
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
/// @dev reentrancy status
uint256 private _status;
/// @dev Throws if called by any account other than the owner or approved creator
modifier onlyOwnerOrCreator() {
require(
owner() == _msgSender() || approvedTokenCreators[_msgSender()],
"caller is not the owner or approved creator"
);
_;
}
/**
* @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;
}
function initialize(
string memory _tokenName,
string memory _tokenSymbol,
address _storeAddress
) public initializer {
__ERC721_init(_tokenName, _tokenSymbol);
__ERC2981_init();
__ERC721URIStorage_init();
__Pausable_init();
__Ownable_init();
__UUPSUpgradeable_init();
_status = _NOT_ENTERED;
// counter starts from 0, increase to 1
_tokenIdCounter.increment();
setStoreAddress(_storeAddress);
}
/// @dev get current total supply of NFTs
function totalSupply() public view override returns (uint256) {
return getNextTokenId() - 1;
}
/// @dev Set store address. Only called by the owner.
function setStoreAddress(address _storeAddress) public override onlyOwner {
artworkStore = IArtworkStore(_storeAddress);
emit NewArtworkStore(_storeAddress);
}
/// @inheritdoc ITRLabCore
function setTokenRoyalty(
uint256 _tokenId,
address _receiver,
uint256 _bps
) public override onlyOwner {
Royalty memory r = Royalty({receiver: _receiver, bps: _bps});
_setRoyalty(_tokenId, r);
}
/// @dev set the royalty of tokens. Can only be called by owner at emergency
/// @param _tokenIds uint256[] the ids of the token
/// @param _receiver address the receiver address of the royalty
/// @param _bps uint256 the royalty percentage in bps
function setTokensRoyalty(
uint256[] calldata _tokenIds,
address _receiver,
uint256 _bps
) public override onlyOwner {
Royalty memory r = Royalty({receiver: _receiver, bps: _bps});
for (uint256 idx = 0; idx < _tokenIds.length; idx++) {
uint256 id = _tokenIds[idx];
_setRoyalty(id, r);
}
}
/// @dev Set approved creator. Only called by the owner.
function setApprovedCreator(address[] calldata creators, bool ok) external onlyOwner {
for (uint256 idx = 0; idx < creators.length; idx++) {
approvedTokenCreators[creators[idx]] = ok;
}
}
/// @inheritdoc ITRLabCore
function getArtwork(uint256 _artworkId) external view override returns (LibArtwork.Artwork memory artwork) {
artwork = _getArtwork(_artworkId);
}
/// @inheritdoc ITRLabCore
function createArtwork(
uint32 _totalSupply,
string calldata _metadataPath,
address _royaltyReceiver,
uint256 _royaltyBps
) external override whenNotPaused onlyOwnerOrCreator {
_createArtwork(_msgSender(), _totalSupply, _metadataPath, _royaltyReceiver, _royaltyBps);
}
/// @inheritdoc ITRLabCore
function createArtworkAndReleases(
uint32 _totalSupply,
string calldata _metadataPath,
uint32 _numReleases,
address _royaltyReceiver,
uint256 _royaltyBps
) external override whenNotPaused onlyOwnerOrCreator {
uint256 artworkId = _createArtwork(_msgSender(), _totalSupply, _metadataPath, _royaltyReceiver, _royaltyBps);
_batchArtworkRelease(_msgSender(), artworkId, _numReleases);
}
/// @inheritdoc ITRLabCore
function releaseArtwork(uint256 _artworkId, uint32 _numReleases)
external
override
whenNotPaused
onlyOwnerOrCreator
{
_batchArtworkRelease(_msgSender(), _artworkId, _numReleases);
}
/// @inheritdoc ITRLabCore
function releaseArtworkForReceiver(
address _receiver,
uint256 _artworkId,
uint32 _numReleases
) external override whenNotPaused onlyOwnerOrCreator {
_batchArtworkRelease(_receiver, _artworkId, _numReleases);
}
/// @notice get the next token id, won't change state
function getNextTokenId() public view override returns (uint256) {
return _tokenIdCounter.current();
}
/// @notice burns an artwork, Once this function succeeds, this artwork
/// will no longer be able to mint any more tokens. Existing tokens need to be
/// burned individually though.
/// @param _artworkId the id of the artwork to burn
function burnArtwork(uint256 _artworkId) public onlyOwner {
_burnArtwork(_artworkId);
}
/// @dev pause the contract
function pause() public onlyOwner {
_pause();
}
/// @dev unpause the contract
function unpause() public onlyOwner {
_unpause();
}
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public whenNotPaused {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
/// @notice returns ipfs uri of token
/// @param tokenId uint256 id of token
/// @return the ipfs uri
function tokenURI(uint256 tokenId)
public
view
override(ERC721Upgradeable, ERC721URIStorageUpgradeable)
returns (string memory)
{
require(_exists(tokenId), "URI query for nonexistent token");
LibArtwork.ArtworkRelease memory artworkRelease = tokenIdToArtworkRelease[tokenId];
uint256 artworkId = artworkRelease.artworkId;
uint256 printEdition = artworkRelease.printEdition;
LibArtwork.Artwork memory artwork = _getArtwork(artworkId);
string memory baseURI = artwork.metadataPath;
return _tokenURIHelper(baseURI, printEdition);
}
function _tokenURIHelper(string memory baseURI, uint256 printEdition) private pure returns (string memory) {
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, printEdition.toString())) : "";
}
/**
* Creates a new artwork object. Returns the artwork id.
*/
function _createArtwork(
address _creator,
uint32 _totalSupply,
string calldata _metadataPath,
address _royaltyReceiver,
uint256 _royaltyBps
) internal returns (uint256) {
return artworkStore.createArtwork(_creator, _totalSupply, _metadataPath, _royaltyReceiver, _royaltyBps);
}
/**
* Creates _count number of NFT token for artwork
* Bumps up the print index by _count.
* @param _nftOwner address the owner of the NFT token
* @param _artworkId uint256 the artwork id
* @param _count uint256 how many tokens of this batch
*/
function _batchArtworkRelease(
address _nftOwner,
uint256 _artworkId,
uint32 _count
) internal nonReentrant {
// Sanity check of _count number. Negative number will throw overflow exception
require(_count < 10000, "Cannot print more than 10K tokens at once");
LibArtwork.Artwork memory _artwork = _getArtwork(_artworkId);
// If artwork not exists, its creator is address(0)
require(_artwork.creator != address(0), "artwork not exists");
// Get the old print index before increment.
uint32 currentPrintIndex = _artwork.printIndex;
// Increase print index before mint logic, check if increment valid. Saving gas if count exceeds maxSupply.
_incrementArtworkPrintIndex(_artworkId, _count);
Royalty memory royalty = Royalty({receiver: _artwork.royaltyReceiver, bps: _artwork.royaltyBps});
for (uint32 i = 0; i < _count; i++) {
uint32 newPrintEdition = currentPrintIndex + 1 + i;
LibArtwork.ArtworkRelease memory _artworkRelease = LibArtwork.ArtworkRelease({
printEdition: newPrintEdition,
artworkId: _artworkId
});
uint256 tokenId = _nextTokenId();
tokenIdToArtworkRelease[tokenId] = _artworkRelease;
// This will assign ownership and also emit the Transfer event as per ERC721
_safeMint(_nftOwner, tokenId);
_setRoyalty(tokenId, royalty);
emit ArtworkReleaseCreated(
tokenId,
_nftOwner,
_artworkId,
newPrintEdition,
_tokenURIHelper(_artwork.metadataPath, newPrintEdition)
);
}
emit ArtworkPrintIndexUpdated(_artworkId, currentPrintIndex + _count);
}
function _incrementArtworkPrintIndex(uint256 _artworkId, uint32 _count) internal {
artworkStore.incrementArtworkPrintIndex(_artworkId, _count);
}
// this function changes _tokenIdCounter status
function _nextTokenId() internal returns (uint256) {
uint256 _nextId = _tokenIdCounter.current();
_tokenIdCounter.increment();
return _nextId;
}
function _getArtwork(uint256 artworkId) internal view returns (LibArtwork.Artwork memory) {
return artworkStore.getArtwork(artworkId);
}
/**
* Burns an artwork. Once this function succeeds, this artwork
* will no longer be able to mint any more tokens. Existing tokens need to be
* burned individually though.
* @param _artworkId the id of the digital media to burn
*/
function _burnArtwork(uint256 _artworkId) internal {
LibArtwork.Artwork memory _artwork = _getArtwork(_artworkId);
uint32 increment = _artwork.totalSupply - _artwork.printIndex;
_incrementArtworkPrintIndex(_artworkId, increment);
emit ArtworkBurned(_artworkId);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override whenNotPaused {
super._beforeTokenTransfer(from, to, tokenId);
}
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
function _burn(uint256 tokenId) internal override(ERC721Upgradeable, ERC721URIStorageUpgradeable) {
super._burn(tokenId);
delete tokenIdToArtworkRelease[tokenId];
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC2981Upgradeable, ERC721Upgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function emergencyWithdrawERC20Tokens(
address _tokenAddr,
address _to,
uint256 _amount
) external onlyOwner {
IERC20Upgradeable(_tokenAddr).safeTransfer(_to, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping (uint256 => address) private _owners;
// Mapping owner address to token count
mapping (address => uint256) private _balances;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return interfaceId == type(IERC721Upgradeable).interfaceId
|| interfaceId == type(IERC721MetadataUpgradeable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
/**
* @dev Base URI for computing {tokenURI}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
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
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../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 initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev Base contract for building openzeppelin-upgrades compatible implementations for the {ERC1967Proxy}. It includes
* publicly available upgrade functions that are called by the plugin and by the secure upgrade mechanism to verify
* continuation of the upgradability.
*
* The {_authorizeUpgrade} function MUST be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal initializer {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal initializer {
}
function upgradeTo(address newImplementation) external virtual {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, bytes(""), false);
}
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.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 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;
}
}
}
// SPDX-License-Identifier: MIT
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'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + 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
// 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 Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant alphabet = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../lib/LibArtwork.sol";
/// @title Interface for artwork data storage
/// @author Joe
/// @notice This is the interface for TRLab NFTs artwork data storage.
/// @dev Separating artwork storage from the TRLabCore contract decouples features.
interface IArtworkStore {
/// @notice This event emits when a new artwork has been created.
/// @param artworkId uint256 the id of the new artwork
/// @param creator address the creator address of the artwork
/// @param royaltyReceiver address the receiver address of the artwork second sale royalty
/// @param royaltyBps uint256 the royalty percent in bps
/// @param totalSupply uint256 the maximum tokens can be minted of this artwork
/// @param metadataPath the ipfs path of the artwork metadata
event ArtworkCreated(
uint256 indexed artworkId,
address indexed creator,
address indexed royaltyReceiver,
uint256 royaltyBps,
uint256 totalSupply,
string metadataPath
);
/// @notice This event emits when artwork print id increases.
/// @param artworkId uint256 the id of the new artwork
/// @param increment uint32 the increment of artwork print index
/// @param newPrintIndex uint32 the new print index of this artwork
event ArtworkPrintIndexIncrement(uint256 indexed artworkId, uint32 increment, uint32 newPrintIndex);
/// @notice Creates a new digital artwork object in storage
/// @param _creator address the address of the creator
/// @param _totalSupply uint32 the total allowable prints for this artwork
/// @param _metadataPath string the ipfs metadata path
/// @param _royaltyReceiver address the royalty receiver
/// @param _royaltyBps uint256 the royalty percentage in bps
function createArtwork(
address _creator,
uint32 _totalSupply,
string calldata _metadataPath,
address _royaltyReceiver,
uint256 _royaltyBps
) external returns (uint256);
/// @notice Update Artwork Royalty Info, can only be called by owner at emergency
/// @param _artworkId id of the artwork
/// @param _royaltyReceiver address the royalty receiver
/// @param _royaltyBps uint256 the royalty percentage in bps
function updateArtworkRoyaltyInfo(
uint256 _artworkId,
address _royaltyReceiver,
uint256 _royaltyBps
) external;
/// @notice Update Artwork metadata path (base uri), can only be called by owner at emergency
/// @param _artworkId id of the artwork
/// @param _metadataPath metadata path (base uri)
function updateArtworkMetadataPath(uint256 _artworkId, string memory _metadataPath) external;
/// @notice Increments the current print index of the artwork object, can be triggered by mint or burn.
/// @param _artworkId uint256 the id of the artwork
/// @param _increment uint32 the amount to increment by
function incrementArtworkPrintIndex(uint256 _artworkId, uint32 _increment) external;
/// Retrieves the artwork object by id
/// @param _artworkId uint256 the address of the creator
function getArtwork(uint256 _artworkId) external view returns (LibArtwork.Artwork memory artwork);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../lib/LibArtwork.sol";
/// @title Interface of TRLab NFT core contract
/// @author Joe
/// @notice This is the interface of TRLab NFT core contract
interface ITRLabCore {
/// @notice This event emits when a new NFT token has been minted.
/// @param id uint256 the id of the minted NFT token.
/// @param owner address the address of the token owner.
/// @param artworkId uint256 the id of the artwork of this token.
/// @param printEdition uint32 the print edition of this token.
/// @param tokenURI string the metadata ipfs URI.
event ArtworkReleaseCreated(
uint256 indexed id,
address indexed owner,
uint256 indexed artworkId,
uint32 printEdition,
string tokenURI
);
/// @notice This event emits when a batch of NFT tokens has been minted.
/// @param artworkId uint256 the id of the artwork of this token.
/// @param printEdition uint32 the new print edition of this artwork.
event ArtworkPrintIndexUpdated(uint256 indexed artworkId, uint32 indexed printEdition);
event NewArtworkStore(address indexed storeAddress);
/// @notice This event emits when an artwork has been burned.
/// @param artworkId uint256 the id of the burned artwork.
event ArtworkBurned(uint256 indexed artworkId);
/// @dev get current total supply of NFTs
function totalSupply() external view returns (uint256);
/// @dev sets the artwork store address.
/// @param _storeAddress address the address of the artwork store contract.
function setStoreAddress(address _storeAddress) external;
/// @dev set the royalty of a token. Can only be called by owner at emergency
/// @param _tokenId uint256 the id of the token
/// @param _receiver address the receiver address of the royalty
/// @param _bps uint256 the royalty percentage in bps
function setTokenRoyalty(
uint256 _tokenId,
address _receiver,
uint256 _bps
) external;
/// @dev set the royalty of tokens. Can only be called by owner at emergency
/// @param _tokenIds uint256[] the ids of the token
/// @param _receiver address the receiver address of the royalty
/// @param _bps uint256 the royalty percentage in bps
function setTokensRoyalty(
uint256[] calldata _tokenIds,
address _receiver,
uint256 _bps
) external;
/// @notice Retrieves the artwork object by id
/// @param _artworkId uint256 the address of the creator
/// @return artwork the artwork object
function getArtwork(uint256 _artworkId) external view returns (LibArtwork.Artwork memory artwork);
/// @notice Creates a new artwork object, artwork creator is _msgSender()
/// @param _totalSupply uint32 the total allowable prints for this artwork
/// @param _metadataPath string the ipfs metadata path
/// @param _royaltyReceiver address the royalty receiver
/// @param _royaltyBps uint256 the royalty percentage in bps
function createArtwork(
uint32 _totalSupply,
string calldata _metadataPath,
address _royaltyReceiver,
uint256 _royaltyBps
) external;
/// @notice Creates a new artwork object and mints it's first release token.
/// @dev No creations of any kind are allowed when the contract is paused.
/// @param _totalSupply uint32 the total allowable prints for this artwork
/// @param _metadataPath string the ipfs metadata path
/// @param _numReleases uint32 the number of tokens to be minted
/// @param _royaltyReceiver address the royalty receiver
/// @param _royaltyBps uint256 the royalty percentage in bps
function createArtworkAndReleases(
uint32 _totalSupply,
string calldata _metadataPath,
uint32 _numReleases,
address _royaltyReceiver,
uint256 _royaltyBps
) external;
/// @notice mints tokens of artwork.
/// @dev No creations of any kind are allowed when the contract is paused.
/// @param _artworkId uint256 the id of the artwork
/// @param _numReleases uint32 the number of tokens to be minted
function releaseArtwork(uint256 _artworkId, uint32 _numReleases) external;
/// @notice mints tokens of artwork in behave of receiver. Designed for buy-now contract.
/// @dev No creations of any kind are allowed when the contract is paused.
/// @param _receiver address the owner of the new nft token.
/// @param _artworkId uint256 the id of the artwork.
/// @param _numReleases uint32 the number of tokens to be minted.
function releaseArtworkForReceiver(
address _receiver,
uint256 _artworkId,
uint32 _numReleases
) external;
/// @notice get the next token id
/// @return the last token id
function getNextTokenId() external view returns (uint256);
/// @dev getter function for approvedTokenCreators mapping. Check if caller is approved creator.
/// @param caller address the address of caller to check.
/// @return true if caller is approved creator, otherwise false.
function approvedTokenCreators(address caller) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol";
import "../interfaces/IERC2981Upgradeable.sol";
contract ERC2981Upgradeable is Initializable, IERC2981Upgradeable, ERC165Upgradeable {
event RoyaltySet(uint256 indexed tokenId, Royalty royalty);
// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
struct Royalty {
address receiver;
uint256 bps;
}
// token id -> royalty
mapping(uint256 => Royalty) public royaltyMap;
function __ERC2981_init() internal initializer {
__ERC165_init_unchained();
__ERC2981_init_unchained();
}
function __ERC2981_init_unchained() internal initializer {}
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _salePrice - the sale price of the NFT asset specified by _tokenId
/// @return receiver - address of who should be sent the royalty payment
/// @return royaltyAmount - the royalty payment amount for _salePrice
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
Royalty memory royalty = royaltyMap[_tokenId];
receiver = royalty.receiver;
royaltyAmount = (_salePrice * royalty.bps) / 10000;
}
function _setRoyalty(uint256 _id, Royalty memory _royalty) internal {
// require(_royalty.account != address(0), "Recipient should be present");
require(_royalty.bps <= 10000, "Royalty bps should less than 10000");
royaltyMap[_id] = _royalty;
emit RoyaltySet(_id, _royalty);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* ERC165 bytes to add to interface array - set in parent contract
* implementing this standard
*
* bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
* bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
* _registerInterface(_INTERFACE_ID_ERC2981);
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(IERC2981Upgradeable, ERC165Upgradeable)
returns (bool)
{
return
interfaceId == type(IERC2981Upgradeable).interfaceId ||
interfaceId == _INTERFACE_ID_ERC2981 ||
super.supportsInterface(interfaceId);
}
uint256[46] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library LibArtwork {
struct Artwork {
address creator;
uint32 printIndex;
uint32 totalSupply;
string metadataPath;
address royaltyReceiver;
uint256 royaltyBps; // royaltyBps is a value between 0 to 10000
}
struct ArtworkRelease {
// The unique edition number of this artwork release
uint32 printEdition;
// Reference ID to the artwork metadata
uint256 artworkId;
}
struct ArtworkOnSaleInfo {
address takeTokenAddress; // only accept erc20, should use WETH
uint256 takeAmount;
uint256 startTime; // timestamp in seconds
uint256 endTime;
uint256 purchaseLimit;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal initializer {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal initializer {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(address newImplementation, bytes memory data, bool forceCall) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature(
"upgradeTo(address)",
oldImplementation
)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(
AddressUpgradeable.isContract(newBeacon),
"ERC1967: new beacon is not a contract"
);
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/*
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol";
///
/// @dev Interface for the NFT Royalty Standard
///
interface IERC2981Upgradeable is IERC165Upgradeable {
/// ERC165 bytes to add to interface array - set in parent contract
/// implementing this standard
///
/// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
/// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
/// _registerInterface(_INTERFACE_ID_ERC2981);
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _salePrice - the sale price of the NFT asset specified by _tokenId
/// @return receiver - address of who should be sent the royalty payment
/// @return royaltyAmount - the royalty payment amount for _salePrice
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
/// @notice Informs callers that this contract supports ERC2981
/// @dev If `_registerInterface(_INTERFACE_ID_ERC2981)` is called
/// in the initializer, this should be automatic
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @return `true` if the contract implements
/// `_INTERFACE_ID_ERC2981` and `false` otherwise
function supportsInterface(bytes4 interfaceID) external view override returns (bool);
}
| Perform implementation upgrade with additional setup call. Emits an {Upgraded} event./ | function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
| 1,574,415 |
./partial_match/1/0x508efB44A06a64Bd4020e8c5e8Ecf1A9236C75aE/sources/tokenWhitelistable.sol | Checks whether a token is loadable. return bool loadable or not. | function _isTokenLoadable(address _a) internal view returns (bool) {
(, , , , bool loadable, , ) = _getTokenInfo(_a);
return loadable;
}
| 3,598,122 |
./full_match/5/0xc1E942B282fcB873238aeD8126137f492d81dcFD/sources/contracts/15yrslater.sol | Removes the Offer if the owner no Longer Owns the NFTs | function _removeInvalidOffer(uint256 _tokenId, address _offeror )internal virtual {
TradeOffer memory targetTradeOffer = tradeoffers[_tokenId][_offeror];
delete tradeoffers[_tokenId][_offeror];
emit TradeOfferRemoved(_tokenId, targetTradeOffer.offeror);
}
| 11,587,897 |
// SPDX-License-Identifier: CC-BY-4.0
pragma solidity >=0.4.22 <0.9.0;
import "../common/Owned.sol";
import "../common/Version.sol";
import "./SupplierRole.sol";
import "./ManufacturerRole.sol";
import "./DistributorRole.sol";
import "./ResellerRole.sol";
import "./EndUserRole.sol";
contract SupplyChain is Owned, SupplierRole, ManufacturerRole, DistributorRole, ResellerRole, EndUserRole {
// Define a variable called 'sku' for Stock Keeping Unit (SKU)
uint sku;
uint upc;
// Define a public mapping of the UPC to a Product.
mapping (uint => Product) products;
// Define a public mapping 'history' that maps the UPC to an array of TxHash,
// that track its journey through the supply chain -- to be sent from DApp.
//mapping (uint => Txblocks[]) history;
// Define enum 'State' with the following values:
enum State
{
OrderedFromSupplier, // 0
ShippedBySupplier, // 1
ProduceByManufacturer, // 2
ForSaleByManufacturer, // 3
PurchasedByDistributor, // 4
ShippedByManufacturer, // 5
ReceivedByDistributor, // 6
ProcessedByDistributor, // 7
PackageByDistributor, // 8
ForSaleByDistributor, // 9
PurchasedByReseller, // 10
ShippedByDistributor, // 11
ReceivedByReseller, // 12
ForSaleByReseller, // 13
PurchasedByEndUser // 14
}
State constant defaultState = State.OrderedFromSupplier;
// Define a struct 'Product' with the following fields:
struct Product {
uint sku; // Stock Keeping Unit (SKU)
uint upc; // Universal Product Code (UPC), generated by the Manufacturer, goes on the package, can be verified by the EndUser
uint lot; // Lot number
uint manufacturedDate; // The manufacturing date
address ownerID; // Metamask-Ethereum address of the current owner as the product moves through 8 stages
address distributorID;
address payable originID; // Metamask-Ethereum address of the Manufacturer
string originName; // Winemaker Name
string originInformation; // Winemaker Information
string originLatitude; // Winemaker Latitude
string originLongitude; // Winemaker Longitude
uint productID; // Product ID potentially a combination of upc + sku
string productNotes; // Product Notes
uint productPrice; // Product Price
uint productFinalPrice; // Final price pof the product when sales by the wine merchant
uint productSliced;
State productState; // Product State as represented in the enum above
address payable resellerID; // Metamask-Ethereum address of the Wine Merchant
address payable enduserID; // Metamask-Ethereum address of the EndUser
}
// Block number stuct
struct Txblocks {
uint STM; // blocksupplierToManufacturer
uint MTD; // blockmanufacturerToDistributor
uint DTR; // blockDistributorToReseller
uint RTC; // blockResellerToEnduser
}
event OrderedFromSupplier(uint upc); //1
event ShippedBySupplier(uint upc); //2
event ProduceByManufacturer(uint upc); //2
event ForSaleByManufacturer(uint upc); //3
event PurchasedByDistributor(uint upc); //4
event ShippedByManufacturer(uint upc); //5
event ReceivedByDistributor(uint upc); //6
event ProcessedByDistributor(uint upc); //7
event PackagedByDistributor(uint upc); //8
event ForSaleByDistributor(uint upc); //9
event PurchasedByReseller(uint upc); //10
event ShippedByDistributor(uint upc); //11
event ReceivedByReseller(uint upc); //12
event ForSaleByReseller(uint upc); //13
event PurchasedByEndUser(uint upc); //14
// Define a modifer that verifies the Caller
modifier verifyCaller (address _address) {
require(msg.sender == _address, "");
_;
}
// Define a modifier that checks if the paid amount is sufficient to cover the price
modifier paidEnough(uint _price) {
require(msg.value >= _price, "");
_;
}
// Define a modifier that checks the price and refunds the remaining balance
modifier checkValue(uint _upc, address payable addressToFund) {
uint _price = products[_upc].productPrice;
uint amountToReturn = msg.value - _price;
addressToFund.transfer(amountToReturn);
_;
}
//Product State Modifiers
modifier producedByManufacturer(uint _upc) {
require(products[_upc].productState == State.ProduceByManufacturer, "");
_;
}
modifier forSaleByManufacturer(uint _upc) {
require(products[_upc].productState == State.ForSaleByManufacturer, "");
_;
}
modifier purchasedByDistributor(uint _upc) {
require(products[_upc].productState == State.PurchasedByDistributor, "");
_;
}
modifier shippedByManufacturer(uint _upc) {
require(products[_upc].productState == State.ShippedByManufacturer, "");
_;
}
modifier receivedByDistributor(uint _upc) {
require(products[_upc].productState == State.ReceivedByDistributor, "");
_;
}
modifier processByDistributor(uint _upc) {
require(products[_upc].productState == State.ProcessedByDistributor, "");
_;
}
modifier packagedByDistributor(uint _upc) {
require(products[_upc].productState == State.PackageByDistributor, "");
_;
}
modifier forSaleByDistributor(uint _upc) {
require(products[_upc].productState == State.ForSaleByDistributor, "");
_;
}
modifier shippedByDistributor(uint _upc) {
require(products[_upc].productState == State.ShippedByDistributor, "");
_;
}
modifier purchasedByReseller(uint _upc) {
require(products[_upc].productState == State.PurchasedByReseller, "");
_;
}
modifier receivedByReseller(uint _upc) {
require(products[_upc].productState == State.ReceivedByReseller, "");
_;
}
modifier forSaleByReseller(uint _upc) {
require(products[_upc].productState == State.ForSaleByReseller, "");
_;
}
modifier purchasedByEndUser(uint _upc) {
require(products[_upc].productState == State.PurchasedByEndUser, "");
_;
}
// constructor setup owner sku upc
constructor() payable {
sku = 1;
upc = 1;
}
// Define a function 'kill'
function kill() public {
if (msg.sender == getOwner()) {
address payable ownerAddressPayable = _make_payable(getOwner());
selfdestruct(ownerAddressPayable);
}
}
// allows you to convert an address into a payable address
function _make_payable(address x) internal pure returns (address payable) {
return payable(x);
}
/*
1st step in supplychain
Allows manufacturer to create cheese
*/
function produceProductByManufacturer(
uint _upc,
string memory _originName,
string memory _originInformation,
string memory _originLatitude,
string memory _originLongitude,
string memory _productNotes,
uint _price,
uint256 epoch)
public
payable
onlyManufacturer() // check address belongs to manufacturerRole
{
address distributorID; // Empty distributorID address
address resellerID; // Empty resellerID address
address enduserID; // Empty enduserID address
Product memory newProduce; // Create a new struct Product in memory
newProduce.sku = sku; // Stock Keeping Unit (SKU)
newProduce.upc = _upc; // Universal Product Code (UPC), generated by the Manufacturer, goes on the package, can be verified by the EndUser
newProduce.ownerID = msg.sender; // Metamask-Ethereum address of the current owner as the product moves through 8 stages
newProduce.originID = payable(msg.sender); // Metamask-Ethereum address of the Manufacturer
newProduce.originName = _originName; // Manufacturer Name
newProduce.originInformation = _originInformation; // Manufacturer Information
newProduce.originLatitude = _originLatitude; // Farm Latitude
newProduce.originLongitude = _originLongitude; // Farm Longitude
newProduce.productID = _upc+sku; // Product ID
newProduce.productNotes = _productNotes; // Product Notes
newProduce.productPrice = _price; // Product Price
newProduce.manufacturedDate = epoch;
newProduce.productSliced = 0;
newProduce.productState = defaultState; // Product State as represented in the enum above
newProduce.distributorID = distributorID; // Metamask-Ethereum address of the Distributor
newProduce.resellerID = payable(resellerID); // Metamask-Ethereum address of the Reseller
newProduce.enduserID = payable(enduserID); // Metamask-Ethereum address of the EndUser // ADDED payable
products[_upc] = newProduce; // Add newProduce to products struct by upc
//uint placeholder; // Block number place holder
//Txblocks memory txBlock; // create new txBlock struct
//txBlock.STM = placeholder;
//txBlock.MTD = placeholder; // assign placeholder values
//txBlock.DTR = placeholder;
//txBlock.RTC = placeholder;
//history[_upc] = txBlock; // add txBlock to history mapping by upc
// Increment sku
sku = sku + 1;
// Emit the appropriate event
emit ProduceByManufacturer(_upc);
}
/*
2nd step in supplychain
Allows manufacturer to sell cheese
*/
function sellProductByManufacturer(uint _upc, uint _price) public
onlyManufacturer() // check msg.sender belongs to manufacturerRole
producedByManufacturer(_upc) // check products state has been produced
verifyCaller(products[_upc].ownerID) // check msg.sender is owner
{
products[_upc].productState = State.ForSaleByManufacturer;
products[_upc].productPrice = _price;
emit ForSaleByManufacturer(_upc);
}
/*
3rd step in supplychain
Allows distributor to purchase cheese
*/
function purchaseProductByDistributor(uint _upc)
public
payable
onlyDistributor() // check msg.sender belongs to distributorRole
forSaleByManufacturer(_upc) // check products state is for ForSaleByManufacturer
paidEnough(products[_upc].productPrice) // check if distributor sent enough Ether for cheese
checkValue(_upc, payable(msg.sender)) // check if overpayed return remaing funds back to msg.sender
{
address payable ownerAddressPayable = _make_payable(products[_upc].originID); // make originFarmID payable
ownerAddressPayable.transfer(products[_upc].productPrice); // transfer funds from distributor to manufacturer
products[_upc].ownerID = msg.sender; // update owner
products[_upc].distributorID = msg.sender; // update distributor
products[_upc].productState = State.PurchasedByDistributor; // update state
//history[_upc].STM = block.number; // add block number
emit PurchasedByDistributor(_upc);
}
/*
4th step in supplychain
Allows manufacturer to ship cheese purchased by distributor
*/
function shippedProductByManufacturer(uint _upc) public payable
onlyManufacturer() // check msg.sender belongs to ManufacturerRole
purchasedByDistributor(_upc)
verifyCaller(products[_upc].originID) // check msg.sender is originFarmID
{
products[_upc].productState = State.ShippedByManufacturer; // update state
emit ShippedByManufacturer(_upc);
}
/*
5th step in supplychain
Allows distributor to receive cheese
*/
function receivedProductByDistributor(uint _upc) public
onlyDistributor() // check msg.sender belongs to DistributorRole
shippedByManufacturer(_upc)
verifyCaller(products[_upc].ownerID) // check msg.sender is owner
{
products[_upc].productState = State.ReceivedByDistributor; // update state
emit ReceivedByDistributor(_upc);
}
/*
6th step in supplychain
Allows distributor to process cheese
*/
function processedProductByDistributor(uint _upc,uint slices) public
onlyDistributor() // check msg.sender belongs to DistributorRole
receivedByDistributor(_upc)
verifyCaller(products[_upc].ownerID) // check msg.sender is owner
{
products[_upc].productState = State.ProcessedByDistributor; // update state
products[_upc].productSliced = slices; // add slice amount
emit ProcessedByDistributor(_upc);
}
/*
7th step in supplychain
Allows distributor to package cheese
*/
function packageProductByDistributor(uint _upc) public
onlyDistributor() // check msg.sender belongs to DistributorRole
processByDistributor(_upc)
verifyCaller(products[_upc].ownerID) // check msg.sender is owner
{
products[_upc].productState = State.PackageByDistributor;
emit PackagedByDistributor(_upc);
}
/*
8th step in supplychain
Allows distributor to sell cheese
*/
function sellProductByDistributor(uint _upc, uint _price) public
onlyDistributor() // check msg.sender belongs to DistributorRole
packagedByDistributor(_upc)
verifyCaller(products[_upc].ownerID) // check msg.sender is owner
{
products[_upc].productState = State.ForSaleByDistributor;
products[_upc].productPrice = _price;
emit ForSaleByDistributor(_upc);
}
/*
9th step in supplychain
Allows reseller to purchase cheese
*/
function purchaseProductByReseller(uint _upc) public payable
onlyReseller() // check msg.sender belongs to ResellerRole
forSaleByDistributor(_upc)
paidEnough(products[_upc].productPrice)
checkValue(_upc, payable(msg.sender))
{
address payable ownerAddressPayable = _make_payable(products[_upc].distributorID);
ownerAddressPayable.transfer(products[_upc].productPrice);
products[_upc].ownerID = msg.sender;
products[_upc].resellerID = payable(msg.sender);
products[_upc].productState = State.PurchasedByReseller;
//history[_upc].DTR = block.number;
emit PurchasedByReseller(_upc);
}
/*
10th step in supplychain
Allows Distributor to
*/
function shippedProductByDistributor(uint _upc) public
onlyDistributor() // check msg.sender belongs to DistributorRole
purchasedByReseller(_upc)
verifyCaller(products[_upc].distributorID) // check msg.sender is distributorID
{
products[_upc].productState = State.ShippedByDistributor;
emit ShippedByDistributor(_upc);
}
/*
11th step in supplychain
*/
function receivedProductByReseller(uint _upc) public
onlyReseller() // check msg.sender belongs to ResellerRole
shippedByDistributor(_upc)
verifyCaller(products[_upc].ownerID) // check msg.sender is ownerID
{
products[_upc].productState = State.ReceivedByReseller;
emit ReceivedByReseller(_upc);
}
/*
12th step in supplychain
*/
function sellProductByReseller(uint _upc, uint _price) public
onlyReseller() // check msg.sender belongs to ResellerRole
receivedByReseller(_upc)
verifyCaller(products[_upc].ownerID) // check msg.sender is ownerID
{
products[_upc].productState = State.ForSaleByReseller;
products[_upc].productPrice = _price;
emit ForSaleByReseller(_upc);
}
/*
13th step in supplychain
*/
function purchaseProductByEndUser(uint _upc) public payable
onlyEndUser() // check msg.sender belongs to EndUserRole
forSaleByReseller(_upc)
paidEnough(products[_upc].productPrice)
checkValue(_upc, payable(msg.sender))
{
address payable ownerAddressPayable = _make_payable(products[_upc].resellerID);
ownerAddressPayable.transfer(products[_upc].productPrice);
products[_upc].ownerID = msg.sender;
products[_upc].enduserID = payable(msg.sender);
products[_upc].productState = State.PurchasedByEndUser;
//history[_upc].RTC = block.number;
emit PurchasedByEndUser(_upc);
}
// Define a function 'fetchProductBufferOne' that fetches the data
function fetchProductBufferOne(uint _upc) public view returns
(
uint itemSKU,
uint itemUPC,
address ownerID,
address originManufacturerID,
string memory originName,
string memory originInformation,
string memory originLatitude,
string memory originLongitude,
uint manufacturedDate,
uint productSliced
)
{
// Assign values to the 8 parameters
Product memory item = products[_upc];
return
(
item.sku,
item.upc,
item.ownerID,
item.originID,
item.originName,
item.originInformation,
item.originLatitude,
item.originLongitude,
item.manufacturedDate,
item.productSliced
);
}
// Define a function 'fetchProductBufferTwo' that fetches the data
function fetchProductBufferTwo(uint _upc) public view returns
(
uint itemSKU,
uint itemUPC,
uint productID,
string memory productNotes,
uint productPrice,
uint256 manufacturedDate,
State itemState,
address distributorID,
address resellerID,
address enduserID
)
{
// Assign values to the 9 parameters
Product memory item = products[_upc];
return
(
item.sku,
item.upc,
item.productID,
item.productNotes,
item.productPrice,
item.manufacturedDate,
item.productState,
item.distributorID,
item.resellerID,
item.enduserID
);
}
// Define a function 'fetchProductHistory' that fetaches the data
function fetchitemHistory(uint _upc) public view returns
(
uint blocksupplierToManufacturer,
uint blockmanufacturerToDistributor,
uint blockDistributorToReseller,
uint blockResellerToEndUser
)
{
// Assign value to the parameters
//Txblocks memory txblock = history[_upc];
//return
//(
// txblock.STM,
// txblock.MTD,
// txblock.DTR,
// txblock.RTC
//);
}
} | /uint placeholder; Block number place holderTxblocks memory txBlock; create new txBlock structtxBlock.STM = placeholder;txBlock.MTD = placeholder; assign placeholder valuestxBlock.DTR = placeholder;txBlock.RTC = placeholder;history[_upc] = txBlock; add txBlock to history mapping by upc Increment sku Emit the appropriate event | function produceProductByManufacturer(
uint _upc,
string memory _originName,
string memory _originInformation,
string memory _originLatitude,
string memory _originLongitude,
string memory _productNotes,
uint _price,
uint256 epoch)
public
payable
{
newProduce.manufacturedDate = epoch;
newProduce.productSliced = 0;
sku = sku + 1;
emit ProduceByManufacturer(_upc);
}
Allows manufacturer to sell cheese
| 12,965,813 |
./full_match/1/0x8bC4CbEc17c3b8c0b4e4b7086F9293398c8AC83c/sources/Blingy.sol | 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);
}
| 3,206,970 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ContractDataStorage.sol";
import "./SvgParser.sol";
contract CyberBrokersMetadata is Ownable {
using Strings for uint256;
bool private _useOnChainMetadata = false;
bool private _useIndividualExternalUri = false;
string private _externalUri = "https://cyberbrokers.io/";
string private _imageCacheUri = "ipfs://QmcsrQJMKA9qC9GcEMgdjb9LPN99iDNAg8aQQJLJGpkHxk/";
// Mapping of all layers
struct CyberBrokerLayer {
string key;
string attributeName;
string attributeValue;
}
CyberBrokerLayer[1460] public layerMap;
// Mapping of all talents
struct CyberBrokerTalent {
string talent;
string species;
string class;
string description;
}
CyberBrokerTalent[51] public talentMap;
// Directory of Brokers
uint256[10001] public brokerDna;
// Bitwise constants
uint256 constant private BROKER_MIND_DNA_POSITION = 0;
uint256 constant private BROKER_BODY_DNA_POSITION = 5;
uint256 constant private BROKER_SOUL_DNA_POSITION = 10;
uint256 constant private BROKER_TALENT_DNA_POSITION = 15;
uint256 constant private BROKER_LAYER_COUNT_DNA_POSITION = 21;
uint256 constant private BROKER_LAYERS_DNA_POSITION = 26;
uint256 constant private BROKER_LAYERS_DNA_SIZE = 12;
uint256 constant private BROKER_MIND_DNA_BITMASK = uint256(0x1F);
uint256 constant private BROKER_BODY_DNA_BITMASK = uint256(0x1F);
uint256 constant private BROKER_SOUL_DNA_BITMASK = uint256(0x1F);
uint256 constant private BROKER_TALENT_DNA_BITMASK = uint256(0x2F);
uint256 constant private BROKER_LAYER_COUNT_DNA_BITMASK = uint256(0x1F);
uint256 constant private BROKER_LAYER_DNA_BITMASK = uint256(0x0FFF);
// Contracts
ContractDataStorage public contractDataStorage;
SvgParser public svgParser;
constructor(
address _contractDataStorageAddress,
address _svgParserAddress
) {
// Set the addresses
setContractDataStorageAddress(_contractDataStorageAddress);
setSvgParserAddress(_svgParserAddress);
}
function setContractDataStorageAddress(address _contractDataStorageAddress) public onlyOwner {
contractDataStorage = ContractDataStorage(_contractDataStorageAddress);
}
function setSvgParserAddress(address _svgParserAddress) public onlyOwner {
svgParser = SvgParser(_svgParserAddress);
}
/**
* Save the data on-chain
**/
function setLayers(
uint256[] memory indexes,
string[] memory keys,
string[] memory attributeNames,
string[] memory attributeValues
)
public
onlyOwner
{
require(
indexes.length == keys.length &&
indexes.length == attributeNames.length &&
indexes.length == attributeValues.length,
"Number of indexes much match keys, names and values"
);
for (uint256 idx; idx < indexes.length; idx++) {
uint256 index = indexes[idx];
layerMap[index] = CyberBrokerLayer(keys[idx], attributeNames[idx], attributeValues[idx]);
}
}
function setTalents(
uint256[] memory indexes,
string[] memory talent,
string[] memory species,
string[] memory class,
string[] memory description
)
public
onlyOwner
{
require(
indexes.length == talent.length &&
indexes.length == species.length &&
indexes.length == class.length &&
indexes.length == description.length
, "Number of indexes must match talent, species, class, and description");
for (uint256 idx; idx < indexes.length; idx++) {
uint256 index = indexes[idx];
talentMap[index] = CyberBrokerTalent(talent[idx], species[idx], class[idx], description[idx]);
}
}
function setBrokers(
uint256[] memory indexes,
uint8[] memory talent,
uint8[] memory mind,
uint8[] memory body,
uint8[] memory soul,
uint16[][] memory layers
)
public
onlyOwner
{
require(
indexes.length == talent.length &&
indexes.length == mind.length &&
indexes.length == body.length &&
indexes.length == soul.length &&
indexes.length == layers.length,
"Number of indexes must match talent, mind, body, soul, and layers"
);
for (uint8 idx; idx < indexes.length; idx++) {
require(talent[idx] <= talentMap.length, "Invalid talent index");
require(mind[idx] <= 30, "Invalid mind");
require(body[idx] <= 30, "Invalid body");
require(soul[idx] <= 30, "Invalid soul");
uint256 _dna = (
(uint256(mind[idx]) << BROKER_MIND_DNA_POSITION) +
(uint256(body[idx]) << BROKER_BODY_DNA_POSITION) +
(uint256(soul[idx]) << BROKER_SOUL_DNA_POSITION) +
(uint256(talent[idx]) << BROKER_TALENT_DNA_POSITION) +
(layers[idx].length << BROKER_LAYER_COUNT_DNA_POSITION)
);
for (uint16 layerIdx; layerIdx < layers[idx].length; layerIdx++) {
require(uint256(layers[idx][layerIdx]) <= layerMap.length, "Invalid layer index");
_dna += uint256(layers[idx][layerIdx]) << (BROKER_LAYERS_DNA_SIZE * layerIdx + BROKER_LAYERS_DNA_POSITION);
}
uint256 index = indexes[idx];
brokerDna[index] = _dna;
}
}
/**
* On-Chain Metadata Construction
**/
// REQUIRED for token contract
function hasOnchainMetadata(uint256) public view returns (bool) {
return _useOnChainMetadata;
}
function setOnChainMetadata(bool _state) public onlyOwner {
_useOnChainMetadata = _state;
}
function setExternalUri(string calldata _uri) public onlyOwner {
_externalUri = _uri;
}
function setUseIndividualExternalUri(bool _setting) public onlyOwner {
_useIndividualExternalUri = _setting;
}
function setImageCacheUri(string calldata _uri) public onlyOwner {
_imageCacheUri = _uri;
}
// REQUIRED for token contract
function tokenURI(uint256 tokenId) public view returns (string memory) {
require(tokenId <= 10000, "Invalid tokenId");
// Unpack the name, talent and layers
string memory name = getBrokerName(tokenId);
return string(
abi.encodePacked(
abi.encodePacked(
bytes('data:application/json;utf8,{"name":"'),
name,
bytes('","description":"'),
getDescription(tokenId),
bytes('","external_url":"'),
getExternalUrl(tokenId),
bytes('","image":"'),
getImageCache(tokenId)
),
abi.encodePacked(
bytes('","attributes":['),
getTalentAttributes(tokenId),
getStatAttributes(tokenId),
getLayerAttributes(tokenId),
bytes(']}')
)
)
);
}
function getBrokerName(uint256 _tokenId) public view returns (string memory) {
string memory _key = 'broker-names';
require(contractDataStorage.hasKey(_key), "Broker names are not uploaded");
// Get the broker names
bytes memory brokerNames = contractDataStorage.getData(_key);
// Pull the broker name size
uint256 brokerNameSize = uint256(uint8(brokerNames[_tokenId * 31]));
bytes memory name = new bytes(brokerNameSize);
for (uint256 idx; idx < brokerNameSize; idx++) {
name[idx] = brokerNames[_tokenId * (31) + 1 + idx];
}
return string(name);
}
function getLayers(uint256 tokenId) public view returns (uint256[] memory) {
require(tokenId <= 10000, "Invalid tokenId");
// Get the broker DNA -> layers
uint256 dna = brokerDna[tokenId];
require(dna > 0, "Broker DNA missing for token");
uint256 layerCount = (dna >> BROKER_LAYER_COUNT_DNA_POSITION) & BROKER_LAYER_COUNT_DNA_BITMASK;
uint256[] memory layers = new uint256[](layerCount);
for (uint256 layerIdx; layerIdx < layerCount; layerIdx++) {
layers[layerIdx] = (dna >> (BROKER_LAYERS_DNA_SIZE * layerIdx + BROKER_LAYERS_DNA_POSITION)) & BROKER_LAYER_DNA_BITMASK;
}
return layers;
}
function getDescription(uint256 tokenId) public view returns (string memory) {
CyberBrokerTalent memory talent = getTalent(tokenId);
return talent.description;
}
function getExternalUrl(uint256 tokenId) public view returns (string memory) {
if (_useIndividualExternalUri) {
return string(abi.encodePacked(_externalUri, tokenId.toString()));
}
return _externalUri;
}
function getImageCache(uint256 tokenId) public view returns (string memory) {
return string(abi.encodePacked(_imageCacheUri, tokenId.toString(), ".svg"));
}
function getTalentAttributes(uint256 tokenId) public view returns (string memory) {
CyberBrokerTalent memory talent = getTalent(tokenId);
return string(
abi.encodePacked(
abi.encodePacked(
bytes('{"trait_type": "Talent", "value": "'),
talent.talent,
bytes('"},{"trait_type": "Species", "value": "'),
talent.species
),
abi.encodePacked(
bytes('"},{"trait_type": "Class", "value": "'),
talent.class,
bytes('"},')
)
)
);
}
function getTalent(uint256 tokenId) public view returns (CyberBrokerTalent memory talent) {
require(tokenId <= 10000, "Invalid tokenId");
// Get the broker DNA
uint256 dna = brokerDna[tokenId];
require(dna > 0, "Broker DNA missing for token");
// Get the talent
uint256 talentIndex = (dna >> BROKER_TALENT_DNA_POSITION) & BROKER_TALENT_DNA_BITMASK;
require(talentIndex < talentMap.length, "Invalid talent index");
return talentMap[talentIndex];
}
function getStats(uint256 tokenId) public view returns (uint256 mind, uint256 body, uint256 soul) {
require(tokenId <= 10000, "Invalid tokenId");
// Get the broker DNA
uint256 dna = brokerDna[tokenId];
require(dna > 0, "Broker DNA missing for token");
// Return the mind, body, and soul
return (
(dna >> BROKER_MIND_DNA_POSITION) & BROKER_MIND_DNA_BITMASK,
(dna >> BROKER_BODY_DNA_POSITION) & BROKER_BODY_DNA_BITMASK,
(dna >> BROKER_SOUL_DNA_POSITION) & BROKER_SOUL_DNA_BITMASK
);
}
function getStatAttributes(uint256 tokenId) public view returns (string memory) {
(uint256 mind, uint256 body, uint256 soul) = getStats(tokenId);
return string(
abi.encodePacked(
abi.encodePacked(
bytes('{"trait_type": "Mind", "value": '),
mind.toString(),
bytes('},{"trait_type": "Body", "value": '),
body.toString()
),
abi.encodePacked(
bytes('},{"trait_type": "Soul", "value": '),
soul.toString(),
bytes('}')
)
)
);
}
function getLayerAttributes(uint256 tokenId) public view returns (string memory) {
// Get the layersg
uint256[] memory layers = getLayers(tokenId);
// Get the attribute names for all layers
CyberBrokerLayer[] memory attrLayers = new CyberBrokerLayer[](layers.length);
uint256 maxAttrLayerIdx = 0;
for (uint16 layerIdx; layerIdx < layers.length; layerIdx++) {
CyberBrokerLayer memory attribute = layerMap[layers[layerIdx]];
if (keccak256(abi.encodePacked(attribute.attributeValue)) != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470) {
attrLayers[maxAttrLayerIdx++] = attribute;
}
}
// Compile the attributes
string memory attributes = "";
for (uint16 attrIdx; attrIdx < maxAttrLayerIdx; attrIdx++) {
attributes = string(
abi.encodePacked(
attributes,
bytes(',{"trait_type": "'),
attrLayers[attrIdx].attributeName,
bytes('", "value": "'),
attrLayers[attrIdx].attributeValue,
bytes('"}')
)
);
}
return attributes;
}
/**
* On-Chain Token SVG Rendering
**/
// REQUIRED for token contract
function render(
uint256
)
public
pure
returns (string memory)
{
return string("To render the token on-chain, call CyberBrokersMetadata.renderBroker(_tokenId, _startIndex) or CyberBrokersMetadata._renderBroker(_tokenId, _startIndex, _thresholdCounter) and iterate through the pages starting at _startIndex = 0. To render off-chain and use an off-chain renderer, call CyberBrokersMetadata.getTokenData(_tokenId) to get the raw data. A JavaScript parser is available by calling CyberBrokersMetadata.getOffchainSvgParser().");
}
function renderData(
string memory _key,
uint256 _startIndex
)
public
view
returns (
string memory,
uint256
)
{
return _renderData(_key, _startIndex, 2800);
}
function _renderData(
string memory _key,
uint256 _startIndex,
uint256 _thresholdCounter
)
public
view
returns (
string memory,
uint256
)
{
require(contractDataStorage.hasKey(_key));
return svgParser.parse(contractDataStorage.getData(_key), _startIndex, _thresholdCounter);
}
function renderBroker(
uint256 _tokenId,
uint256 _startIndex
)
public
view
returns (
string memory,
uint256
)
{
return _renderBroker(_tokenId, _startIndex, 2800);
}
function _renderBroker(
uint256 _tokenId,
uint256 _startIndex,
uint256 _thresholdCounter
)
public
view
returns (
string memory,
uint256
)
{
require(_tokenId <= 10000, "Can only render valid token ID");
return svgParser.parse(getTokenData(_tokenId), _startIndex, _thresholdCounter);
}
/**
* Off-Chain Token SVG Rendering
**/
function getTokenData(uint256 _tokenId)
public
view
returns (bytes memory)
{
uint256[] memory layerNumbers = getLayers(_tokenId);
string[] memory layers = new string[](layerNumbers.length);
for (uint256 layerIdx; layerIdx < layerNumbers.length; layerIdx++) {
string memory key = layerMap[layerNumbers[layerIdx]].key;
require(contractDataStorage.hasKey(key), "Key does not exist in contract data storage");
layers[layerIdx] = key;
}
return contractDataStorage.getDataForAll(layers);
}
function getOffchainSvgParser()
public
view
returns (
string memory _output
)
{
string memory _key = 'svg-parser.js';
require(contractDataStorage.hasKey(_key), "Off-chain SVG Parser not uploaded");
return string(contractDataStorage.getData(_key));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// 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
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* Explaining the `init` variable within saveData:
*
* 61_00_00 -- PUSH2 (size)
* 60_00 -- PUSH1 (code position)
* 60_00 -- PUSH1 (mem position)
* 39 CODECOPY
* 61_00_00 PUSH2 (size)
* 60_00 PUSH1 (mem position)
* f3 RETURN
*
**/
contract ContractDataStorage is Ownable {
struct ContractData {
address rawContract;
uint128 size;
uint128 offset;
}
struct ContractDataPages {
uint256 maxPageNumber;
bool exists;
mapping (uint256 => ContractData) pages;
}
mapping (string => ContractDataPages) internal _contractDataPages;
mapping (address => bool) internal _controllers;
constructor() {
updateController(_msgSender(), true);
}
/**
* Access Control
**/
function updateController(address _controller, bool _status) public onlyOwner {
_controllers[_controller] = _status;
}
modifier onlyController() {
require(_controllers[_msgSender()], "ContractDataStorage: caller is not a controller");
_;
}
/**
* Storage & Revocation
**/
function saveData(
string memory _key,
uint128 _pageNumber,
bytes memory _b
)
public
onlyController
{
require(_b.length < 24576, "SvgStorage: Exceeded 24,576 bytes max contract size");
// Create the header for the contract data
bytes memory init = hex"610000_600e_6000_39_610000_6000_f3";
bytes1 size1 = bytes1(uint8(_b.length));
bytes1 size2 = bytes1(uint8(_b.length >> 8));
init[2] = size1;
init[1] = size2;
init[10] = size1;
init[9] = size2;
// Prepare the code for storage in a contract
bytes memory code = abi.encodePacked(init, _b);
// Create the contract
address dataContract;
assembly {
dataContract := create(0, add(code, 32), mload(code))
if eq(dataContract, 0) {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
// Store the record of the contract
saveDataForDeployedContract(
_key,
_pageNumber,
dataContract,
uint128(_b.length),
0
);
}
function saveDataForDeployedContract(
string memory _key,
uint256 _pageNumber,
address dataContract,
uint128 _size,
uint128 _offset
)
public
onlyController
{
// Pull the current data for the contractData
ContractDataPages storage _cdPages = _contractDataPages[_key];
// Store the maximum page
if (_cdPages.maxPageNumber < _pageNumber) {
_cdPages.maxPageNumber = _pageNumber;
}
// Keep track of the existance of this key
_cdPages.exists = true;
// Add the page to the location needed
_cdPages.pages[_pageNumber] = ContractData(
dataContract,
_size,
_offset
);
}
function revokeContractData(
string memory _key
)
public
onlyController
{
delete _contractDataPages[_key];
}
function getSizeOfPages(
string memory _key
)
public
view
returns (uint256)
{
// For all data within the contract data pages, iterate over and compile them
ContractDataPages storage _cdPages = _contractDataPages[_key];
// Determine the total size
uint256 totalSize;
for (uint256 idx; idx <= _cdPages.maxPageNumber; idx++) {
totalSize += _cdPages.pages[idx].size;
}
return totalSize;
}
function getData(
string memory _key
)
public
view
returns (bytes memory)
{
// Get the total size
uint256 totalSize = getSizeOfPages(_key);
// Create a region large enough for all of the data
bytes memory _totalData = new bytes(totalSize);
// Retrieve the pages
ContractDataPages storage _cdPages = _contractDataPages[_key];
// For each page, pull and compile
uint256 currentPointer = 32;
for (uint256 idx; idx <= _cdPages.maxPageNumber; idx++) {
ContractData storage dataPage = _cdPages.pages[idx];
address dataContract = dataPage.rawContract;
uint256 size = uint256(dataPage.size);
uint256 offset = uint256(dataPage.offset);
// Copy directly to total data
assembly {
extcodecopy(dataContract, add(_totalData, currentPointer), offset, size)
}
// Update the current pointer
currentPointer += size;
}
return _totalData;
}
function getDataForAll(string[] memory _keys)
public
view
returns (bytes memory)
{
// Get the total size of all of the keys
uint256 totalSize;
for (uint256 idx; idx < _keys.length; idx++) {
totalSize += getSizeOfPages(_keys[idx]);
}
// Create a region large enough for all of the data
bytes memory _totalData = new bytes(totalSize);
// For each key, pull down all data
uint256 currentPointer = 32;
for (uint256 idx; idx < _keys.length; idx++) {
// Retrieve the set of pages
ContractDataPages storage _cdPages = _contractDataPages[_keys[idx]];
// For each page, pull and compile
for (uint256 innerIdx; innerIdx <= _cdPages.maxPageNumber; innerIdx++) {
ContractData storage dataPage = _cdPages.pages[innerIdx];
address dataContract = dataPage.rawContract;
uint256 size = uint256(dataPage.size);
uint256 offset = uint256(dataPage.offset);
// Copy directly to total data
assembly {
extcodecopy(dataContract, add(_totalData, currentPointer), offset, size)
}
// Update the current pointer
currentPointer += size;
}
}
return _totalData;
}
function hasKey(string memory _key)
public
view
returns (bool)
{
return _contractDataPages[_key].exists;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Utils.sol";
contract SvgParser {
// Limits
uint256 constant DEFAULT_THRESHOLD_COUNTER = 2800;
// Bits & Masks
bytes1 constant tagBit = bytes1(0x80);
bytes1 constant startTagBit = bytes1(0x40);
bytes1 constant tagTypeMask = bytes1(0x3F);
bytes1 constant attributeTypeMask = bytes1(0x7F);
bytes1 constant dCommandBit = bytes1(0x80);
bytes1 constant percentageBit = bytes1(0x40);
bytes1 constant negativeBit = bytes1(0x20);
bytes1 constant decimalBit = bytes1(0x10);
bytes1 constant numberMask = bytes1(0x0F);
bytes1 constant filterInIdBit = bytes1(0x80);
bytes1 constant filterInIdMask = bytes1(0x7F);
// SVG tags
bytes constant SVG_OPEN_TAG = bytes('<?xml version="1.0" encoding="UTF-8"?><svg width="1320px" height="1760px" viewBox="0 0 1320 1760" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">');
bytes constant SVG_CLOSE_TAG = bytes("</svg>");
bytes[25] TAGS = [
bytes("g"),
bytes("polygon"),
bytes("path"),
bytes("circle"),
bytes("defs"),
bytes("linearGradient"),
bytes("stop"),
bytes("rect"),
bytes("polyline"),
bytes("text"),
bytes("tspan"),
bytes("mask"),
bytes("use"),
bytes("ellipse"),
bytes("radialGradient"),
bytes("filter"),
bytes("feColorMatrix"),
bytes("feComposite"),
bytes("feGaussianBlur"),
bytes("feMorphology"),
bytes("feOffset"),
bytes("pattern"),
bytes("feMergeNode"),
bytes("feMerge"),
bytes("INVALIDTAG")
];
bytes[54] ATTRIBUTES = [
bytes("d"),
bytes("points"),
bytes("transform"),
bytes("cx"),
bytes("cy"),
bytes("r"),
bytes("stroke"),
bytes("stroke-width"),
bytes("fill"),
bytes("fill-opacity"),
bytes("translate"),
bytes("rotate"),
bytes("scale"),
bytes("x1"),
bytes("y1"),
bytes("x2"),
bytes("y2"),
bytes("stop-color"),
bytes("offset"),
bytes("stop-opacity"),
bytes("width"),
bytes("height"),
bytes("x"),
bytes("y"),
bytes("font-size"),
bytes("letter-spacing"),
bytes("opacity"),
bytes("id"),
bytes("xlink:href"),
bytes("rx"),
bytes("ry"),
bytes("mask"),
bytes("fx"),
bytes("fy"),
bytes("gradientTransform"),
bytes("filter"),
bytes("filterUnits"),
bytes("result"),
bytes("in"),
bytes("in2"),
bytes("type"),
bytes("values"),
bytes("operator"),
bytes("k1"),
bytes("k2"),
bytes("k3"),
bytes("k4"),
bytes("stdDeviation"),
bytes("edgeMode"),
bytes("radius"),
bytes("fill-rule"),
bytes("dx"),
bytes("dy"),
bytes("INVALIDATTRIBUTE")
];
bytes[2] PAIR_NUMBER_SET_ATTRIBUTES = [
bytes("translate"),
bytes("scale")
];
bytes[4] PAIR_COLOR_ATTRIBUTES = [
bytes("stroke"),
bytes("fill"),
bytes("stop-color"),
bytes("mask")
];
bytes[23] SINGLE_NUMBER_SET_ATTRIBUTES = [
bytes("cx"),
bytes("cy"),
bytes("r"),
bytes("rotate"),
bytes("x1"),
bytes("y1"),
bytes("x2"),
bytes("y2"),
bytes("offset"),
bytes("x"),
bytes("y"),
bytes("rx"),
bytes("ry"),
bytes("fx"),
bytes("fy"),
bytes("font-size"),
bytes("letter-spacing"),
bytes("stroke-width"),
bytes("width"),
bytes("height"),
bytes("fill-opacity"),
bytes("stop-opacity"),
bytes("opacity")
];
bytes[20] D_COMMANDS = [
bytes("M"),
bytes("m"),
bytes("L"),
bytes("l"),
bytes("H"),
bytes("h"),
bytes("V"),
bytes("v"),
bytes("C"),
bytes("c"),
bytes("S"),
bytes("s"),
bytes("Q"),
bytes("q"),
bytes("T"),
bytes("t"),
bytes("A"),
bytes("a"),
bytes("Z"),
bytes("z")
];
bytes[2] FILL_RULE = [
bytes("nonzero"),
bytes("evenodd")
];
bytes[2] FILTER_UNIT = [
bytes("userSpaceOnUse"),
bytes("objectBoundingBox")
];
bytes[6] FILTER_IN = [
bytes("SourceGraphic"),
bytes("SourceAlpha"),
bytes("BackgroundImage"),
bytes("BackgroundAlpha"),
bytes("FillPaint"),
bytes("StrokePaint")
];
bytes[16] FILTER_TYPE = [
bytes("translate"),
bytes("scale"),
bytes("rotate"),
bytes("skewX"),
bytes("skewY"),
bytes("matrix"),
bytes("saturate"),
bytes("hueRotate"),
bytes("luminanceToAlpha"),
bytes("identity"),
bytes("table"),
bytes("discrete"),
bytes("linear"),
bytes("gamma"),
bytes("fractalNoise"),
bytes("turbulence")
];
bytes[9] FILTER_OPERATOR = [
bytes("over"),
bytes("in"),
bytes("out"),
bytes("atop"),
bytes("xor"),
bytes("lighter"),
bytes("arithmetic"),
bytes("erode"),
bytes("dilate")
];
bytes[3] FILTER_EDGEMODE = [
bytes("duplicate"),
bytes("wrap"),
bytes("none")
];
function checkTag(bytes1 line) internal pure returns (bool) {
return line & tagBit > 0;
}
function checkStartTag(bytes1 line) internal pure returns (bool) {
return line & startTagBit > 0;
}
function getTag(bytes1 line) internal view returns (bytes memory) {
uint8 key = uint8(line & tagTypeMask);
if (key >= TAGS.length - 1) {
return TAGS[TAGS.length - 1];
}
return TAGS[key];
}
function getAttribute(bytes1 line) internal view returns (bytes memory) {
uint8 key = uint8(line & attributeTypeMask);
if (key >= ATTRIBUTES.length - 1) {
return ATTRIBUTES[ATTRIBUTES.length - 1];
}
return ATTRIBUTES[key];
}
function compareAttrib(bytes memory attrib, string memory compareTo) internal pure returns (bool) {
return keccak256(attrib) == keccak256(bytes(compareTo));
}
function compareAttrib(bytes memory attrib, bytes storage compareTo) internal pure returns (bool) {
return keccak256(attrib) == keccak256(compareTo);
}
function addOutput(bytes memory _output, uint256 _outputIdx, bytes memory _addendum) internal pure returns (uint256) {
for (uint256 _idx; _idx < _addendum.length; _idx++) {
_output[_outputIdx++] = _addendum[_idx];
}
return _outputIdx;
}
function addOutput(bytes memory _output, uint256 _outputIdx, bytes memory _addendum1, bytes memory _addendum2)
internal pure returns (uint256)
{
return addOutput(_output, addOutput(_output, _outputIdx, _addendum1), _addendum2);
}
function addOutput(bytes memory _output, uint256 _outputIdx, bytes memory _addendum1, bytes memory _addendum2, bytes memory _addendum3)
internal pure returns (uint256)
{
return addOutput(_output, addOutput(_output, addOutput(_output, _outputIdx, _addendum1), _addendum2), _addendum3);
}
function addOutput(bytes memory _output, uint256 _outputIdx, bytes memory _addendum1, bytes memory _addendum2, bytes memory _addendum3, bytes memory _addendum4)
internal pure returns (uint256)
{
return addOutput(_output, addOutput(_output, addOutput(_output, addOutput(_output, _outputIdx, _addendum1), _addendum2), _addendum3), _addendum4);
}
function parse(bytes memory input, uint256 idx) public view returns (string memory, uint256) {
return parse(input, idx, DEFAULT_THRESHOLD_COUNTER);
}
function parse(bytes memory input, uint256 idx, uint256 thresholdCounter) public view returns (string memory, uint256) {
// Keep track of what we're returning
bytes memory output = new bytes(thresholdCounter * 15); // Plenty of padding
uint256 outputIdx = 0;
bool isTagOpen = false;
uint256 counter = idx;
// Start the output with SVG tags if needed
if (idx == 0) {
outputIdx = addOutput(output, outputIdx, SVG_OPEN_TAG);
}
// Go through all bytes we want to review
while (idx < input.length)
{
// Get the current byte
bytes1 _b = bytes1(input[idx]);
// If this is a tag, determine if we're creating a new tag
if (checkTag(_b)) {
// Close the current tag
bool closeTag = false;
if (isTagOpen) {
closeTag = true;
isTagOpen = false;
if ((idx - counter) >= thresholdCounter) {
outputIdx = addOutput(output, outputIdx, bytes(">"));
break;
}
}
// Start the next tag
if (checkStartTag(_b)) {
isTagOpen = true;
if (closeTag) {
outputIdx = addOutput(output, outputIdx, bytes("><"), getTag(_b));
} else {
outputIdx = addOutput(output, outputIdx, bytes("<"), getTag(_b));
}
} else {
// If needed, open and close an end tag
if (closeTag) {
outputIdx = addOutput(output, outputIdx, bytes("></"), getTag(_b), bytes(">"));
} else {
outputIdx = addOutput(output, outputIdx, bytes("</"), getTag(_b), bytes(">"));
}
}
}
else
{
// Attributes
bytes memory attrib = getAttribute(_b);
if (compareAttrib(attrib, "transform") || compareAttrib(attrib, "gradientTransform")) {
// Keep track of which transform we're doing
bool isGradientTransform = compareAttrib(attrib, "gradientTransform");
// Get the next byte & attribute
idx += 2;
_b = bytes1(input[idx]);
attrib = getAttribute(_b);
outputIdx = addOutput(output, outputIdx, bytes(" "), isGradientTransform ? bytes('gradientTransform="') : bytes('transform="'));
while (compareAttrib(attrib, 'translate') || compareAttrib(attrib, 'rotate') || compareAttrib(attrib, 'scale')) {
outputIdx = addOutput(output, outputIdx, bytes(" "));
(idx, outputIdx) = parseAttributeValues(output, outputIdx, attrib, input, idx);
// Get the next byte & attribute
idx += 2;
_b = bytes1(input[idx]);
attrib = getAttribute(_b);
}
outputIdx = addOutput(output, outputIdx, bytes('"'));
// Undo the previous index increment
idx -= 2;
}
else if (compareAttrib(attrib, "d")) {
(idx, outputIdx) = packDPoints(output, outputIdx, input, idx);
}
else if (compareAttrib(attrib, "points"))
{
(idx, outputIdx) = packPoints(output, outputIdx, input, idx, bytes(' points="'));
}
else if (compareAttrib(attrib, "values"))
{
(idx, outputIdx) = packPoints(output, outputIdx, input, idx, bytes(' values="'));
}
else
{
outputIdx = addOutput(output, outputIdx, bytes(" "));
(idx, outputIdx) = parseAttributeValues(output, outputIdx, attrib, input, idx);
}
}
idx += 2;
}
if (idx >= input.length) {
// Close out the SVG tags
outputIdx = addOutput(output, outputIdx, SVG_CLOSE_TAG);
idx = 0;
}
// Pack everything down to the size that actually fits
bytes memory finalOutput = new bytes(outputIdx);
for (uint256 _idx; _idx < outputIdx; _idx++) {
finalOutput[_idx] = output[_idx];
}
return (string(finalOutput), idx);
}
function packDPoints(bytes memory output, uint256 outputIdx, bytes memory input, uint256 idx) internal view returns (uint256, uint256) {
outputIdx = addOutput(output, outputIdx, bytes(' d="'));
// Due to the open-ended nature of points, we concat directly to local_output
idx += 2;
uint256 count = uint256(uint8(input[idx + 1])) * 2**8 + uint256(uint8(input[idx]));
for (uint256 countIdx = 0; countIdx < count; countIdx++) {
idx += 2;
// Add the d command prior to any bits
if (uint8(input[idx + 1] & dCommandBit) > 0) {
outputIdx = addOutput(output, outputIdx, bytes(" "), D_COMMANDS[uint8(input[idx])]);
}
else
{
countIdx++;
outputIdx = addOutput(output, outputIdx, bytes(" "), parseNumberSetValues(input[idx], input[idx + 1]), bytes(","), parseNumberSetValues(input[idx + 2], input[idx + 3]));
idx += 2;
}
}
outputIdx = addOutput(output, outputIdx, bytes('"'));
return (idx, outputIdx);
}
function packPoints(bytes memory output, uint256 outputIdx, bytes memory input, uint256 idx, bytes memory attributePreface) internal view returns (uint256, uint256) {
outputIdx = addOutput(output, outputIdx, attributePreface);
// Due to the open-ended nature of points, we concat directly to local_output
idx += 2;
uint256 count = uint256(uint8(input[idx + 1])) * 2**8 + uint256(uint8(input[idx]));
for (uint256 countIdx = 0; countIdx < count; countIdx++) {
idx += 2;
bytes memory numberSet = parseNumberSetValues(input[idx], input[idx + 1]);
if (countIdx > 0) {
outputIdx = addOutput(output, outputIdx, bytes(" "), numberSet);
} else {
outputIdx = addOutput(output, outputIdx, numberSet);
}
}
outputIdx = addOutput(output, outputIdx, bytes('"'));
return (idx, outputIdx);
}
function parseAttributeValues(
bytes memory output,
uint256 outputIdx,
bytes memory attrib,
bytes memory input,
uint256 idx
)
internal
view
returns (uint256, uint256)
{
// Handled in main function
if (compareAttrib(attrib, "d") || compareAttrib(attrib, "points") || compareAttrib(attrib, "values") || compareAttrib(attrib, 'transform')) {
return (idx + 2, outputIdx);
}
if (compareAttrib(attrib, 'id') || compareAttrib(attrib, 'xlink:href') || compareAttrib(attrib, 'filter') || compareAttrib(attrib, 'result'))
{
bytes memory number = Utils.uint2bytes(
uint256(uint8(input[idx + 2])) * 2**16 +
uint256(uint8(input[idx + 5])) * 2**8 +
uint256(uint8(input[idx + 4]))
);
if (compareAttrib(attrib, 'xlink:href')) {
outputIdx = addOutput(output, outputIdx, attrib, bytes('="#id-'), number, bytes('"'));
} else if (compareAttrib(attrib, 'filter')) {
outputIdx = addOutput(output, outputIdx, attrib, bytes('="url(#id-'), number, bytes(')"'));
} else {
outputIdx = addOutput(output, outputIdx, attrib, bytes('="id-'), number, bytes('"'));
}
return (idx + 4, outputIdx);
}
for (uint256 attribIdx = 0; attribIdx < PAIR_NUMBER_SET_ATTRIBUTES.length; attribIdx++) {
if (compareAttrib(attrib, PAIR_NUMBER_SET_ATTRIBUTES[attribIdx])) {
outputIdx = addOutput(output, outputIdx, attrib, bytes('('), parseNumberSetValues(input[idx + 2], input[idx + 3]), bytes(','));
outputIdx = addOutput(output, outputIdx, parseNumberSetValues(input[idx + 4], input[idx + 5]), bytes(')'));
return (idx + 4, outputIdx);
}
}
for (uint256 attribIdx = 0; attribIdx < PAIR_COLOR_ATTRIBUTES.length; attribIdx++) {
if (compareAttrib(attrib, PAIR_COLOR_ATTRIBUTES[attribIdx])) {
outputIdx = addOutput(output, outputIdx, attrib, bytes('="'), parseColorValues(input[idx + 2], input[idx + 3], input[idx + 4], input[idx + 5]), bytes('"'));
return (idx + 4, outputIdx);
}
}
if (compareAttrib(attrib, 'rotate')) {
// Default, single number set values
outputIdx = addOutput(output, outputIdx, attrib, bytes('('), parseNumberSetValues(input[idx + 2], input[idx + 3]), bytes(')'));
return (idx + 2, outputIdx);
}
// Dictionary lookups
if (compareAttrib(attrib, 'in') || compareAttrib(attrib, 'in2')) {
// Special case for the dictionary lookup for in & in2 => allow for ID lookup
if (uint8(input[idx + 3] & filterInIdBit) > 0) {
bytes memory number = Utils.uint2bytes(
uint256(uint8(input[idx + 2] & filterInIdMask)) * 2**16 +
uint256(uint8(input[idx + 5] & filterInIdMask)) * 2**8 +
uint256(uint8(input[idx + 4]))
);
outputIdx = addOutput(output, outputIdx, attrib, bytes('="id-'), number, bytes('"'));
} else {
outputIdx = addOutput(output, outputIdx, attrib, bytes('="'), FILTER_IN[uint8(input[idx + 2])], bytes('"'));
}
return (idx + 4, outputIdx);
} else if (compareAttrib(attrib, 'type')) {
outputIdx = addOutput(output, outputIdx, attrib, bytes('="'), FILTER_TYPE[uint8(input[idx + 2])], bytes('"'));
return (idx + 2, outputIdx);
} else if (compareAttrib(attrib, 'operator')) {
outputIdx = addOutput(output, outputIdx, attrib, bytes('="'), FILTER_OPERATOR[uint8(input[idx + 2])], bytes('"'));
return (idx + 2, outputIdx);
} else if (compareAttrib(attrib, 'edgeMode')) {
outputIdx = addOutput(output, outputIdx, attrib, bytes('="'), FILTER_EDGEMODE[uint8(input[idx + 2])], bytes('"'));
return (idx + 2, outputIdx);
} else if (compareAttrib(attrib, 'fill-rule')) {
outputIdx = addOutput(output, outputIdx, attrib, bytes('="'), FILL_RULE[uint8(input[idx + 2])], bytes('"'));
return (idx + 2, outputIdx);
} else if (compareAttrib(attrib, 'filterUnits')) {
outputIdx = addOutput(output, outputIdx, attrib, bytes('="'), FILTER_UNIT[uint8(input[idx + 2])], bytes('"'));
return (idx + 2, outputIdx);
}
// Default, single number set values
outputIdx = addOutput(output, outputIdx, attrib, bytes('="'), parseNumberSetValues(input[idx + 2], input[idx + 3]), bytes('"'));
return (idx + 2, outputIdx);
}
function parseColorValues(bytes1 one, bytes1 two, bytes1 three, bytes1 four) internal pure returns (bytes memory) {
if (uint8(two) == 0xFF && uint8(one) == 0 && uint8(four) == 0 && uint8(three) == 0) {
// None identifier case
return bytes("none");
}
else if (uint8(two) == 0x80)
{
// URL identifier case
bytes memory number = Utils.uint2bytes(
uint256(uint8(one)) * 2**16 +
uint256(uint8(four)) * 2**8 +
uint256(uint8(three))
);
return abi.encodePacked("url(#id-", number, ")");
} else {
return Utils.unpackHexColorValues(uint8(one), uint8(four), uint8(three));
}
}
function parseNumberSetValues(bytes1 one, bytes1 two) internal pure returns (bytes memory) {
return Utils.unpackNumberSetValues(
uint256(uint8(two & numberMask)) * 2**8 + uint256(uint8(one)), // number
uint8(two & decimalBit) > 0, // decimal
uint8(two & negativeBit) > 0, // negative
uint8(two & percentageBit) > 0 // percent
);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library Utils {
/**
* From https://github.com/provable-things/ethereum-api/blob/master/oraclizeAPI_0.5.sol
**/
function uint2bytes(uint _i) internal pure returns (bytes memory) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
unchecked {
bstr[k--] = bytes1(uint8(48 + _i % 10));
}
_i /= 10;
}
return bstr;
}
function unpackNumberSetValues(uint _i, bool decimal, bool negative, bool percent) internal pure returns (bytes memory) {
// Base case
if (_i == 0) {
if (percent) {
return "0%";
} else {
return "0";
}
}
// Kick off length with the slots needed to make room for, considering certain bits
uint j = _i;
uint len = (negative ? 1 : 0) + (percent ? 1 : 0) + (decimal ? 2 : 0);
// See how many tens we need
uint numTens;
while (j != 0) {
numTens++;
j /= 10;
}
// Expand length
// Special case: if decimal & numTens is less than 3, need to pad by 3 since we'll left-pad zeroes
if (decimal && numTens < 3) {
len += 3;
} else {
len += numTens;
}
// Now create the byte "string"
bytes memory bstr = new bytes(len);
// Index from right-most to left-most
uint k = len - 1;
// Percent character
if (percent) {
bstr[k--] = bytes1("%");
}
// The entire number
while (_i != 0) {
unchecked {
bstr[k--] = bytes1(uint8(48 + _i % 10));
}
_i /= 10;
}
// If a decimal, we need to left-pad if the numTens isn't enough
if (decimal) {
while (numTens < 3) {
bstr[k--] = bytes1("0");
numTens++;
}
bstr[k--] = bytes1(".");
unchecked {
bstr[k--] = bytes1("0");
}
}
// If negative, the last byte should be negative
if (negative) {
bstr[0] = bytes1("-");
}
return bstr;
}
/**
* Reference pulled from https://gist.github.com/okwme/f3a35193dc4eb9d1d0db65ccf3eb4034
**/
function unpackHexColorValues(uint8 r, uint8 g, uint8 b) internal pure returns (bytes memory) {
bytes memory rHex = Utils.uint2hexchar(r);
bytes memory gHex = Utils.uint2hexchar(g);
bytes memory bHex = Utils.uint2hexchar(b);
bytes memory bstr = new bytes(7);
bstr[6] = bHex[1];
bstr[5] = bHex[0];
bstr[4] = gHex[1];
bstr[3] = gHex[0];
bstr[2] = rHex[1];
bstr[1] = rHex[0];
bstr[0] = bytes1("#");
return bstr;
}
function uint2hexchar(uint8 _i) internal pure returns (bytes memory) {
uint8 mask = 15;
bytes memory bstr = new bytes(2);
bstr[1] = (_i & mask) > 9 ? bytes1(uint8(55 + (_i & mask))) : bytes1(uint8(48 + (_i & mask)));
bstr[0] = ((_i >> 4) & mask) > 9 ? bytes1(uint8(55 + ((_i >> 4) & mask))) : bytes1(uint8(48 + ((_i >> 4) & mask)));
return bstr;
}
} | Base case Expand length Special case: if decimal & numTens is less than 3, need to pad by 3 since we'll left-pad zeroes Percent character The entire number If a decimal, we need to left-pad if the numTens isn't enough If negative, the last byte should be negative | function unpackNumberSetValues(uint _i, bool decimal, bool negative, bool percent) internal pure returns (bytes memory) {
if (_i == 0) {
if (percent) {
return "0%";
return "0";
}
}
uint len = (negative ? 1 : 0) + (percent ? 1 : 0) + (decimal ? 2 : 0);
while (j != 0) {
numTens++;
j /= 10;
}
if (decimal && numTens < 3) {
len += 3;
len += numTens;
}
if (percent) {
bstr[k--] = bytes1("%");
}
while (_i != 0) {
unchecked {
bstr[k--] = bytes1(uint8(48 + _i % 10));
}
_i /= 10;
}
if (decimal) {
while (numTens < 3) {
bstr[k--] = bytes1("0");
numTens++;
}
bstr[k--] = bytes1(".");
unchecked {
bstr[k--] = bytes1("0");
}
}
if (negative) {
bstr[0] = bytes1("-");
}
return bstr;
}
| 1,589,740 |
./full_match/1/0x91A6194F1278f6Cf25ae51B604029075695A74E5/sources/contracts/Vault.sol | Adds a new curve swap pool from an input token to {underlying} _param Swap pool params | function addPool(SwapPoolParam memory _param) external onlyAdmin {
_addPool(_param);
}
| 4,864,825 |
pragma solidity ^0.4.24;
import "./../../TransferManager/ITransferManager.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
/**
* @title Transfer Manager for limiting volume of tokens in a single trade
*/
contract SingleTradeVolumeRestrictionTM is ITransferManager {
using SafeMath for uint256;
bytes32 constant public ADMIN = "ADMIN";
bool public isTransferLimitInPercentage;
uint256 public globalTransferLimitInTokens;
// should be multipled by 10^16. if the transfer percentage is 20%, then globalTransferLimitInPercentage should be 20*10^16
uint256 public globalTransferLimitInPercentage;
// Ignore transactions which are part of the primary issuance
bool public allowPrimaryIssuance = true;
//mapping to store the wallets that are exempted from the volume restriction
mapping(address => bool) public exemptWallets;
//addresses on this list have special transfer restrictions apart from global
mapping(address => uint) public specialTransferLimitsInTokens;
mapping(address => uint) public specialTransferLimitsInPercentages;
event ExemptWalletAdded(address _wallet);
event ExemptWalletRemoved(address _wallet);
event TransferLimitInTokensSet(address _wallet, uint256 _amount);
event TransferLimitInPercentageSet(address _wallet, uint _percentage);
event TransferLimitInPercentageRemoved(address _wallet);
event TransferLimitInTokensRemoved(address _wallet);
event GlobalTransferLimitInTokensSet(uint256 _amount, uint256 _oldAmount);
event GlobalTransferLimitInPercentageSet(uint256 _percentage, uint256 _oldPercentage);
event TransferLimitChangedToTokens();
event TransferLimitChangedtoPercentage();
event SetAllowPrimaryIssuance(bool _allowPrimaryIssuance, uint256 _timestamp);
/**
* @notice Constructor
* @param _securityToken Address of the security token
* @param _polyAddress Address of the polytoken
*/
constructor(address _securityToken, address _polyAddress) public
Module(_securityToken, _polyAddress)
{
}
/** @notice Used to verify the transfer transaction and prevent an account from sending more tokens than allowed in a single transfer
* @param _from Address of the sender
* @param _amount The amount of tokens to transfer
*/
function verifyTransfer(
address _from,
address /* _to */,
uint256 _amount,
bytes /* _data */,
bool /* _isTransfer */
)
public
returns(Result)
{
bool validTransfer;
if (exemptWallets[_from] || paused) return Result.NA;
if (_from == address(0) && allowPrimaryIssuance) {
return Result.NA;
}
if (isTransferLimitInPercentage) {
if(specialTransferLimitsInPercentages[_from] > 0) {
validTransfer = (_amount.mul(10**18).div(ISecurityToken(securityToken).totalSupply())) <= specialTransferLimitsInPercentages[_from];
} else {
validTransfer = (_amount.mul(10**18).div(ISecurityToken(securityToken).totalSupply())) <= globalTransferLimitInPercentage;
}
} else {
if (specialTransferLimitsInTokens[_from] > 0) {
validTransfer = _amount <= specialTransferLimitsInTokens[_from];
} else {
validTransfer = _amount <= globalTransferLimitInTokens;
}
}
if (validTransfer) return Result.NA;
return Result.INVALID;
}
/**
* @notice Used to intialize the variables of the contract
* @param _isTransferLimitInPercentage true if the transfer limit is in percentage else false
* @param _globalTransferLimitInPercentageOrToken transfer limit per single transaction.
*/
function configure(
bool _isTransferLimitInPercentage,
uint256 _globalTransferLimitInPercentageOrToken,
bool _allowPrimaryIssuance
) public onlyFactory {
isTransferLimitInPercentage = _isTransferLimitInPercentage;
if (isTransferLimitInPercentage) {
changeGlobalLimitInPercentage(_globalTransferLimitInPercentageOrToken);
} else {
changeGlobalLimitInTokens(_globalTransferLimitInPercentageOrToken);
}
allowPrimaryIssuance = _allowPrimaryIssuance;
}
/**
* @notice Sets whether or not to consider primary issuance transfers
* @param _allowPrimaryIssuance whether to allow all primary issuance transfers
*/
function setAllowPrimaryIssuance(bool _allowPrimaryIssuance) public withPerm(ADMIN) {
require(_allowPrimaryIssuance != allowPrimaryIssuance, "Must change setting");
allowPrimaryIssuance = _allowPrimaryIssuance;
/*solium-disable-next-line security/no-block-members*/
emit SetAllowPrimaryIssuance(_allowPrimaryIssuance, now);
}
/**
* @notice Changes the manager to use transfer limit as Percentages
* @param _newGlobalTransferLimitInPercentage uint256 new global Transfer Limit In Percentage.
* @dev specialTransferLimits set for wallets have to re-configured
*/
function changeTransferLimitToPercentage(uint256 _newGlobalTransferLimitInPercentage) public withPerm(ADMIN) {
require(!isTransferLimitInPercentage, "Transfer limit already in percentage");
isTransferLimitInPercentage = true;
changeGlobalLimitInPercentage(_newGlobalTransferLimitInPercentage);
emit TransferLimitChangedtoPercentage();
}
/**
* @notice Changes the manager to use transfer limit as tokens
* @param _newGlobalTransferLimit uint256 new global Transfer Limit in tokens.
* @dev specialTransferLimits set for wallets have to re-configured
*/
function changeTransferLimitToTokens(uint _newGlobalTransferLimit) public withPerm(ADMIN) {
require(isTransferLimitInPercentage, "Transfer limit already in tokens");
isTransferLimitInPercentage = false;
changeGlobalLimitInTokens(_newGlobalTransferLimit);
emit TransferLimitChangedToTokens();
}
/**
* @notice Changes the global transfer limit
* @param _newGlobalTransferLimitInTokens new transfer limit in tokens
* @dev This function can be used only when The manager is configured to use limits in tokens
*/
function changeGlobalLimitInTokens(uint256 _newGlobalTransferLimitInTokens) public withPerm(ADMIN) {
require(!isTransferLimitInPercentage, "Transfer limit not set in tokens");
require(_newGlobalTransferLimitInTokens > 0, "Transfer limit has to greater than zero");
emit GlobalTransferLimitInTokensSet(_newGlobalTransferLimitInTokens, globalTransferLimitInTokens);
globalTransferLimitInTokens = _newGlobalTransferLimitInTokens;
}
/**
* @notice Changes the global transfer limit
* @param _newGlobalTransferLimitInPercentage new transfer limit in percentage.
* Multiply the percentage by 10^16. Eg 22% will be 22*10^16
* @dev This function can be used only when The manager is configured to use limits in percentage
*/
function changeGlobalLimitInPercentage(uint256 _newGlobalTransferLimitInPercentage) public withPerm(ADMIN) {
require(isTransferLimitInPercentage, "Transfer limit not set in Percentage");
require(_newGlobalTransferLimitInPercentage > 0 && _newGlobalTransferLimitInPercentage <= 100 * 10 ** 16, "Limit not within [0,100]");
emit GlobalTransferLimitInPercentageSet(_newGlobalTransferLimitInPercentage, globalTransferLimitInPercentage);
globalTransferLimitInPercentage = _newGlobalTransferLimitInPercentage;
}
/**
* @notice Adds an exempt wallet
* @param _wallet exempt wallet address
*/
function addExemptWallet(address _wallet) public withPerm(ADMIN) {
require(_wallet != address(0), "Wallet address cannot be a zero address");
exemptWallets[_wallet] = true;
emit ExemptWalletAdded(_wallet);
}
/**
* @notice Removes an exempt wallet
* @param _wallet exempt wallet address
*/
function removeExemptWallet(address _wallet) public withPerm(ADMIN) {
require(_wallet != address(0), "Wallet address cannot be a zero address");
exemptWallets[_wallet] = false;
emit ExemptWalletRemoved(_wallet);
}
/**
* @notice Adds an array of exempt wallet
* @param _wallets array of exempt wallet addresses
*/
function addExemptWalletMulti(address[] _wallets) public withPerm(ADMIN) {
require(_wallets.length > 0, "Wallets cannot be empty");
for (uint256 i = 0; i < _wallets.length; i++) {
addExemptWallet(_wallets[i]);
}
}
/**
* @notice Removes an array of exempt wallet
* @param _wallets array of exempt wallet addresses
*/
function removeExemptWalletMulti(address[] _wallets) public withPerm(ADMIN) {
require(_wallets.length > 0, "Wallets cannot be empty");
for (uint256 i = 0; i < _wallets.length; i++) {
removeExemptWallet(_wallets[i]);
}
}
/**
* @notice Sets transfer limit per wallet
* @param _wallet wallet address
* @param _transferLimit transfer limit for the wallet in tokens
* @dev the manager has to be configured to use limits in tokens
*/
function setTransferLimitInTokens(address _wallet, uint _transferLimit) public withPerm(ADMIN) {
require(_transferLimit > 0, "Transfer limit has to be greater than 0");
require(!isTransferLimitInPercentage, "Transfer limit not in token amount");
specialTransferLimitsInTokens[_wallet] = _transferLimit;
emit TransferLimitInTokensSet(_wallet, _transferLimit);
}
/**
* @notice Sets transfer limit for a wallet
* @param _wallet wallet address
* @param _transferLimitInPercentage transfer limit for the wallet in percentage.
* Multiply the percentage by 10^16. Eg 22% will be 22*10^16
* @dev The manager has to be configured to use percentages
*/
function setTransferLimitInPercentage(address _wallet, uint _transferLimitInPercentage) public withPerm(ADMIN) {
require(isTransferLimitInPercentage, "Transfer limit not in percentage");
require(_transferLimitInPercentage > 0 && _transferLimitInPercentage <= 100 * 10 ** 16, "Transfer limit not in required range");
specialTransferLimitsInPercentages[_wallet] = _transferLimitInPercentage;
emit TransferLimitInPercentageSet(_wallet, _transferLimitInPercentage);
}
/**
* @notice Removes transfer limit set in percentage for a wallet
* @param _wallet wallet address
*/
function removeTransferLimitInPercentage(address _wallet) public withPerm(ADMIN) {
require(specialTransferLimitsInPercentages[_wallet] > 0, "Wallet Address does not have a transfer limit");
specialTransferLimitsInPercentages[_wallet] = 0;
emit TransferLimitInPercentageRemoved(_wallet);
}
/**
* @notice Removes transfer limit set in tokens for a wallet
* @param _wallet wallet address
*/
function removeTransferLimitInTokens(address _wallet) public withPerm(ADMIN) {
require(specialTransferLimitsInTokens[_wallet] > 0, "Wallet Address does not have a transfer limit");
specialTransferLimitsInTokens[_wallet] = 0;
emit TransferLimitInTokensRemoved(_wallet);
}
/**
* @notice Sets transfer limits for an array of wallet
* @param _wallets array of wallet addresses
* @param _transferLimits array of transfer limits for each wallet in tokens
* @dev The manager has to be configured to use tokens as limit
*/
function setTransferLimitInTokensMulti(address[] _wallets, uint[] _transferLimits) public withPerm(ADMIN) {
require(_wallets.length > 0, "Wallets cannot be empty");
require(_wallets.length == _transferLimits.length, "Wallets don't match to transfer limits");
for (uint256 i = 0; i < _wallets.length; i++ ) {
setTransferLimitInTokens(_wallets[i], _transferLimits[i]);
}
}
/**
* @notice Sets transfer limits for an array of wallet
* @param _wallets array of wallet addresses
* @param _transferLimitsInPercentage array of transfer limits for each wallet in percentages
* The percentage has to be multipled by 10 ** 16. Eg: 20% would be 20 * 10 ** 16
* @dev The manager has to be configured to use percentage as limit
*/
function setTransferLimitInPercentageMulti(address[] _wallets, uint[] _transferLimitsInPercentage) public withPerm(ADMIN) {
require(_wallets.length > 0, "Wallets cannot be empty");
require(_wallets.length == _transferLimitsInPercentage.length, "Wallets don't match to percentage limits");
for (uint256 i = 0; i < _wallets.length; i++) {
setTransferLimitInPercentage(_wallets[i], _transferLimitsInPercentage[i]);
}
}
/**
* @notice Removes transfer limits set in tokens for an array of wallet
* @param _wallets array of wallet addresses
*/
function removeTransferLimitInTokensMulti(address[] _wallets) public withPerm(ADMIN) {
require(_wallets.length > 0, "Wallets cannot be empty");
for (uint i = 0; i < _wallets.length; i++) {
removeTransferLimitInTokens(_wallets[i]);
}
}
/**
* @notice Removes transfer limits set in percentage for an array of wallet
* @param _wallets array of wallet addresses
*/
function removeTransferLimitInPercentageMulti(address[] _wallets) public withPerm(ADMIN) {
require(_wallets.length > 0, "Wallets cannot be empty");
for (uint i = 0; i < _wallets.length; i++) {
removeTransferLimitInPercentage(_wallets[i]);
}
}
/**
* @notice This function returns the signature of configure function
*/
function getInitFunction() public pure returns (bytes4) {
return bytes4(keccak256("configure(bool,uint256,bool)"));
}
/**
* @notice Returns the permissions flag that are associated with SingleTradeVolumeRestrictionManager
*/
function getPermissions() public view returns(bytes32[]) {
bytes32[] memory allPermissions = new bytes32[](1);
allPermissions[0] = ADMIN;
return allPermissions;
}
}
| Sets transfer limits for an array of wallet _wallets array of wallet addresses _transferLimits array of transfer limits for each wallet in tokens The manager has to be configured to use tokens as limit/ | function setTransferLimitInTokensMulti(address[] _wallets, uint[] _transferLimits) public withPerm(ADMIN) {
require(_wallets.length > 0, "Wallets cannot be empty");
require(_wallets.length == _transferLimits.length, "Wallets don't match to transfer limits");
for (uint256 i = 0; i < _wallets.length; i++ ) {
setTransferLimitInTokens(_wallets[i], _transferLimits[i]);
}
}
| 14,036,742 |
./full_match/44787/0xE03639b06Be343BC0898FAaA8463EcF6E5c14869/sources/contracts/SpacetarContract.sol | Function to get the total point balance of all users | function getTotalPointBalance() public view onlyRole(ADMIN_ROLE) returns (uint256) {
uint256 totalBalance = 0;
for (uint256 i = 0; i < spacetarChats.length; i++) {
totalBalance += userPoints[spacetarChats[i].user];
}
return totalBalance;
}
| 13,260,752 |
/***
* ██████╗ ██╗ ██╗███╗ ██╗ █████╗ ██████╗ ██╗ ███████╗
* ██╔═══██╗██║ ██║████╗ ██║██╔══██╗██╔══██╗██║ ██╔════╝
* ██║ ██║██║ █╗ ██║██╔██╗ ██║███████║██████╔╝██║ █████╗
* ██║ ██║██║███╗██║██║╚██╗██║██╔══██║██╔══██╗██║ ██╔══╝
* ╚██████╔╝╚███╔███╔╝██║ ╚████║██║ ██║██████╔╝███████╗███████╗
* ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚═╝ ╚═╝╚═════╝ ╚══════╝╚══════╝
* This is a re-write of @openzeppelin/contracts/access/Ownable.sol
* Rewritten by MaxFlowO2, Senior Developer and Partner of G&M² Labs
* Follow me on https://github.com/MaxflowO2 or Twitter @MaxFlowO2
* email: [email protected]
*
* Upgraded to push/pull and decline by @MaxFlowO2 on 31 Dec 2021
* Updated to ContextV2, and removed ERC165 calculations on 31 Dec 2021
*/
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.3.2
// Rewritten for onlyOwner modifier
pragma solidity >=0.8.0 <0.9.0;
import "../utils/ContextV2.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (a 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 {transferOwner}.
*
* 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 OwnableV2 is ContextV2 {
address private _Owner;
address private _newOwner;
event OwnerTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial Owner.
*/
constructor() {
_transferOwner(_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(), "Owner: 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 renounceOwner() public virtual onlyOwner {
_transferOwner(address(0));
}
/**
* @dev Transfers Owner of the contract to a new account (`newOwner`).
* Can only be called by the current Owner. Now push/pull.
*/
function transferOwner(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Owner: new Owner is the zero address");
_newOwner = newOwner;
}
/**
* @dev Accepts Transfer Owner of the contract to a new account (`newOwner`).
* Can only be called by the new Owner. Pull Accepted.
*/
function acceptOwner() public virtual {
require(_newOwner == _msgSender(), "New Owner: new Owner is the only caller");
_transferOwner(_newOwner);
}
/**
* @dev Declines Transfer Owner of the contract to a new account (`newOwner`).
* Can only be called by the new Owner. Pull Declined.
*/
function declineOwner() public virtual {
require(_newOwner == _msgSender(), "New Owner: new Owner is the only caller");
_newOwner = address(0);
}
/**
* @dev Transfers Owner of the contract to a new account (`newOwner`).
* Can only be called by the current Owner. Now push only. Orginal V1 style
*/
function pushOwner(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Owner: new Owner is the zero address");
_transferOwner(newOwner);
}
/**
* @dev Transfers Owner of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwner(address newOwner) internal virtual {
address oldOwner = _Owner;
_Owner = newOwner;
emit OwnerTransferred(oldOwner, newOwner);
}
}
| Transfers Owner of the contract to a new account (`newOwner`). Can only be called by the current Owner. Now push/pull./ | function transferOwner(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Owner: new Owner is the zero address");
_newOwner = newOwner;
}
| 5,371,918 |
./full_match/4/0x0199C6242d1ca20E05b88Da441C43F771498d8FB/sources/browser/Comptroller.sol | Checks if the account should be allowed to borrow the underlying asset of the given market cToken The market to verify the borrow against borrower The account which would borrow the asset 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)/ Pausing is a very serious situation - we revert to sound the alarms only cTokens may call borrowAllowed if borrower not in market attempt to add borrower to the market Borrow cap of 0 corresponds to unlimited borrowing | function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint) {
require(!borrowGuardianPaused[cToken], "borrow is paused");
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[cToken].accountMembership[borrower]) {
require(msg.sender == cToken, "sender must be cToken");
Error err = addToMarketInternal(CToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
}
if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[cToken];
if (borrowCap != 0) {
uint totalBorrows = CToken(cToken).totalBorrows();
(MathError mathErr, uint nextTotalBorrows) = addUInt(totalBorrows, borrowAmount);
require(mathErr == MathError.NO_ERROR, "total borrows overflow");
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
updateCompBorrowIndex(cToken, borrowIndex);
distributeBorrowerComp(cToken, borrower, borrowIndex, false);
return uint(Error.NO_ERROR);
}
| 760,680 |
pragma solidity ^0.5.0;
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: openzeppelin-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 private _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 () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_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: contracts/Referral.sol
contract Referral is Ownable {
using SafeMath for uint256;
uint32 private managerTokenReward;
uint32 private managerEthReward;
uint32 private managerCustomerReward;
uint32 private referralTokenReward;
uint32 private referralCustomerReward;
function setManagerReward(uint32 tokenReward, uint32 ethReward, uint32 customerReward) public onlyOwner returns(bool){
managerTokenReward = tokenReward;
managerEthReward = ethReward;
managerCustomerReward = customerReward;
return true;
}
function setReferralReward(uint32 tokenReward, uint32 customerReward) public onlyOwner returns(bool){
referralTokenReward = tokenReward;
referralCustomerReward = customerReward;
return true;
}
function getManagerTokenReward() public view returns (uint32){
return managerTokenReward;
}
function getManagerEthReward() public view returns (uint32){
return managerEthReward;
}
function getManagerCustomerReward() public view returns (uint32){
return managerCustomerReward;
}
function getReferralTokenReward() public view returns (uint32){
return referralTokenReward;
}
function getReferralCustomerReward() public view returns (uint32){
return referralCustomerReward;
}
function getCustomerReward(address referral, uint256 amount, bool isSalesManager) public view returns (uint256){
uint256 reward = 0;
if (isSalesManager){
reward = amount.mul(managerCustomerReward).div(1000);
} else {
reward = amount.mul(referralCustomerReward).div(1000);
}
return reward;
}
function getEthReward(uint256 amount) public view returns (uint256){
uint256 reward = amount.mul(managerEthReward).div(1000);
return reward;
}
function getTokenReward(address referral, uint256 amount, bool isSalesManager) public view returns (uint256){
uint256 reward = 0;
if (isSalesManager){
reward = amount.mul(managerTokenReward).div(1000);
} else {
reward = amount.mul(referralTokenReward).div(1000);
}
return reward;
}
}
// File: contracts/Whitelisted.sol
contract Whitelisted is Ownable {
mapping (address => uint16) public whitelist;
mapping (address => bool) public provider;
mapping (address => bool) public salesManager;
// Only whitelisted
modifier onlyWhitelisted {
require(isWhitelisted(msg.sender));
_;
}
modifier onlyProvider {
require(isProvider(msg.sender));
_;
}
// Check if address is KYC provider
function isProvider(address _provider) public view returns (bool){
if (owner() == _provider){
return true;
}
return provider[_provider] == true ? true : false;
}
// Check if address is Sales manager
function isSalesManager(address _manager) public view returns (bool){
if (owner() == _manager){
return true;
}
return salesManager[_manager] == true ? true : false;
}
// Set new provider
function setProvider(address _provider) public onlyOwner {
provider[_provider] = true;
}
// Deactive current provider
function deactivateProvider(address _provider) public onlyOwner {
require(provider[_provider] == true);
provider[_provider] = false;
}
// Set new provider
function setSalesManager(address _manager) public onlyOwner {
salesManager[_manager] = true;
}
// Deactive current provider
function deactivateSalesManager(address _manager) public onlyOwner {
require(salesManager[_manager] == true);
salesManager[_manager] = false;
}
// Set purchaser to whitelist with zone code
function setWhitelisted(address _purchaser, uint16 _zone) public onlyProvider {
whitelist[_purchaser] = _zone;
}
// Delete purchaser from whitelist
function deleteFromWhitelist(address _purchaser) public onlyProvider {
whitelist[_purchaser] = 0;
}
// Get purchaser zone code
function getWhitelistedZone(address _purchaser) public view returns(uint16) {
return whitelist[_purchaser] > 0 ? whitelist[_purchaser] : 0;
}
// Check if purchaser is whitelisted : return true or false
function isWhitelisted(address _purchaser) public view returns (bool){
return whitelist[_purchaser] > 0;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
require(token.transferFrom(from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require((value == 0) || (token.allowance(msg.sender, spender) == 0));
require(token.approve(spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
require(token.approve(spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
require(token.approve(spender, newAllowance));
}
}
// File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol
/**
* @title Helps contracts guard against reentrancy attacks.
* @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]>
* @dev If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @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() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
}
// File: openzeppelin-solidity/contracts/crowdsale/Crowdsale.sol
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/
contract Crowdsale is ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address payable private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param rate Number of token units a buyer gets per wei
* @dev The rate is the conversion between wei and the smallest and indivisible
* token unit. So, if you are using a rate of 1 with a ERC20Detailed token
* with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK.
* @param wallet Address where collected funds will be forwarded to
* @param token Address of the token being sold
*/
constructor (uint256 rate, address payable wallet, IERC20 token) public {
require(rate > 0);
require(wallet != address(0));
require(address(token) != address(0));
_rate = rate;
_wallet = wallet;
_token = token;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer fund with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
// function () external payable {
// buyTokens(msg.sender);
// }
/**
* @return the token being sold.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary, address payable referral) public nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, tokens);
emit TokensPurchased(msg.sender, beneficiary, weiAmount, tokens);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met.
* Use `super` in contracts that inherit from Crowdsale to extend their validations.
* Example from CappedCrowdsale.sol's _preValidatePurchase method:
* super._preValidatePurchase(beneficiary, weiAmount);
* require(weiRaised().add(weiAmount) <= cap);
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
require(beneficiary != address(0));
require(weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
* conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
_token.safeTransfer(beneficiary, tokenAmount);
}
function _changeRate(uint256 rate) internal {
_rate = rate;
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
_deliverTokens(beneficiary, tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
return weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
}
// File: openzeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 private _openingTime;
uint256 private _closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(isOpen());
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param openingTime Crowdsale opening time
* @param closingTime Crowdsale closing time
*/
constructor (uint256 openingTime, uint256 closingTime) public {
// solhint-disable-next-line not-rely-on-time
// require(openingTime >= block.timestamp);
require(closingTime > openingTime);
_openingTime = openingTime;
_closingTime = closingTime;
}
/**
* @return the crowdsale opening time.
*/
function openingTime() public view returns (uint256) {
return _openingTime;
}
/**
* @return the crowdsale closing time.
*/
function closingTime() public view returns (uint256) {
return _closingTime;
}
/**
* @return true if the crowdsale is open, false otherwise.
*/
function isOpen() public view returns (bool) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp >= _openingTime && block.timestamp <= _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp > _closingTime;
}
function _changeClosingTime(uint256 closingTime) internal {
_closingTime = closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param beneficiary Token purchaser
* @param weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal onlyWhileOpen view {
super._preValidatePurchase(beneficiary, weiAmount);
}
}
// File: openzeppelin-solidity/contracts/crowdsale/distribution/PostDeliveryCrowdsale.sol
/**
* @title PostDeliveryCrowdsale
* @dev Crowdsale that locks tokens from withdrawal until it ends.
*/
contract PostDeliveryCrowdsale is TimedCrowdsale {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
/**
* @dev Withdraw tokens only after crowdsale ends.
* @param beneficiary Whose tokens will be withdrawn.
*/
function withdrawTokens(address beneficiary) public {
require(hasClosed());
uint256 amount = _balances[beneficiary];
require(amount > 0);
_balances[beneficiary] = 0;
_deliverTokens(beneficiary, amount);
}
/**
* @return the balance of an account.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev Overrides parent by storing balances instead of issuing tokens right away.
* @param beneficiary Token purchaser
* @param tokenAmount Amount of tokens purchased
*/
function _processPurchase(address beneficiary, uint256 tokenAmount) internal {
_balances[beneficiary] = _balances[beneficiary].add(tokenAmount);
}
}
// File: openzeppelin-solidity/contracts/math/Math.sol
/**
* @title Math
* @dev Assorted math operations
*/
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 Calculates the average of two numbers. Since these are integers,
* averages of an even and odd number cannot be represented, and will be
* rounded down.
*/
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-solidity/contracts/crowdsale/emission/AllowanceCrowdsale.sol
/**
* @title AllowanceCrowdsale
* @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale.
*/
contract AllowanceCrowdsale is Crowdsale {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address private _tokenWallet;
/**
* @dev Constructor, takes token wallet address.
* @param tokenWallet Address holding the tokens, which has approved allowance to the crowdsale
*/
constructor (address tokenWallet) public {
require(tokenWallet != address(0));
_tokenWallet = tokenWallet;
}
/**
* @return the address of the wallet that will hold the tokens.
*/
function tokenWallet() public view returns (address) {
return _tokenWallet;
}
/**
* @dev Checks the amount of tokens left in the allowance.
* @return Amount of tokens left in the allowance
*/
function remainingTokens() public view returns (uint256) {
return Math.min(token().balanceOf(_tokenWallet), token().allowance(_tokenWallet, address(this)));
}
/**
* @dev Overrides parent behavior by transferring tokens from wallet.
* @param beneficiary Token purchaser
* @param tokenAmount Amount of tokens purchased
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
token().safeTransferFrom(_tokenWallet, beneficiary, tokenAmount);
}
}
// File: contracts/MocoCrowdsale.sol
contract MocoCrowdsale is TimedCrowdsale, AllowanceCrowdsale, Whitelisted, Referral {
// Amount of wei raised
uint256 public bonusPeriod;
uint256 public bonusAmount;
uint256 private _weiRaised;
uint256 private _weiRefRaised;
uint256 private _totalManagerRewards;
uint256 private _minAmount;
// Unlock period 1 - 6 month
uint256 private _unlock1;
// Unlock period 2 - 12 month
uint256 private _unlock2;
// Specify locked zone for 2nd period
uint8 private _lockedZone;
// Total tokens distributed
uint256 private _totalTokensDistributed;
// Total tokens locked
uint256 private _totalTokensLocked;
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
address indexed referral,
uint256 value,
uint256 amount,
uint256 valueReward,
uint256 tokenReward
);
event LockTokens(
address indexed beneficiary,
uint256 tokenAmount
);
mapping (address => uint256) private _balances;
constructor(
uint256 _openingTime,
uint256 _closingTime,
uint256 _unlockPeriod1,
uint256 _unlockPeriod2,
uint256 _bonusPeriodEnd,
uint256 _bonusAmount,
uint256 rate,
uint256 minAmount,
address payable _wallet,
IERC20 _token,
address _tokenWallet
) public
TimedCrowdsale(_openingTime, _closingTime)
Crowdsale(rate, _wallet, _token)
AllowanceCrowdsale(_tokenWallet){
_unlock1 = _unlockPeriod1;
_unlock2 = _unlockPeriod2;
bonusPeriod = _bonusPeriodEnd;
bonusAmount = _bonusAmount;
_minAmount = minAmount;
}
//
function setMinAmount(uint256 minAmount) public onlyOwner returns (bool){
_minAmount = minAmount;
return true;
}
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
function weiRefRaised() public view returns (uint256) {
return _weiRefRaised;
}
function totalManagerRewards() public view returns (uint256) {
return _totalManagerRewards;
}
function changeRate(uint256 rate) public onlyOwner returns (bool){
super._changeRate(rate);
return true;
}
function changeClosingTime(uint256 closingTime) public onlyOwner returns (bool){
super._changeClosingTime(closingTime);
}
function _getTokenAmount(uint256 weiAmount)
internal view returns (uint256)
{
return weiAmount.mul(rate());
}
function minAmount() public view returns (uint256) {
return _minAmount;
}
// Buy Tokens
function buyTokens(address beneficiary, address payable referral) public onlyWhitelisted payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
_weiRaised = _weiRaised.add(weiAmount);
uint256 ethReward = 0;
uint256 tokenReward = 0;
uint256 customerReward = 0;
uint256 initTokens = tokens;
if (beneficiary != referral && isWhitelisted(referral)){
customerReward = getCustomerReward(referral, tokens, isSalesManager(referral));
if (isSalesManager(referral)){
ethReward = getEthReward(weiAmount);
_totalManagerRewards = _totalManagerRewards.add(ethReward);
}
tokenReward = getTokenReward(referral, initTokens, isSalesManager(referral));
_processReward(referral, ethReward, tokenReward);
_weiRefRaised = _weiRefRaised.add(weiAmount);
}
uint256 bonusTokens = getBonusAmount(initTokens);
bonusTokens = bonusTokens.add(customerReward);
tokens = tokens.add(bonusTokens);
_processPurchase(beneficiary, initTokens, bonusTokens);
emit TokensPurchased(
msg.sender,
beneficiary,
referral,
weiAmount,
tokens,
ethReward,
tokenReward
);
uint256 weiForward = weiAmount.sub(ethReward);
wallet().transfer(weiForward);
}
function _processReward(
address payable referral,
uint256 weiAmount,
uint256 tokenAmount
)
internal
{
_balances[referral] = _balances[referral].add(tokenAmount);
emit LockTokens(referral, tokenAmount);
if (isSalesManager(referral) && weiAmount > 0){
referral.transfer(weiAmount);
}
}
// Check if locked is end
function lockedHasEnd() public view returns (bool) {
return block.timestamp > _unlock1 ? true : false;
}
// Check if locked is end
function lockedTwoHasEnd() public view returns (bool) {
return block.timestamp > _unlock2 ? true : false;
}
// Withdraw tokens after locked period is finished
function withdrawTokens(address beneficiary) public {
require(lockedHasEnd());
uint256 amount = _balances[beneficiary];
require(amount > 0);
uint256 zone = super.getWhitelistedZone(beneficiary);
if (zone == 840){
// require(lockedTwoHasEnd());
if(lockedTwoHasEnd()){
_balances[beneficiary] = 0;
_deliverTokens(beneficiary, amount);
}
} else {
_balances[beneficiary] = 0;
_deliverTokens(beneficiary, amount);
}
}
// Locked tokens balance
function balanceOf(address account) public view returns(uint256) {
return _balances[account];
}
// Pre validation token buy
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
view
{
require(beneficiary != address(0));
require(weiAmount >= minAmount());
}
function getBonusAmount(uint256 _tokenAmount) public view returns(uint256) {
return block.timestamp < bonusPeriod ? _tokenAmount.mul(bonusAmount).div(1000) : 0;
}
function calculateTokens(uint256 _weiAmount) public view returns(uint256) {
uint256 tokens = _getTokenAmount(_weiAmount);
return tokens + getBonusAmount(tokens);
}
function lockedTokens(address beneficiary, uint256 tokenAmount) public onlyOwner returns(bool) {
_balances[beneficiary] = _balances[beneficiary].add(tokenAmount);
emit LockTokens(beneficiary, tokenAmount);
return true;
}
function _processPurchase(
address beneficiary,
uint256 tokenAmount,
uint256 bonusTokens
)
internal
{
uint256 zone = super.getWhitelistedZone(beneficiary);
if (zone == 840){
uint256 totalTokens = bonusTokens.add(tokenAmount);
_balances[beneficiary] = _balances[beneficiary].add(totalTokens);
emit LockTokens(beneficiary, tokenAmount);
}
else {
super._deliverTokens(beneficiary, tokenAmount);
_balances[beneficiary] = _balances[beneficiary].add(bonusTokens);
emit LockTokens(beneficiary, tokenAmount);
}
}
} | Check if address is Sales manager | function isSalesManager(address _manager) public view returns (bool){
if (owner() == _manager){
return true;
}
return salesManager[_manager] == true ? true : false;
}
| 1,820,328 |
./full_match/1/0xd3FCf40bc00ce800066E9f16608c5545Ff530531/sources/contracts/MultiSenderV1.sol | solhint-disable not-rely-on-time | function registerVIP(address[] memory beneficiarys, uint256 duration)
public
onlyOwner
{
for (uint256 i = 0; i < beneficiarys.length; i++) {
if (vipMap[beneficiarys[i]].startedAt == 0) {
vipMap[beneficiarys[i]].startedAt = block.timestamp;
vips.push(beneficiarys[i]);
vipMap[beneficiarys[i]].expiredAt = block.timestamp + duration;
vipMap[beneficiarys[i]].expiredAt =
vipMap[beneficiarys[i]].expiredAt +
duration;
}
}
}
| 9,625,824 |
// SPDX-License-Identifier: AGPL-3.0-only
/*
ValidatorService.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol";
import "../Permissions.sol";
import "../ConstantsHolder.sol";
import "./DelegationController.sol";
import "./TimeHelpers.sol";
/**
* @title ValidatorService
* @dev This contract handles all validator operations including registration,
* node management, validator-specific delegation parameters, and more.
*
* TIP: For more information see our main instructions
* https://forum.skale.network/t/skale-mainnet-launch-faq/182[SKALE MainNet Launch FAQ].
*
* Validators register an address, and use this address to accept delegations and
* register nodes.
*/
contract ValidatorService is Permissions {
using ECDSA for bytes32;
struct Validator {
string name;
address validatorAddress;
address requestedAddress;
string description;
uint feeRate;
uint registrationTime;
uint minimumDelegationAmount;
bool acceptNewRequests;
}
/**
* @dev Emitted when a validator registers.
*/
event ValidatorRegistered(
uint validatorId
);
/**
* @dev Emitted when a validator address changes.
*/
event ValidatorAddressChanged(
uint validatorId,
address newAddress
);
/**
* @dev Emitted when a validator is enabled.
*/
event ValidatorWasEnabled(
uint validatorId
);
/**
* @dev Emitted when a validator is disabled.
*/
event ValidatorWasDisabled(
uint validatorId
);
/**
* @dev Emitted when a node address is linked to a validator.
*/
event NodeAddressWasAdded(
uint validatorId,
address nodeAddress
);
/**
* @dev Emitted when a node address is unlinked from a validator.
*/
event NodeAddressWasRemoved(
uint validatorId,
address nodeAddress
);
mapping (uint => Validator) public validators;
mapping (uint => bool) private _trustedValidators;
uint[] public trustedValidatorsList;
// address => validatorId
mapping (address => uint) private _validatorAddressToId;
// address => validatorId
mapping (address => uint) private _nodeAddressToValidatorId;
// validatorId => nodeAddress[]
mapping (uint => address[]) private _nodeAddresses;
uint public numberOfValidators;
bool public useWhitelist;
bytes32 public constant VALIDATOR_MANAGER_ROLE = keccak256("VALIDATOR_MANAGER_ROLE");
modifier onlyValidatorManager() {
require(hasRole(VALIDATOR_MANAGER_ROLE, msg.sender), "VALIDATOR_MANAGER_ROLE is required");
_;
}
modifier checkValidatorExists(uint validatorId) {
require(validatorExists(validatorId), "Validator with such ID does not exist");
_;
}
/**
* @dev Creates a new validator ID that includes a validator name, description,
* commission or fee rate, and a minimum delegation amount accepted by the validator.
*
* Emits a {ValidatorRegistered} event.
*
* Requirements:
*
* - Sender must not already have registered a validator ID.
* - Fee rate must be between 0 - 1000‰. Note: in per mille.
*/
function registerValidator(
string calldata name,
string calldata description,
uint feeRate,
uint minimumDelegationAmount
)
external
returns (uint validatorId)
{
require(!validatorAddressExists(msg.sender), "Validator with such address already exists");
require(feeRate <= 1000, "Fee rate of validator should be lower than 100%");
validatorId = ++numberOfValidators;
validators[validatorId] = Validator(
name,
msg.sender,
address(0),
description,
feeRate,
now,
minimumDelegationAmount,
true
);
_setValidatorAddress(validatorId, msg.sender);
emit ValidatorRegistered(validatorId);
}
/**
* @dev Allows Admin to enable a validator by adding their ID to the
* trusted list.
*
* Emits a {ValidatorWasEnabled} event.
*
* Requirements:
*
* - Validator must not already be enabled.
*/
function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyValidatorManager {
require(!_trustedValidators[validatorId], "Validator is already enabled");
_trustedValidators[validatorId] = true;
trustedValidatorsList.push(validatorId);
emit ValidatorWasEnabled(validatorId);
}
/**
* @dev Allows Admin to disable a validator by removing their ID from
* the trusted list.
*
* Emits a {ValidatorWasDisabled} event.
*
* Requirements:
*
* - Validator must not already be disabled.
*/
function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyValidatorManager {
require(_trustedValidators[validatorId], "Validator is already disabled");
_trustedValidators[validatorId] = false;
uint position = _find(trustedValidatorsList, validatorId);
if (position < trustedValidatorsList.length) {
trustedValidatorsList[position] =
trustedValidatorsList[trustedValidatorsList.length.sub(1)];
}
trustedValidatorsList.pop();
emit ValidatorWasDisabled(validatorId);
}
/**
* @dev Owner can disable the trusted validator list. Once turned off, the
* trusted list cannot be re-enabled.
*/
function disableWhitelist() external onlyValidatorManager {
useWhitelist = false;
}
/**
* @dev Allows `msg.sender` to request a new address.
*
* Requirements:
*
* - `msg.sender` must already be a validator.
* - New address must not be null.
* - New address must not be already registered as a validator.
*/
function requestForNewAddress(address newValidatorAddress) external {
require(newValidatorAddress != address(0), "New address cannot be null");
require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered");
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].requestedAddress = newValidatorAddress;
}
/**
* @dev Allows msg.sender to confirm an address change.
*
* Emits a {ValidatorAddressChanged} event.
*
* Requirements:
*
* - Must be owner of new address.
*/
function confirmNewAddress(uint validatorId)
external
checkValidatorExists(validatorId)
{
require(
getValidator(validatorId).requestedAddress == msg.sender,
"The validator address cannot be changed because it is not the actual owner"
);
delete validators[validatorId].requestedAddress;
_setValidatorAddress(validatorId, msg.sender);
emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress);
}
/**
* @dev Links a node address to validator ID. Validator must present
* the node signature of the validator ID.
*
* Requirements:
*
* - Signature must be valid.
* - Address must not be assigned to a validator.
*/
function linkNodeAddress(address nodeAddress, bytes calldata sig) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(
keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress,
"Signature is not pass"
);
require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator");
_addNodeAddress(validatorId, nodeAddress);
emit NodeAddressWasAdded(validatorId, nodeAddress);
}
/**
* @dev Unlinks a node address from a validator.
*
* Emits a {NodeAddressWasRemoved} event.
*/
function unlinkNodeAddress(address nodeAddress) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
this.removeNodeAddress(validatorId, nodeAddress);
emit NodeAddressWasRemoved(validatorId, nodeAddress);
}
/**
* @dev Allows a validator to set a minimum delegation amount.
*/
function setValidatorMDA(uint minimumDelegationAmount) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].minimumDelegationAmount = minimumDelegationAmount;
}
/**
* @dev Allows a validator to set a new validator name.
*/
function setValidatorName(string calldata newName) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].name = newName;
}
/**
* @dev Allows a validator to set a new validator description.
*/
function setValidatorDescription(string calldata newDescription) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].description = newDescription;
}
/**
* @dev Allows a validator to start accepting new delegation requests.
*
* Requirements:
*
* - Must not have already enabled accepting new requests.
*/
function startAcceptingNewRequests() external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled");
validators[validatorId].acceptNewRequests = true;
}
/**
* @dev Allows a validator to stop accepting new delegation requests.
*
* Requirements:
*
* - Must not have already stopped accepting new requests.
*/
function stopAcceptingNewRequests() external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled");
validators[validatorId].acceptNewRequests = false;
}
function removeNodeAddress(uint validatorId, address nodeAddress) external allowTwo("ValidatorService", "Nodes") {
require(_nodeAddressToValidatorId[nodeAddress] == validatorId,
"Validator does not have permissions to unlink node");
delete _nodeAddressToValidatorId[nodeAddress];
for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) {
if (_nodeAddresses[validatorId][i] == nodeAddress) {
if (i + 1 < _nodeAddresses[validatorId].length) {
_nodeAddresses[validatorId][i] =
_nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)];
}
delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)];
_nodeAddresses[validatorId].pop();
break;
}
}
}
/**
* @dev Returns the amount of validator bond (self-delegation).
*/
function getAndUpdateBondAmount(uint validatorId)
external
returns (uint)
{
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
return delegationController.getAndUpdateDelegatedByHolderToValidatorNow(
getValidator(validatorId).validatorAddress,
validatorId
);
}
/**
* @dev Returns node addresses linked to the msg.sender.
*/
function getMyNodesAddresses() external view returns (address[] memory) {
return getNodeAddresses(getValidatorId(msg.sender));
}
/**
* @dev Returns the list of trusted validators.
*/
function getTrustedValidators() external view returns (uint[] memory) {
return trustedValidatorsList;
}
/**
* @dev Checks whether the validator ID is linked to the validator address.
*/
function checkValidatorAddressToId(address validatorAddress, uint validatorId)
external
view
returns (bool)
{
return getValidatorId(validatorAddress) == validatorId ? true : false;
}
/**
* @dev Returns the validator ID linked to a node address.
*
* Requirements:
*
* - Node address must be linked to a validator.
*/
function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) {
validatorId = _nodeAddressToValidatorId[nodeAddress];
require(validatorId != 0, "Node address is not assigned to a validator");
}
function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view {
require(isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request");
require(isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests");
require(
validators[validatorId].minimumDelegationAmount <= amount,
"Amount does not meet the validator's minimum delegation amount"
);
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
useWhitelist = true;
}
/**
* @dev Returns a validator's node addresses.
*/
function getNodeAddresses(uint validatorId) public view returns (address[] memory) {
return _nodeAddresses[validatorId];
}
/**
* @dev Checks whether validator ID exists.
*/
function validatorExists(uint validatorId) public view returns (bool) {
return validatorId <= numberOfValidators && validatorId != 0;
}
/**
* @dev Checks whether validator address exists.
*/
function validatorAddressExists(address validatorAddress) public view returns (bool) {
return _validatorAddressToId[validatorAddress] != 0;
}
/**
* @dev Checks whether validator address exists.
*/
function checkIfValidatorAddressExists(address validatorAddress) public view {
require(validatorAddressExists(validatorAddress), "Validator address does not exist");
}
/**
* @dev Returns the Validator struct.
*/
function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) {
return validators[validatorId];
}
/**
* @dev Returns the validator ID for the given validator address.
*/
function getValidatorId(address validatorAddress) public view returns (uint) {
checkIfValidatorAddressExists(validatorAddress);
return _validatorAddressToId[validatorAddress];
}
/**
* @dev Checks whether the validator is currently accepting new delegation requests.
*/
function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) {
return validators[validatorId].acceptNewRequests;
}
function isAuthorizedValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) {
return _trustedValidators[validatorId] || !useWhitelist;
}
// private
/**
* @dev Links a validator address to a validator ID.
*
* Requirements:
*
* - Address is not already in use by another validator.
*/
function _setValidatorAddress(uint validatorId, address validatorAddress) private {
if (_validatorAddressToId[validatorAddress] == validatorId) {
return;
}
require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator");
address oldAddress = validators[validatorId].validatorAddress;
delete _validatorAddressToId[oldAddress];
_nodeAddressToValidatorId[validatorAddress] = validatorId;
validators[validatorId].validatorAddress = validatorAddress;
_validatorAddressToId[validatorAddress] = validatorId;
}
/**
* @dev Links a node address to a validator ID.
*
* Requirements:
*
* - Node address must not be already linked to a validator.
*/
function _addNodeAddress(uint validatorId, address nodeAddress) private {
if (_nodeAddressToValidatorId[nodeAddress] == validatorId) {
return;
}
require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address");
_nodeAddressToValidatorId[nodeAddress] = validatorId;
_nodeAddresses[validatorId].push(nodeAddress);
}
function _find(uint[] memory array, uint index) private pure returns (uint) {
uint i;
for (i = 0; i < array.length; i++) {
if (array[i] == index) {
return i;
}
}
return array.length;
}
}
pragma solidity ^0.6.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Permissions.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
import "./ContractManager.sol";
/**
* @title Permissions
* @dev Contract is connected module for Upgradeable approach, knows ContractManager
*/
contract Permissions is AccessControlUpgradeSafe {
using SafeMath for uint;
using Address for address;
ContractManager public contractManager;
/**
* @dev Modifier to make a function callable only when caller is the Owner.
*
* Requirements:
*
* - The caller must be the owner.
*/
modifier onlyOwner() {
require(_isOwner(), "Caller is not the owner");
_;
}
/**
* @dev Modifier to make a function callable only when caller is an Admin.
*
* Requirements:
*
* - The caller must be an admin.
*/
modifier onlyAdmin() {
require(_isAdmin(msg.sender), "Caller is not an admin");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName` contract.
*
* Requirements:
*
* - The caller must be the owner or `contractName`.
*/
modifier allow(string memory contractName) {
require(
contractManager.getContract(contractName) == msg.sender || _isOwner(),
"Message sender is invalid");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName1` or `contractName2` contract.
*
* Requirements:
*
* - The caller must be the owner, `contractName1`, or `contractName2`.
*/
modifier allowTwo(string memory contractName1, string memory contractName2) {
require(
contractManager.getContract(contractName1) == msg.sender ||
contractManager.getContract(contractName2) == msg.sender ||
_isOwner(),
"Message sender is invalid");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName1`, `contractName2`, or `contractName3` contract.
*
* Requirements:
*
* - The caller must be the owner, `contractName1`, `contractName2`, or
* `contractName3`.
*/
modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) {
require(
contractManager.getContract(contractName1) == msg.sender ||
contractManager.getContract(contractName2) == msg.sender ||
contractManager.getContract(contractName3) == msg.sender ||
_isOwner(),
"Message sender is invalid");
_;
}
function initialize(address contractManagerAddress) public virtual initializer {
AccessControlUpgradeSafe.__AccessControl_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setContractManager(contractManagerAddress);
}
function _isOwner() internal view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
function _isAdmin(address account) internal view returns (bool) {
address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager")));
if (skaleManagerAddress != address(0)) {
AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress);
return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner();
} else {
return _isOwner();
}
}
function _setContractManager(address contractManagerAddress) private {
require(contractManagerAddress != address(0), "ContractManager address is not set");
require(contractManagerAddress.isContract(), "Address is not contract");
contractManager = ContractManager(contractManagerAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ConstantsHolder.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "./Permissions.sol";
/**
* @title ConstantsHolder
* @dev Contract contains constants and common variables for the SKALE Network.
*/
contract ConstantsHolder is Permissions {
// initial price for creating Node (100 SKL)
uint public constant NODE_DEPOSIT = 100 * 1e18;
uint8 public constant TOTAL_SPACE_ON_NODE = 128;
// part of Node for Small Skale-chain (1/128 of Node)
uint8 public constant SMALL_DIVISOR = 128;
// part of Node for Medium Skale-chain (1/32 of Node)
uint8 public constant MEDIUM_DIVISOR = 32;
// part of Node for Large Skale-chain (full Node)
uint8 public constant LARGE_DIVISOR = 1;
// part of Node for Medium Test Skale-chain (1/4 of Node)
uint8 public constant MEDIUM_TEST_DIVISOR = 4;
// typically number of Nodes for Skale-chain (16 Nodes)
uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16;
// number of Nodes for Test Skale-chain (2 Nodes)
uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2;
// number of Nodes for Test Skale-chain (4 Nodes)
uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4;
// number of seconds in one year
uint32 public constant SECONDS_TO_YEAR = 31622400;
// initial number of monitors
uint public constant NUMBER_OF_MONITORS = 24;
uint public constant OPTIMAL_LOAD_PERCENTAGE = 80;
uint public constant ADJUSTMENT_SPEED = 1000;
uint public constant COOLDOWN_TIME = 60;
uint public constant MIN_PRICE = 10**6;
uint public constant MSR_REDUCING_COEFFICIENT = 2;
uint public constant DOWNTIME_THRESHOLD_PART = 30;
uint public constant BOUNTY_LOCKUP_MONTHS = 2;
uint public constant ALRIGHT_DELTA = 62893;
uint public constant BROADCAST_DELTA = 131000;
uint public constant COMPLAINT_BAD_DATA_DELTA = 49580;
uint public constant PRE_RESPONSE_DELTA = 74500;
uint public constant COMPLAINT_DELTA = 76221;
uint public constant RESPONSE_DELTA = 183000;
// MSR - Minimum staking requirement
uint public msr;
// Reward period - 30 days (each 30 days Node would be granted for bounty)
uint32 public rewardPeriod;
// Allowable latency - 150000 ms by default
uint32 public allowableLatency;
/**
* Delta period - 1 hour (1 hour before Reward period became Monitors need
* to send Verdicts and 1 hour after Reward period became Node need to come
* and get Bounty)
*/
uint32 public deltaPeriod;
/**
* Check time - 2 minutes (every 2 minutes monitors should check metrics
* from checked nodes)
*/
uint public checkTime;
//Need to add minimal allowed parameters for verdicts
uint public launchTimestamp;
uint public rotationDelay;
uint public proofOfUseLockUpPeriodDays;
uint public proofOfUseDelegationPercentage;
uint public limitValidatorsPerDelegator;
uint256 public firstDelegationsMonth; // deprecated
// date when schains will be allowed for creation
uint public schainCreationTimeStamp;
uint public minimalSchainLifetime;
uint public complaintTimelimit;
bytes32 public constant CONSTANTS_HOLDER_MANAGER_ROLE = keccak256("CONSTANTS_HOLDER_MANAGER_ROLE");
modifier onlyConstantsHolderManager() {
require(hasRole(CONSTANTS_HOLDER_MANAGER_ROLE, msg.sender), "CONSTANTS_HOLDER_MANAGER_ROLE is required");
_;
}
/**
* @dev Allows the Owner to set new reward and delta periods
* This function is only for tests.
*/
function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyConstantsHolderManager {
require(
newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime,
"Incorrect Periods"
);
rewardPeriod = newRewardPeriod;
deltaPeriod = newDeltaPeriod;
}
/**
* @dev Allows the Owner to set the new check time.
* This function is only for tests.
*/
function setCheckTime(uint newCheckTime) external onlyConstantsHolderManager {
require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time");
checkTime = newCheckTime;
}
/**
* @dev Allows the Owner to set the allowable latency in milliseconds.
* This function is only for testing purposes.
*/
function setLatency(uint32 newAllowableLatency) external onlyConstantsHolderManager {
allowableLatency = newAllowableLatency;
}
/**
* @dev Allows the Owner to set the minimum stake requirement.
*/
function setMSR(uint newMSR) external onlyConstantsHolderManager {
msr = newMSR;
}
/**
* @dev Allows the Owner to set the launch timestamp.
*/
function setLaunchTimestamp(uint timestamp) external onlyConstantsHolderManager {
require(now < launchTimestamp, "Cannot set network launch timestamp because network is already launched");
launchTimestamp = timestamp;
}
/**
* @dev Allows the Owner to set the node rotation delay.
*/
function setRotationDelay(uint newDelay) external onlyConstantsHolderManager {
rotationDelay = newDelay;
}
/**
* @dev Allows the Owner to set the proof-of-use lockup period.
*/
function setProofOfUseLockUpPeriod(uint periodDays) external onlyConstantsHolderManager {
proofOfUseLockUpPeriodDays = periodDays;
}
/**
* @dev Allows the Owner to set the proof-of-use delegation percentage
* requirement.
*/
function setProofOfUseDelegationPercentage(uint percentage) external onlyConstantsHolderManager {
require(percentage <= 100, "Percentage value is incorrect");
proofOfUseDelegationPercentage = percentage;
}
/**
* @dev Allows the Owner to set the maximum number of validators that a
* single delegator can delegate to.
*/
function setLimitValidatorsPerDelegator(uint newLimit) external onlyConstantsHolderManager {
limitValidatorsPerDelegator = newLimit;
}
function setSchainCreationTimeStamp(uint timestamp) external onlyConstantsHolderManager {
schainCreationTimeStamp = timestamp;
}
function setMinimalSchainLifetime(uint lifetime) external onlyConstantsHolderManager {
minimalSchainLifetime = lifetime;
}
function setComplaintTimelimit(uint timelimit) external onlyConstantsHolderManager {
complaintTimelimit = timelimit;
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
msr = 0;
rewardPeriod = 2592000;
allowableLatency = 150000;
deltaPeriod = 3600;
checkTime = 300;
launchTimestamp = uint(-1);
rotationDelay = 12 hours;
proofOfUseLockUpPeriodDays = 90;
proofOfUseDelegationPercentage = 50;
limitValidatorsPerDelegator = 20;
firstDelegationsMonth = 0;
complaintTimelimit = 1800;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
DelegationController.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol";
import "../BountyV2.sol";
import "../Nodes.sol";
import "../Permissions.sol";
import "../utils/FractionUtils.sol";
import "../utils/MathUtils.sol";
import "./DelegationPeriodManager.sol";
import "./PartialDifferences.sol";
import "./Punisher.sol";
import "./TokenState.sol";
import "./ValidatorService.sol";
/**
* @title Delegation Controller
* @dev This contract performs all delegation functions including delegation
* requests, and undelegation, etc.
*
* Delegators and validators may both perform delegations. Validators who perform
* delegations to themselves are effectively self-delegating or self-bonding.
*
* IMPORTANT: Undelegation may be requested at any time, but undelegation is only
* performed at the completion of the current delegation period.
*
* Delegated tokens may be in one of several states:
*
* - PROPOSED: token holder proposes tokens to delegate to a validator.
* - ACCEPTED: token delegations are accepted by a validator and are locked-by-delegation.
* - CANCELED: token holder cancels delegation proposal. Only allowed before the proposal is accepted by the validator.
* - REJECTED: token proposal expires at the UTC start of the next month.
* - DELEGATED: accepted delegations are delegated at the UTC start of the month.
* - UNDELEGATION_REQUESTED: token holder requests delegations to undelegate from the validator.
* - COMPLETED: undelegation request is completed at the end of the delegation period.
*/
contract DelegationController is Permissions, ILocker {
using MathUtils for uint;
using PartialDifferences for PartialDifferences.Sequence;
using PartialDifferences for PartialDifferences.Value;
using FractionUtils for FractionUtils.Fraction;
uint public constant UNDELEGATION_PROHIBITION_WINDOW_SECONDS = 3 * 24 * 60 * 60;
enum State {
PROPOSED,
ACCEPTED,
CANCELED,
REJECTED,
DELEGATED,
UNDELEGATION_REQUESTED,
COMPLETED
}
struct Delegation {
address holder; // address of token owner
uint validatorId;
uint amount;
uint delegationPeriod;
uint created; // time of delegation creation
uint started; // month when a delegation becomes active
uint finished; // first month after a delegation ends
string info;
}
struct SlashingLogEvent {
FractionUtils.Fraction reducingCoefficient;
uint nextMonth;
}
struct SlashingLog {
// month => slashing event
mapping (uint => SlashingLogEvent) slashes;
uint firstMonth;
uint lastMonth;
}
struct DelegationExtras {
uint lastSlashingMonthBeforeDelegation;
}
struct SlashingEvent {
FractionUtils.Fraction reducingCoefficient;
uint validatorId;
uint month;
}
struct SlashingSignal {
address holder;
uint penalty;
}
struct LockedInPending {
uint amount;
uint month;
}
struct FirstDelegationMonth {
// month
uint value;
//validatorId => month
mapping (uint => uint) byValidator;
}
struct ValidatorsStatistics {
// number of validators
uint number;
//validatorId => bool - is Delegated or not
mapping (uint => uint) delegated;
}
/**
* @dev Emitted when a delegation is proposed to a validator.
*/
event DelegationProposed(
uint delegationId
);
/**
* @dev Emitted when a delegation is accepted by a validator.
*/
event DelegationAccepted(
uint delegationId
);
/**
* @dev Emitted when a delegation is cancelled by the delegator.
*/
event DelegationRequestCanceledByUser(
uint delegationId
);
/**
* @dev Emitted when a delegation is requested to undelegate.
*/
event UndelegationRequested(
uint delegationId
);
/// @dev delegations will never be deleted to index in this array may be used like delegation id
Delegation[] public delegations;
// validatorId => delegationId[]
mapping (uint => uint[]) public delegationsByValidator;
// holder => delegationId[]
mapping (address => uint[]) public delegationsByHolder;
// delegationId => extras
mapping(uint => DelegationExtras) private _delegationExtras;
// validatorId => sequence
mapping (uint => PartialDifferences.Value) private _delegatedToValidator;
// validatorId => sequence
mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator;
// validatorId => slashing log
mapping (uint => SlashingLog) private _slashesOfValidator;
// holder => sequence
mapping (address => PartialDifferences.Value) private _delegatedByHolder;
// holder => validatorId => sequence
mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator;
// holder => validatorId => sequence
mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator;
SlashingEvent[] private _slashes;
// holder => index in _slashes;
mapping (address => uint) private _firstUnprocessedSlashByHolder;
// holder => validatorId => month
mapping (address => FirstDelegationMonth) private _firstDelegationMonth;
// holder => locked in pending
mapping (address => LockedInPending) private _lockedInPendingDelegations;
mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator;
/**
* @dev Modifier to make a function callable only if delegation exists.
*/
modifier checkDelegationExists(uint delegationId) {
require(delegationId < delegations.length, "Delegation does not exist");
_;
}
/**
* @dev Update and return a validator's delegations.
*/
function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) {
return _getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth());
}
/**
* @dev Update and return the amount delegated.
*/
function getAndUpdateDelegatedAmount(address holder) external returns (uint) {
return _getAndUpdateDelegatedByHolder(holder);
}
/**
* @dev Update and return the effective amount delegated (minus slash) for
* the given month.
*/
function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external
allow("Distributor") returns (uint effectiveDelegated)
{
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder);
effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId]
.getAndUpdateValueInSequence(month);
_sendSlashingSignals(slashingSignals);
}
/**
* @dev Allows a token holder to create a delegation proposal of an `amount`
* and `delegationPeriod` to a `validatorId`. Delegation must be accepted
* by the validator before the UTC start of the month, otherwise the
* delegation will be rejected.
*
* The token holder may add additional information in each proposal.
*
* Emits a {DelegationProposed} event.
*
* Requirements:
*
* - Holder must have sufficient delegatable tokens.
* - Delegation must be above the validator's minimum delegation amount.
* - Delegation period must be allowed.
* - Validator must be authorized if trusted list is enabled.
* - Validator must be accepting new delegation requests.
*/
function delegate(
uint validatorId,
uint amount,
uint delegationPeriod,
string calldata info
)
external
{
require(
_getDelegationPeriodManager().isDelegationPeriodAllowed(delegationPeriod),
"This delegation period is not allowed");
_getValidatorService().checkValidatorCanReceiveDelegation(validatorId, amount);
_checkIfDelegationIsAllowed(msg.sender, validatorId);
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender);
uint delegationId = _addDelegation(
msg.sender,
validatorId,
amount,
delegationPeriod,
info);
// check that there is enough money
uint holderBalance = IERC777(contractManager.getSkaleToken()).balanceOf(msg.sender);
uint forbiddenForDelegation = TokenState(contractManager.getTokenState())
.getAndUpdateForbiddenForDelegationAmount(msg.sender);
require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate");
emit DelegationProposed(delegationId);
_sendSlashingSignals(slashingSignals);
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev Allows token holder to cancel a delegation proposal.
*
* Emits a {DelegationRequestCanceledByUser} event.
*
* Requirements:
*
* - `msg.sender` must be the token holder of the delegation proposal.
* - Delegation state must be PROPOSED.
*/
function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request");
require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations");
delegations[delegationId].finished = _getCurrentMonth();
_subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount);
emit DelegationRequestCanceledByUser(delegationId);
}
/**
* @dev Allows a validator to accept a proposed delegation.
* Successful acceptance of delegations transition the tokens from a
* PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the
* delegation period.
*
* Emits a {DelegationAccepted} event.
*
* Requirements:
*
* - Validator must be recipient of proposal.
* - Delegation state must be PROPOSED.
*/
function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(
_getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId),
"No permissions to accept request");
_accept(delegationId);
}
/**
* @dev Allows delegator to undelegate a specific delegation.
*
* Emits UndelegationRequested event.
*
* Requirements:
*
* - `msg.sender` must be the delegator.
* - Delegation state must be DELEGATED.
*/
function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation");
ValidatorService validatorService = _getValidatorService();
require(
delegations[delegationId].holder == msg.sender ||
(validatorService.validatorAddressExists(msg.sender) &&
delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)),
"Permission denied to request undelegation");
_removeValidatorFromValidatorsPerDelegators(
delegations[delegationId].holder,
delegations[delegationId].validatorId);
processAllSlashes(msg.sender);
delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId);
require(
now.add(UNDELEGATION_PROHIBITION_WINDOW_SECONDS)
< _getTimeHelpers().monthToTimestamp(delegations[delegationId].finished),
"Undelegation requests must be sent 3 days before the end of delegation period"
);
_subtractFromAllStatistics(delegationId);
emit UndelegationRequested(delegationId);
}
/**
* @dev Allows Punisher contract to slash an `amount` of stake from
* a validator. This slashes an amount of delegations of the validator,
* which reduces the amount that the validator has staked. This consequence
* may force the SKALE Manager to reduce the number of nodes a validator is
* operating so the validator can meet the Minimum Staking Requirement.
*
* Emits a {SlashingEvent}.
*
* See {Punisher}.
*/
function confiscate(uint validatorId, uint amount) external allow("Punisher") {
uint currentMonth = _getCurrentMonth();
FractionUtils.Fraction memory coefficient =
_delegatedToValidator[validatorId].reduceValue(amount, currentMonth);
uint initialEffectiveDelegated =
_effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth);
uint[] memory initialSubtractions = new uint[](0);
if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) {
initialSubtractions = new uint[](
_effectiveDelegatedToValidator[validatorId].lastChangedMonth.sub(currentMonth)
);
for (uint i = 0; i < initialSubtractions.length; ++i) {
initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId]
.subtractDiff[currentMonth.add(i).add(1)];
}
}
_effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth);
_putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth);
_slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth}));
BountyV2 bounty = _getBounty();
bounty.handleDelegationRemoving(
initialEffectiveDelegated.sub(
_effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth)
),
currentMonth
);
for (uint i = 0; i < initialSubtractions.length; ++i) {
bounty.handleDelegationAdd(
initialSubtractions[i].sub(
_effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth.add(i).add(1)]
),
currentMonth.add(i).add(1)
);
}
}
/**
* @dev Allows Distributor contract to return and update the effective
* amount delegated (minus slash) to a validator for a given month.
*/
function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month)
external allowTwo("Bounty", "Distributor") returns (uint)
{
return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month);
}
/**
* @dev Return and update the amount delegated to a validator for the
* current month.
*/
function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) {
return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth());
}
function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory) {
return _effectiveDelegatedToValidator[validatorId].getValuesInSequence();
}
function getEffectiveDelegatedToValidator(uint validatorId, uint month) external view returns (uint) {
return _effectiveDelegatedToValidator[validatorId].getValueInSequence(month);
}
function getDelegatedToValidator(uint validatorId, uint month) external view returns (uint) {
return _delegatedToValidator[validatorId].getValue(month);
}
/**
* @dev Return Delegation struct.
*/
function getDelegation(uint delegationId)
external view checkDelegationExists(delegationId) returns (Delegation memory)
{
return delegations[delegationId];
}
/**
* @dev Returns the first delegation month.
*/
function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) {
return _firstDelegationMonth[holder].byValidator[validatorId];
}
/**
* @dev Returns a validator's total number of delegations.
*/
function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) {
return delegationsByValidator[validatorId].length;
}
/**
* @dev Returns a holder's total number of delegations.
*/
function getDelegationsByHolderLength(address holder) external view returns (uint) {
return delegationsByHolder[holder].length;
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
}
/**
* @dev Process slashes up to the given limit.
*/
function processSlashes(address holder, uint limit) public {
_sendSlashingSignals(_processSlashesWithoutSignals(holder, limit));
}
/**
* @dev Process all slashes.
*/
function processAllSlashes(address holder) public {
processSlashes(holder, 0);
}
/**
* @dev Returns the token state of a given delegation.
*/
function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) {
if (delegations[delegationId].started == 0) {
if (delegations[delegationId].finished == 0) {
if (_getCurrentMonth() == _getTimeHelpers().timestampToMonth(delegations[delegationId].created)) {
return State.PROPOSED;
} else {
return State.REJECTED;
}
} else {
return State.CANCELED;
}
} else {
if (_getCurrentMonth() < delegations[delegationId].started) {
return State.ACCEPTED;
} else {
if (delegations[delegationId].finished == 0) {
return State.DELEGATED;
} else {
if (_getCurrentMonth() < delegations[delegationId].finished) {
return State.UNDELEGATION_REQUESTED;
} else {
return State.COMPLETED;
}
}
}
}
}
/**
* @dev Returns the amount of tokens in PENDING delegation state.
*/
function getLockedInPendingDelegations(address holder) public view returns (uint) {
uint currentMonth = _getCurrentMonth();
if (_lockedInPendingDelegations[holder].month < currentMonth) {
return 0;
} else {
return _lockedInPendingDelegations[holder].amount;
}
}
/**
* @dev Checks whether there are any unprocessed slashes.
*/
function hasUnprocessedSlashes(address holder) public view returns (bool) {
return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length;
}
// private
/**
* @dev Allows Nodes contract to get and update the amount delegated
* to validator for a given month.
*/
function _getAndUpdateDelegatedToValidator(uint validatorId, uint month)
private returns (uint)
{
return _delegatedToValidator[validatorId].getAndUpdateValue(month);
}
/**
* @dev Adds a new delegation proposal.
*/
function _addDelegation(
address holder,
uint validatorId,
uint amount,
uint delegationPeriod,
string memory info
)
private
returns (uint delegationId)
{
delegationId = delegations.length;
delegations.push(Delegation(
holder,
validatorId,
amount,
delegationPeriod,
now,
0,
0,
info
));
delegationsByValidator[validatorId].push(delegationId);
delegationsByHolder[holder].push(delegationId);
_addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount);
}
/**
* @dev Returns the month when a delegation ends.
*/
function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) {
uint currentMonth = _getCurrentMonth();
uint started = delegations[delegationId].started;
if (currentMonth < started) {
return started.add(delegations[delegationId].delegationPeriod);
} else {
uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod);
return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod));
}
}
function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private {
_delegatedToValidator[validatorId].addToValue(amount, month);
}
function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private {
_effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month);
}
function _addToDelegatedByHolder(address holder, uint amount, uint month) private {
_delegatedByHolder[holder].addToValue(amount, month);
}
function _addToDelegatedByHolderToValidator(
address holder, uint validatorId, uint amount, uint month) private
{
_delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month);
}
function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private {
if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) {
_numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1);
}
_numberOfValidatorsPerDelegator[holder].
delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1);
}
function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private {
_delegatedByHolder[holder].subtractFromValue(amount, month);
}
function _removeFromDelegatedByHolderToValidator(
address holder, uint validatorId, uint amount, uint month) private
{
_delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month);
}
function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private {
if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) {
_numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1);
}
_numberOfValidatorsPerDelegator[holder].
delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1);
}
function _addToEffectiveDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint effectiveAmount,
uint month)
private
{
_effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month);
}
function _removeFromEffectiveDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint effectiveAmount,
uint month)
private
{
_effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month);
}
function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) {
uint currentMonth = _getCurrentMonth();
processAllSlashes(holder);
return _delegatedByHolder[holder].getAndUpdateValue(currentMonth);
}
function _getAndUpdateDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint month)
private returns (uint)
{
return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month);
}
function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) {
uint currentMonth = _getCurrentMonth();
if (_lockedInPendingDelegations[holder].month < currentMonth) {
_lockedInPendingDelegations[holder].amount = amount;
_lockedInPendingDelegations[holder].month = currentMonth;
} else {
assert(_lockedInPendingDelegations[holder].month == currentMonth);
_lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount);
}
}
function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) {
uint currentMonth = _getCurrentMonth();
assert(_lockedInPendingDelegations[holder].month == currentMonth);
_lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount);
}
function _getCurrentMonth() private view returns (uint) {
return _getTimeHelpers().getCurrentMonth();
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function _getAndUpdateLockedAmount(address wallet) private returns (uint) {
return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet));
}
function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private {
if (_firstDelegationMonth[holder].value == 0) {
_firstDelegationMonth[holder].value = month;
_firstUnprocessedSlashByHolder[holder] = _slashes.length;
}
if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) {
_firstDelegationMonth[holder].byValidator[validatorId] = month;
}
}
/**
* @dev Checks whether the holder has performed a delegation.
*/
function _everDelegated(address holder) private view returns (bool) {
return _firstDelegationMonth[holder].value > 0;
}
function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private {
_delegatedToValidator[validatorId].subtractFromValue(amount, month);
}
function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private {
_effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month);
}
/**
* @dev Returns the delegated amount after a slashing event.
*/
function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) {
uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation;
uint validatorId = delegations[delegationId].validatorId;
uint amount = delegations[delegationId].amount;
if (startMonth == 0) {
startMonth = _slashesOfValidator[validatorId].firstMonth;
if (startMonth == 0) {
return amount;
}
}
for (uint i = startMonth;
i > 0 && i < delegations[delegationId].finished;
i = _slashesOfValidator[validatorId].slashes[i].nextMonth) {
if (i >= delegations[delegationId].started) {
amount = amount
.mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator)
.div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator);
}
}
return amount;
}
function _putToSlashingLog(
SlashingLog storage log,
FractionUtils.Fraction memory coefficient,
uint month)
private
{
if (log.firstMonth == 0) {
log.firstMonth = month;
log.lastMonth = month;
log.slashes[month].reducingCoefficient = coefficient;
log.slashes[month].nextMonth = 0;
} else {
require(log.lastMonth <= month, "Cannot put slashing event in the past");
if (log.lastMonth == month) {
log.slashes[month].reducingCoefficient =
log.slashes[month].reducingCoefficient.multiplyFraction(coefficient);
} else {
log.slashes[month].reducingCoefficient = coefficient;
log.slashes[month].nextMonth = 0;
log.slashes[log.lastMonth].nextMonth = month;
log.lastMonth = month;
}
}
}
function _processSlashesWithoutSignals(address holder, uint limit)
private returns (SlashingSignal[] memory slashingSignals)
{
if (hasUnprocessedSlashes(holder)) {
uint index = _firstUnprocessedSlashByHolder[holder];
uint end = _slashes.length;
if (limit > 0 && index.add(limit) < end) {
end = index.add(limit);
}
slashingSignals = new SlashingSignal[](end.sub(index));
uint begin = index;
for (; index < end; ++index) {
uint validatorId = _slashes[index].validatorId;
uint month = _slashes[index].month;
uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month);
if (oldValue.muchGreater(0)) {
_delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum(
_delegatedByHolder[holder],
_slashes[index].reducingCoefficient,
month);
_effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence(
_slashes[index].reducingCoefficient,
month);
slashingSignals[index.sub(begin)].holder = holder;
slashingSignals[index.sub(begin)].penalty
= oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month));
}
}
_firstUnprocessedSlashByHolder[holder] = end;
}
}
function _processAllSlashesWithoutSignals(address holder)
private returns (SlashingSignal[] memory slashingSignals)
{
return _processSlashesWithoutSignals(holder, 0);
}
function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private {
Punisher punisher = Punisher(contractManager.getPunisher());
address previousHolder = address(0);
uint accumulatedPenalty = 0;
for (uint i = 0; i < slashingSignals.length; ++i) {
if (slashingSignals[i].holder != previousHolder) {
if (accumulatedPenalty > 0) {
punisher.handleSlash(previousHolder, accumulatedPenalty);
}
previousHolder = slashingSignals[i].holder;
accumulatedPenalty = slashingSignals[i].penalty;
} else {
accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty);
}
}
if (accumulatedPenalty > 0) {
punisher.handleSlash(previousHolder, accumulatedPenalty);
}
}
function _addToAllStatistics(uint delegationId) private {
uint currentMonth = _getCurrentMonth();
delegations[delegationId].started = currentMonth.add(1);
if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) {
_delegationExtras[delegationId].lastSlashingMonthBeforeDelegation =
_slashesOfValidator[delegations[delegationId].validatorId].lastMonth;
}
_addToDelegatedToValidator(
delegations[delegationId].validatorId,
delegations[delegationId].amount,
currentMonth.add(1));
_addToDelegatedByHolder(
delegations[delegationId].holder,
delegations[delegationId].amount,
currentMonth.add(1));
_addToDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
delegations[delegationId].amount,
currentMonth.add(1));
_updateFirstDelegationMonth(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
currentMonth.add(1));
uint effectiveAmount = delegations[delegationId].amount.mul(
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod));
_addToEffectiveDelegatedToValidator(
delegations[delegationId].validatorId,
effectiveAmount,
currentMonth.add(1));
_addToEffectiveDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
effectiveAmount,
currentMonth.add(1));
_addValidatorToValidatorsPerDelegators(
delegations[delegationId].holder,
delegations[delegationId].validatorId
);
}
function _subtractFromAllStatistics(uint delegationId) private {
uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId);
_removeFromDelegatedToValidator(
delegations[delegationId].validatorId,
amountAfterSlashing,
delegations[delegationId].finished);
_removeFromDelegatedByHolder(
delegations[delegationId].holder,
amountAfterSlashing,
delegations[delegationId].finished);
_removeFromDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
amountAfterSlashing,
delegations[delegationId].finished);
uint effectiveAmount = amountAfterSlashing.mul(
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod));
_removeFromEffectiveDelegatedToValidator(
delegations[delegationId].validatorId,
effectiveAmount,
delegations[delegationId].finished);
_removeFromEffectiveDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
effectiveAmount,
delegations[delegationId].finished);
_getBounty().handleDelegationRemoving(
effectiveAmount,
delegations[delegationId].finished);
}
/**
* @dev Checks whether delegation to a validator is allowed.
*
* Requirements:
*
* - Delegator must not have reached the validator limit.
* - Delegation must be made in or after the first delegation month.
*/
function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) {
require(
_numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 ||
(
_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 &&
_numberOfValidatorsPerDelegator[holder].number < _getConstantsHolder().limitValidatorsPerDelegator()
),
"Limit of validators is reached"
);
}
function _getDelegationPeriodManager() private view returns (DelegationPeriodManager) {
return DelegationPeriodManager(contractManager.getDelegationPeriodManager());
}
function _getBounty() private view returns (BountyV2) {
return BountyV2(contractManager.getBounty());
}
function _getValidatorService() private view returns (ValidatorService) {
return ValidatorService(contractManager.getValidatorService());
}
function _getTimeHelpers() private view returns (TimeHelpers) {
return TimeHelpers(contractManager.getTimeHelpers());
}
function _getConstantsHolder() private view returns (ConstantsHolder) {
return ConstantsHolder(contractManager.getConstantsHolder());
}
function _accept(uint delegationId) private {
_checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId);
State currentState = getState(delegationId);
if (currentState != State.PROPOSED) {
if (currentState == State.ACCEPTED ||
currentState == State.DELEGATED ||
currentState == State.UNDELEGATION_REQUESTED ||
currentState == State.COMPLETED)
{
revert("The delegation has been already accepted");
} else if (currentState == State.CANCELED) {
revert("The delegation has been cancelled by token holder");
} else if (currentState == State.REJECTED) {
revert("The delegation request is outdated");
}
}
require(currentState == State.PROPOSED, "Cannot set delegation state to accepted");
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder);
_addToAllStatistics(delegationId);
uint amount = delegations[delegationId].amount;
uint effectiveAmount = amount.mul(
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)
);
_getBounty().handleDelegationAdd(
effectiveAmount,
delegations[delegationId].started
);
_sendSlashingSignals(slashingSignals);
emit DelegationAccepted(delegationId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
TimeHelpers.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "../thirdparty/BokkyPooBahsDateTimeLibrary.sol";
/**
* @title TimeHelpers
* @dev The contract performs time operations.
*
* These functions are used to calculate monthly and Proof of Use epochs.
*/
contract TimeHelpers {
using SafeMath for uint;
uint constant private _ZERO_YEAR = 2020;
function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) {
timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays);
}
function addDays(uint fromTimestamp, uint n) external pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n);
}
function addMonths(uint fromTimestamp, uint n) external pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n);
}
function addYears(uint fromTimestamp, uint n) external pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n);
}
function getCurrentMonth() external view virtual returns (uint) {
return timestampToMonth(now);
}
function timestampToDay(uint timestamp) external view returns (uint) {
uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY;
uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) /
BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY;
require(wholeDays >= zeroDay, "Timestamp is too far in the past");
return wholeDays - zeroDay;
}
function timestampToYear(uint timestamp) external view virtual returns (uint) {
uint year;
(year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp);
require(year >= _ZERO_YEAR, "Timestamp is too far in the past");
return year - _ZERO_YEAR;
}
function timestampToMonth(uint timestamp) public view virtual returns (uint) {
uint year;
uint month;
(year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp);
require(year >= _ZERO_YEAR, "Timestamp is too far in the past");
month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12));
require(month > 0, "Timestamp is too far in the past");
return month;
}
function monthToTimestamp(uint month) public view virtual returns (uint timestamp) {
uint year = _ZERO_YEAR;
uint _month = month;
year = year.add(_month.div(12));
_month = _month.mod(12);
_month = _month.add(1);
return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1);
}
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.6.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
import "../Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, _msgSender()));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*/
abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ContractManager.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol";
import "@skalenetwork/skale-manager-interfaces/IContractManager.sol";
import "./utils/StringUtils.sol";
/**
* @title ContractManager
* @dev Contract contains the actual current mapping from contract IDs
* (in the form of human-readable strings) to addresses.
*/
contract ContractManager is OwnableUpgradeSafe, IContractManager {
using StringUtils for string;
using Address for address;
string public constant BOUNTY = "Bounty";
string public constant CONSTANTS_HOLDER = "ConstantsHolder";
string public constant DELEGATION_PERIOD_MANAGER = "DelegationPeriodManager";
string public constant PUNISHER = "Punisher";
string public constant SKALE_TOKEN = "SkaleToken";
string public constant TIME_HELPERS = "TimeHelpers";
string public constant TOKEN_STATE = "TokenState";
string public constant VALIDATOR_SERVICE = "ValidatorService";
// mapping of actual smart contracts addresses
mapping (bytes32 => address) public contracts;
/**
* @dev Emitted when contract is upgraded.
*/
event ContractUpgraded(string contractsName, address contractsAddress);
function initialize() external initializer {
OwnableUpgradeSafe.__Ownable_init();
}
/**
* @dev Allows the Owner to add contract to mapping of contract addresses.
*
* Emits a {ContractUpgraded} event.
*
* Requirements:
*
* - New address is non-zero.
* - Contract is not already added.
* - Contract address contains code.
*/
function setContractsAddress(
string calldata contractsName,
address newContractsAddress
)
external
override
onlyOwner
{
// check newContractsAddress is not equal to zero
require(newContractsAddress != address(0), "New address is equal zero");
// create hash of contractsName
bytes32 contractId = keccak256(abi.encodePacked(contractsName));
// check newContractsAddress is not equal the previous contract's address
require(contracts[contractId] != newContractsAddress, "Contract is already added");
require(newContractsAddress.isContract(), "Given contract address does not contain code");
// add newContractsAddress to mapping of actual contract addresses
contracts[contractId] = newContractsAddress;
emit ContractUpgraded(contractsName, newContractsAddress);
}
/**
* @dev Returns contract address.
*
* Requirements:
*
* - Contract must exist.
*/
function getDelegationPeriodManager() external view returns (address) {
return getContract(DELEGATION_PERIOD_MANAGER);
}
function getBounty() external view returns (address) {
return getContract(BOUNTY);
}
function getValidatorService() external view returns (address) {
return getContract(VALIDATOR_SERVICE);
}
function getTimeHelpers() external view returns (address) {
return getContract(TIME_HELPERS);
}
function getConstantsHolder() external view returns (address) {
return getContract(CONSTANTS_HOLDER);
}
function getSkaleToken() external view returns (address) {
return getContract(SKALE_TOKEN);
}
function getTokenState() external view returns (address) {
return getContract(TOKEN_STATE);
}
function getPunisher() external view returns (address) {
return getContract(PUNISHER);
}
function getContract(string memory name) public view override returns (address contractAddress) {
contractAddress = contracts[keccak256(abi.encodePacked(name))];
if (contractAddress == address(0)) {
revert(name.strConcat(" contract has not been found"));
}
}
}
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
pragma solidity ^0.6.0;
import "../Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
import "../Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IContractManager.sol - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IContractManager {
function setContractsAddress(string calldata contractsName, address newContractsAddress) external;
function getContract(string calldata name) external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
StringUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
library StringUtils {
using SafeMath for uint;
function strConcat(string memory a, string memory b) internal pure returns (string memory) {
bytes memory _ba = bytes(a);
bytes memory _bb = bytes(b);
string memory ab = new string(_ba.length.add(_bb.length));
bytes memory strBytes = bytes(ab);
uint k = 0;
uint i = 0;
for (i = 0; i < _ba.length; i++) {
strBytes[k++] = _ba[i];
}
for (i = 0; i < _bb.length; i++) {
strBytes[k++] = _bb[i];
}
return string(strBytes);
}
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See {IERC1820Registry} and
* {ERC1820Implementer}.
*/
interface IERC777 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/
function granularity() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function send(address recipient, uint256 amount, bytes calldata data) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/
function burn(uint256 amount, bytes calldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See {operatorSend} and {operatorBurn}.
*/
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor}.
*
* Emits an {AuthorizedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function authorizeOperator(address operator) external;
/**
* @dev Revoke an account's operator status for the caller.
*
* See {isOperatorFor} and {defaultOperators}.
*
* Emits a {RevokedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function revokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if {authorizeOperator} was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* {revokeOperator}, in which case {isOperatorFor} will return false.
*/
function defaultOperators() external view returns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destroys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Bounty.sol - SKALE Manager
Copyright (C) 2020-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "./delegation/DelegationController.sol";
import "./delegation/PartialDifferences.sol";
import "./delegation/TimeHelpers.sol";
import "./delegation/ValidatorService.sol";
import "./ConstantsHolder.sol";
import "./Nodes.sol";
import "./Permissions.sol";
contract BountyV2 is Permissions {
using PartialDifferences for PartialDifferences.Value;
using PartialDifferences for PartialDifferences.Sequence;
struct BountyHistory {
uint month;
uint bountyPaid;
}
uint public constant YEAR1_BOUNTY = 3850e5 * 1e18;
uint public constant YEAR2_BOUNTY = 3465e5 * 1e18;
uint public constant YEAR3_BOUNTY = 3080e5 * 1e18;
uint public constant YEAR4_BOUNTY = 2695e5 * 1e18;
uint public constant YEAR5_BOUNTY = 2310e5 * 1e18;
uint public constant YEAR6_BOUNTY = 1925e5 * 1e18;
uint public constant EPOCHS_PER_YEAR = 12;
uint public constant SECONDS_PER_DAY = 24 * 60 * 60;
uint public constant BOUNTY_WINDOW_SECONDS = 3 * SECONDS_PER_DAY;
uint private _nextEpoch;
uint private _epochPool;
uint private _bountyWasPaidInCurrentEpoch;
bool public bountyReduction;
uint public nodeCreationWindowSeconds;
PartialDifferences.Value private _effectiveDelegatedSum;
// validatorId amount of nodes
mapping (uint => uint) public nodesByValidator; // deprecated
// validatorId => BountyHistory
mapping (uint => BountyHistory) private _bountyHistory;
bytes32 public constant BOUNTY_REDUCTION_MANAGER_ROLE = keccak256("BOUNTY_REDUCTION_MANAGER_ROLE");
modifier onlyBountyReductionManager() {
require(hasRole(BOUNTY_REDUCTION_MANAGER_ROLE, msg.sender), "BOUNTY_REDUCTION_MANAGER_ROLE is required");
_;
}
function calculateBounty(uint nodeIndex)
external
allow("SkaleManager")
returns (uint)
{
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
require(
_getNextRewardTimestamp(nodeIndex, nodes, timeHelpers) <= now,
"Transaction is sent too early"
);
uint validatorId = nodes.getValidatorId(nodeIndex);
if (nodesByValidator[validatorId] > 0) {
delete nodesByValidator[validatorId];
}
uint currentMonth = timeHelpers.getCurrentMonth();
_refillEpochPool(currentMonth, timeHelpers, constantsHolder);
_prepareBountyHistory(validatorId, currentMonth);
uint bounty = _calculateMaximumBountyAmount(
_epochPool,
_effectiveDelegatedSum.getAndUpdateValue(currentMonth),
_bountyWasPaidInCurrentEpoch,
nodeIndex,
_bountyHistory[validatorId].bountyPaid,
delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth),
delegationController.getAndUpdateDelegatedToValidatorNow(validatorId),
constantsHolder,
nodes
);
_bountyHistory[validatorId].bountyPaid = _bountyHistory[validatorId].bountyPaid.add(bounty);
bounty = _reduceBounty(
bounty,
nodeIndex,
nodes,
constantsHolder
);
_epochPool = _epochPool.sub(bounty);
_bountyWasPaidInCurrentEpoch = _bountyWasPaidInCurrentEpoch.add(bounty);
return bounty;
}
function enableBountyReduction() external onlyBountyReductionManager {
bountyReduction = true;
}
function disableBountyReduction() external onlyBountyReductionManager {
bountyReduction = false;
}
function setNodeCreationWindowSeconds(uint window) external allow("Nodes") {
nodeCreationWindowSeconds = window;
}
function handleDelegationAdd(
uint amount,
uint month
)
external
allow("DelegationController")
{
_effectiveDelegatedSum.addToValue(amount, month);
}
function handleDelegationRemoving(
uint amount,
uint month
)
external
allow("DelegationController")
{
_effectiveDelegatedSum.subtractFromValue(amount, month);
}
function estimateBounty(uint nodeIndex) external view returns (uint) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
uint currentMonth = timeHelpers.getCurrentMonth();
uint validatorId = nodes.getValidatorId(nodeIndex);
uint stagePoolSize;
(stagePoolSize, ) = _getEpochPool(currentMonth, timeHelpers, constantsHolder);
return _calculateMaximumBountyAmount(
stagePoolSize,
_effectiveDelegatedSum.getValue(currentMonth),
_nextEpoch == currentMonth.add(1) ? _bountyWasPaidInCurrentEpoch : 0,
nodeIndex,
_getBountyPaid(validatorId, currentMonth),
delegationController.getEffectiveDelegatedToValidator(validatorId, currentMonth),
delegationController.getDelegatedToValidator(validatorId, currentMonth),
constantsHolder,
nodes
);
}
function getNextRewardTimestamp(uint nodeIndex) external view returns (uint) {
return _getNextRewardTimestamp(
nodeIndex,
Nodes(contractManager.getContract("Nodes")),
TimeHelpers(contractManager.getContract("TimeHelpers"))
);
}
function getEffectiveDelegatedSum() external view returns (uint[] memory) {
return _effectiveDelegatedSum.getValues();
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
_nextEpoch = 0;
_epochPool = 0;
_bountyWasPaidInCurrentEpoch = 0;
bountyReduction = false;
nodeCreationWindowSeconds = 3 * SECONDS_PER_DAY;
}
// private
function _calculateMaximumBountyAmount(
uint epochPoolSize,
uint effectiveDelegatedSum,
uint bountyWasPaidInCurrentEpoch,
uint nodeIndex,
uint bountyPaidToTheValidator,
uint effectiveDelegated,
uint delegated,
ConstantsHolder constantsHolder,
Nodes nodes
)
private
view
returns (uint)
{
if (nodes.isNodeLeft(nodeIndex)) {
return 0;
}
if (now < constantsHolder.launchTimestamp()) {
// network is not launched
// bounty is turned off
return 0;
}
if (effectiveDelegatedSum == 0) {
// no delegations in the system
return 0;
}
if (constantsHolder.msr() == 0) {
return 0;
}
uint bounty = _calculateBountyShare(
epochPoolSize.add(bountyWasPaidInCurrentEpoch),
effectiveDelegated,
effectiveDelegatedSum,
delegated.div(constantsHolder.msr()),
bountyPaidToTheValidator
);
return bounty;
}
function _calculateBountyShare(
uint monthBounty,
uint effectiveDelegated,
uint effectiveDelegatedSum,
uint maxNodesAmount,
uint paidToValidator
)
private
pure
returns (uint)
{
if (maxNodesAmount > 0) {
uint totalBountyShare = monthBounty
.mul(effectiveDelegated)
.div(effectiveDelegatedSum);
return _min(
totalBountyShare.div(maxNodesAmount),
totalBountyShare.sub(paidToValidator)
);
} else {
return 0;
}
}
function _getFirstEpoch(TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private view returns (uint) {
return timeHelpers.timestampToMonth(constantsHolder.launchTimestamp());
}
function _getEpochPool(
uint currentMonth,
TimeHelpers timeHelpers,
ConstantsHolder constantsHolder
)
private
view
returns (uint epochPool, uint nextEpoch)
{
epochPool = _epochPool;
for (nextEpoch = _nextEpoch; nextEpoch <= currentMonth; ++nextEpoch) {
epochPool = epochPool.add(_getEpochReward(nextEpoch, timeHelpers, constantsHolder));
}
}
function _refillEpochPool(uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private {
uint epochPool;
uint nextEpoch;
(epochPool, nextEpoch) = _getEpochPool(currentMonth, timeHelpers, constantsHolder);
if (_nextEpoch < nextEpoch) {
(_epochPool, _nextEpoch) = (epochPool, nextEpoch);
_bountyWasPaidInCurrentEpoch = 0;
}
}
function _getEpochReward(
uint epoch,
TimeHelpers timeHelpers,
ConstantsHolder constantsHolder
)
private
view
returns (uint)
{
uint firstEpoch = _getFirstEpoch(timeHelpers, constantsHolder);
if (epoch < firstEpoch) {
return 0;
}
uint epochIndex = epoch.sub(firstEpoch);
uint year = epochIndex.div(EPOCHS_PER_YEAR);
if (year >= 6) {
uint power = year.sub(6).div(3).add(1);
if (power < 256) {
return YEAR6_BOUNTY.div(2 ** power).div(EPOCHS_PER_YEAR);
} else {
return 0;
}
} else {
uint[6] memory customBounties = [
YEAR1_BOUNTY,
YEAR2_BOUNTY,
YEAR3_BOUNTY,
YEAR4_BOUNTY,
YEAR5_BOUNTY,
YEAR6_BOUNTY
];
return customBounties[year].div(EPOCHS_PER_YEAR);
}
}
function _reduceBounty(
uint bounty,
uint nodeIndex,
Nodes nodes,
ConstantsHolder constants
)
private
returns (uint reducedBounty)
{
if (!bountyReduction) {
return bounty;
}
reducedBounty = bounty;
if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) {
reducedBounty = reducedBounty.div(constants.MSR_REDUCING_COEFFICIENT());
}
}
function _prepareBountyHistory(uint validatorId, uint currentMonth) private {
if (_bountyHistory[validatorId].month < currentMonth) {
_bountyHistory[validatorId].month = currentMonth;
delete _bountyHistory[validatorId].bountyPaid;
}
}
function _getBountyPaid(uint validatorId, uint month) private view returns (uint) {
require(_bountyHistory[validatorId].month <= month, "Can't get bounty paid");
if (_bountyHistory[validatorId].month == month) {
return _bountyHistory[validatorId].bountyPaid;
} else {
return 0;
}
}
function _getNextRewardTimestamp(uint nodeIndex, Nodes nodes, TimeHelpers timeHelpers) private view returns (uint) {
uint lastRewardTimestamp = nodes.getNodeLastRewardDate(nodeIndex);
uint lastRewardMonth = timeHelpers.timestampToMonth(lastRewardTimestamp);
uint lastRewardMonthStart = timeHelpers.monthToTimestamp(lastRewardMonth);
uint timePassedAfterMonthStart = lastRewardTimestamp.sub(lastRewardMonthStart);
uint currentMonth = timeHelpers.getCurrentMonth();
assert(lastRewardMonth <= currentMonth);
if (lastRewardMonth == currentMonth) {
uint nextMonthStart = timeHelpers.monthToTimestamp(currentMonth.add(1));
uint nextMonthFinish = timeHelpers.monthToTimestamp(lastRewardMonth.add(2));
if (lastRewardTimestamp < lastRewardMonthStart.add(nodeCreationWindowSeconds)) {
return nextMonthStart.sub(BOUNTY_WINDOW_SECONDS);
} else {
return _min(nextMonthStart.add(timePassedAfterMonthStart), nextMonthFinish.sub(BOUNTY_WINDOW_SECONDS));
}
} else if (lastRewardMonth.add(1) == currentMonth) {
uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth);
uint currentMonthFinish = timeHelpers.monthToTimestamp(currentMonth.add(1));
return _min(
currentMonthStart.add(_max(timePassedAfterMonthStart, nodeCreationWindowSeconds)),
currentMonthFinish.sub(BOUNTY_WINDOW_SECONDS)
);
} else {
uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth);
return currentMonthStart.add(nodeCreationWindowSeconds);
}
}
function _min(uint a, uint b) private pure returns (uint) {
if (a < b) {
return a;
} else {
return b;
}
}
function _max(uint a, uint b) private pure returns (uint) {
if (a < b) {
return b;
} else {
return a;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Nodes.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
@author Dmytro Stebaiev
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/utils/SafeCast.sol";
import "./delegation/DelegationController.sol";
import "./delegation/ValidatorService.sol";
import "./utils/Random.sol";
import "./utils/SegmentTree.sol";
import "./BountyV2.sol";
import "./ConstantsHolder.sol";
import "./Permissions.sol";
/**
* @title Nodes
* @dev This contract contains all logic to manage SKALE Network nodes states,
* space availability, stake requirement checks, and exit functions.
*
* Nodes may be in one of several states:
*
* - Active: Node is registered and is in network operation.
* - Leaving: Node has begun exiting from the network.
* - Left: Node has left the network.
* - In_Maintenance: Node is temporarily offline or undergoing infrastructure
* maintenance
*
* Note: Online nodes contain both Active and Leaving states.
*/
contract Nodes is Permissions {
using Random for Random.RandomGenerator;
using SafeCast for uint;
using SegmentTree for SegmentTree.Tree;
// All Nodes states
enum NodeStatus {Active, Leaving, Left, In_Maintenance}
struct Node {
string name;
bytes4 ip;
bytes4 publicIP;
uint16 port;
bytes32[2] publicKey;
uint startBlock;
uint lastRewardDate;
uint finishTime;
NodeStatus status;
uint validatorId;
}
// struct to note which Nodes and which number of Nodes owned by user
struct CreatedNodes {
mapping (uint => bool) isNodeExist;
uint numberOfNodes;
}
struct SpaceManaging {
uint8 freeSpace;
uint indexInSpaceMap;
}
// TODO: move outside the contract
struct NodeCreationParams {
string name;
bytes4 ip;
bytes4 publicIp;
uint16 port;
bytes32[2] publicKey;
uint16 nonce;
string domainName;
}
bytes32 constant public COMPLIANCE_ROLE = keccak256("COMPLIANCE_ROLE");
bytes32 public constant NODE_MANAGER_ROLE = keccak256("NODE_MANAGER_ROLE");
// array which contain all Nodes
Node[] public nodes;
SpaceManaging[] public spaceOfNodes;
// mapping for checking which Nodes and which number of Nodes owned by user
mapping (address => CreatedNodes) public nodeIndexes;
// mapping for checking is IP address busy
mapping (bytes4 => bool) public nodesIPCheck;
// mapping for checking is Name busy
mapping (bytes32 => bool) public nodesNameCheck;
// mapping for indication from Name to Index
mapping (bytes32 => uint) public nodesNameToIndex;
// mapping for indication from space to Nodes
mapping (uint8 => uint[]) public spaceToNodes;
mapping (uint => uint[]) public validatorToNodeIndexes;
uint public numberOfActiveNodes;
uint public numberOfLeavingNodes;
uint public numberOfLeftNodes;
mapping (uint => string) public domainNames;
mapping (uint => bool) private _invisible;
SegmentTree.Tree private _nodesAmountBySpace;
mapping (uint => bool) public incompliant;
/**
* @dev Emitted when a node is created.
*/
event NodeCreated(
uint nodeIndex,
address owner,
string name,
bytes4 ip,
bytes4 publicIP,
uint16 port,
uint16 nonce,
string domainName,
uint time,
uint gasSpend
);
/**
* @dev Emitted when a node completes a network exit.
*/
event ExitCompleted(
uint nodeIndex,
uint time,
uint gasSpend
);
/**
* @dev Emitted when a node begins to exit from the network.
*/
event ExitInitialized(
uint nodeIndex,
uint startLeavingPeriod,
uint time,
uint gasSpend
);
modifier checkNodeExists(uint nodeIndex) {
_checkNodeIndex(nodeIndex);
_;
}
modifier onlyNodeOrNodeManager(uint nodeIndex) {
_checkNodeOrNodeManager(nodeIndex, msg.sender);
_;
}
modifier onlyCompliance() {
require(hasRole(COMPLIANCE_ROLE, msg.sender), "COMPLIANCE_ROLE is required");
_;
}
modifier nonZeroIP(bytes4 ip) {
require(ip != 0x0 && !nodesIPCheck[ip], "IP address is zero or is not available");
_;
}
/**
* @dev Allows Schains and SchainsInternal contracts to occupy available
* space on a node.
*
* Returns whether operation is successful.
*/
function removeSpaceFromNode(uint nodeIndex, uint8 space)
external
checkNodeExists(nodeIndex)
allowTwo("NodeRotation", "SchainsInternal")
returns (bool)
{
if (spaceOfNodes[nodeIndex].freeSpace < space) {
return false;
}
if (space > 0) {
_moveNodeToNewSpaceMap(
nodeIndex,
uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8()
);
}
return true;
}
/**
* @dev Allows Schains contract to occupy free space on a node.
*
* Returns whether operation is successful.
*/
function addSpaceToNode(uint nodeIndex, uint8 space)
external
checkNodeExists(nodeIndex)
allowTwo("Schains", "NodeRotation")
{
if (space > 0) {
_moveNodeToNewSpaceMap(
nodeIndex,
uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8()
);
}
}
/**
* @dev Allows SkaleManager to change a node's last reward date.
*/
function changeNodeLastRewardDate(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
nodes[nodeIndex].lastRewardDate = block.timestamp;
}
/**
* @dev Allows SkaleManager to change a node's finish time.
*/
function changeNodeFinishTime(uint nodeIndex, uint time)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
nodes[nodeIndex].finishTime = time;
}
/**
* @dev Allows SkaleManager contract to create new node and add it to the
* Nodes contract.
*
* Emits a {NodeCreated} event.
*
* Requirements:
*
* - Node IP must be non-zero.
* - Node IP must be available.
* - Node name must not already be registered.
* - Node port must be greater than zero.
*/
function createNode(address from, NodeCreationParams calldata params)
external
allow("SkaleManager")
nonZeroIP(params.ip)
{
// checks that Node has correct data
require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered");
require(params.port > 0, "Port is zero");
require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect");
uint validatorId = ValidatorService(
contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from);
uint8 totalSpace = ConstantsHolder(contractManager.getContract("ConstantsHolder")).TOTAL_SPACE_ON_NODE();
nodes.push(Node({
name: params.name,
ip: params.ip,
publicIP: params.publicIp,
port: params.port,
publicKey: params.publicKey,
startBlock: block.number,
lastRewardDate: block.timestamp,
finishTime: 0,
status: NodeStatus.Active,
validatorId: validatorId
}));
uint nodeIndex = nodes.length.sub(1);
validatorToNodeIndexes[validatorId].push(nodeIndex);
bytes32 nodeId = keccak256(abi.encodePacked(params.name));
nodesIPCheck[params.ip] = true;
nodesNameCheck[nodeId] = true;
nodesNameToIndex[nodeId] = nodeIndex;
nodeIndexes[from].isNodeExist[nodeIndex] = true;
nodeIndexes[from].numberOfNodes++;
domainNames[nodeIndex] = params.domainName;
spaceOfNodes.push(SpaceManaging({
freeSpace: totalSpace,
indexInSpaceMap: spaceToNodes[totalSpace].length
}));
_setNodeActive(nodeIndex);
emit NodeCreated(
nodeIndex,
from,
params.name,
params.ip,
params.publicIp,
params.port,
params.nonce,
params.domainName,
block.timestamp,
gasleft());
}
/**
* @dev Allows SkaleManager contract to initiate a node exit procedure.
*
* Returns whether the operation is successful.
*
* Emits an {ExitInitialized} event.
*/
function initExit(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
returns (bool)
{
require(isNodeActive(nodeIndex), "Node should be Active");
_setNodeLeaving(nodeIndex);
emit ExitInitialized(
nodeIndex,
block.timestamp,
block.timestamp,
gasleft());
return true;
}
/**
* @dev Allows SkaleManager contract to complete a node exit procedure.
*
* Returns whether the operation is successful.
*
* Emits an {ExitCompleted} event.
*
* Requirements:
*
* - Node must have already initialized a node exit procedure.
*/
function completeExit(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
returns (bool)
{
require(isNodeLeaving(nodeIndex), "Node is not Leaving");
_setNodeLeft(nodeIndex);
emit ExitCompleted(
nodeIndex,
block.timestamp,
gasleft());
return true;
}
/**
* @dev Allows SkaleManager contract to delete a validator's node.
*
* Requirements:
*
* - Validator ID must exist.
*/
function deleteNodeForValidator(uint validatorId, uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
uint[] memory validatorNodes = validatorToNodeIndexes[validatorId];
uint position = _findNode(validatorNodes, nodeIndex);
if (position < validatorNodes.length) {
validatorToNodeIndexes[validatorId][position] =
validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)];
}
validatorToNodeIndexes[validatorId].pop();
address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey);
if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) {
if (nodeIndexes[nodeOwner].numberOfNodes == 1 && !validatorService.validatorAddressExists(nodeOwner)) {
validatorService.removeNodeAddress(validatorId, nodeOwner);
}
nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false;
nodeIndexes[nodeOwner].numberOfNodes--;
}
}
/**
* @dev Allows SkaleManager contract to check whether a validator has
* sufficient stake to create another node.
*
* Requirements:
*
* - Validator must be included on trusted list if trusted list is enabled.
* - Validator must have sufficient stake to operate an additional node.
*/
function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") {
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress);
require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node");
require(
_checkValidatorPositionToMaintainNode(validatorId, validatorToNodeIndexes[validatorId].length),
"Validator must meet the Minimum Staking Requirement");
}
/**
* @dev Allows SkaleManager contract to check whether a validator has
* sufficient stake to maintain a node.
*
* Returns whether validator can maintain node with current stake.
*
* Requirements:
*
* - Validator ID and nodeIndex must both exist.
*/
function checkPossibilityToMaintainNode(
uint validatorId,
uint nodeIndex
)
external
checkNodeExists(nodeIndex)
allow("Bounty")
returns (bool)
{
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
uint[] memory validatorNodes = validatorToNodeIndexes[validatorId];
uint position = _findNode(validatorNodes, nodeIndex);
require(position < validatorNodes.length, "Node does not exist for this Validator");
return _checkValidatorPositionToMaintainNode(validatorId, position);
}
/**
* @dev Allows Node to set In_Maintenance status.
*
* Requirements:
*
* - Node must already be Active.
* - `msg.sender` must be owner of Node, validator, or SkaleManager.
*/
function setNodeInMaintenance(uint nodeIndex) external onlyNodeOrNodeManager(nodeIndex) {
require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active");
_setNodeInMaintenance(nodeIndex);
}
/**
* @dev Allows Node to remove In_Maintenance status.
*
* Requirements:
*
* - Node must already be In Maintenance.
* - `msg.sender` must be owner of Node, validator, or SkaleManager.
*/
function removeNodeFromInMaintenance(uint nodeIndex) external onlyNodeOrNodeManager(nodeIndex) {
require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance");
_setNodeActive(nodeIndex);
}
/**
* @dev Marks the node as incompliant
*
*/
function setNodeIncompliant(uint nodeIndex) external onlyCompliance checkNodeExists(nodeIndex) {
if (!incompliant[nodeIndex]) {
incompliant[nodeIndex] = true;
_makeNodeInvisible(nodeIndex);
}
}
/**
* @dev Marks the node as compliant
*
*/
function setNodeCompliant(uint nodeIndex) external onlyCompliance checkNodeExists(nodeIndex) {
if (incompliant[nodeIndex]) {
incompliant[nodeIndex] = false;
_tryToMakeNodeVisible(nodeIndex);
}
}
function setDomainName(uint nodeIndex, string memory domainName)
external
onlyNodeOrNodeManager(nodeIndex)
{
domainNames[nodeIndex] = domainName;
}
function makeNodeVisible(uint nodeIndex) external allow("SchainsInternal") {
_tryToMakeNodeVisible(nodeIndex);
}
function makeNodeInvisible(uint nodeIndex) external allow("SchainsInternal") {
_makeNodeInvisible(nodeIndex);
}
function changeIP(
uint nodeIndex,
bytes4 newIP,
bytes4 newPublicIP
)
external
onlyAdmin
checkNodeExists(nodeIndex)
nonZeroIP(newIP)
{
if (newPublicIP != 0x0) {
require(newIP == newPublicIP, "IP address is not the same");
nodes[nodeIndex].publicIP = newPublicIP;
}
nodesIPCheck[nodes[nodeIndex].ip] = false;
nodesIPCheck[newIP] = true;
nodes[nodeIndex].ip = newIP;
}
function getRandomNodeWithFreeSpace(
uint8 freeSpace,
Random.RandomGenerator memory randomGenerator
)
external
view
returns (uint)
{
uint8 place = _nodesAmountBySpace.getRandomNonZeroElementFromPlaceToLast(
freeSpace == 0 ? 1 : freeSpace,
randomGenerator
).toUint8();
require(place > 0, "Node not found");
return spaceToNodes[place][randomGenerator.random(spaceToNodes[place].length)];
}
/**
* @dev Checks whether it is time for a node's reward.
*/
function isTimeForReward(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bool)
{
return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= now;
}
/**
* @dev Returns IP address of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodeIP(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bytes4)
{
require(nodeIndex < nodes.length, "Node does not exist");
return nodes[nodeIndex].ip;
}
/**
* @dev Returns domain name of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodeDomainName(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (string memory)
{
return domainNames[nodeIndex];
}
/**
* @dev Returns the port of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodePort(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint16)
{
return nodes[nodeIndex].port;
}
/**
* @dev Returns the public key of a given node.
*/
function getNodePublicKey(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bytes32[2] memory)
{
return nodes[nodeIndex].publicKey;
}
/**
* @dev Returns an address of a given node.
*/
function getNodeAddress(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (address)
{
return _publicKeyToAddress(nodes[nodeIndex].publicKey);
}
/**
* @dev Returns the finish exit time of a given node.
*/
function getNodeFinishTime(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].finishTime;
}
/**
* @dev Checks whether a node has left the network.
*/
function isNodeLeft(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Left;
}
function isNodeInMaintenance(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.In_Maintenance;
}
/**
* @dev Returns a given node's last reward date.
*/
function getNodeLastRewardDate(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].lastRewardDate;
}
/**
* @dev Returns a given node's next reward date.
*/
function getNodeNextRewardDate(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint)
{
return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex);
}
/**
* @dev Returns the total number of registered nodes.
*/
function getNumberOfNodes() external view returns (uint) {
return nodes.length;
}
/**
* @dev Returns the total number of online nodes.
*
* Note: Online nodes are equal to the number of active plus leaving nodes.
*/
function getNumberOnlineNodes() external view returns (uint) {
return numberOfActiveNodes.add(numberOfLeavingNodes);
}
/**
* @dev Return active node IDs.
*/
function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) {
activeNodeIds = new uint[](numberOfActiveNodes);
uint indexOfActiveNodeIds = 0;
for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) {
if (isNodeActive(indexOfNodes)) {
activeNodeIds[indexOfActiveNodeIds] = indexOfNodes;
indexOfActiveNodeIds++;
}
}
}
/**
* @dev Return a given node's current status.
*/
function getNodeStatus(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (NodeStatus)
{
return nodes[nodeIndex].status;
}
/**
* @dev Return a validator's linked nodes.
*
* Requirements:
*
* - Validator ID must exist.
*/
function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) {
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
return validatorToNodeIndexes[validatorId];
}
/**
* @dev Returns number of nodes with available space.
*/
function countNodesWithFreeSpace(uint8 freeSpace) external view returns (uint count) {
if (freeSpace == 0) {
return _nodesAmountBySpace.sumFromPlaceToLast(1);
}
return _nodesAmountBySpace.sumFromPlaceToLast(freeSpace);
}
/**
* @dev constructor in Permissions approach.
*/
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
numberOfActiveNodes = 0;
numberOfLeavingNodes = 0;
numberOfLeftNodes = 0;
_nodesAmountBySpace.create(128);
}
/**
* @dev Returns the Validator ID for a given node.
*/
function getValidatorId(uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].validatorId;
}
/**
* @dev Checks whether a node exists for a given address.
*/
function isNodeExist(address from, uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodeIndexes[from].isNodeExist[nodeIndex];
}
/**
* @dev Checks whether a node's status is Active.
*/
function isNodeActive(uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Active;
}
/**
* @dev Checks whether a node's status is Leaving.
*/
function isNodeLeaving(uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Leaving;
}
function _removeNodeFromSpaceToNodes(uint nodeIndex, uint8 space) internal {
uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap;
uint len = spaceToNodes[space].length.sub(1);
if (indexInArray < len) {
uint shiftedIndex = spaceToNodes[space][len];
spaceToNodes[space][indexInArray] = shiftedIndex;
spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray;
}
spaceToNodes[space].pop();
delete spaceOfNodes[nodeIndex].indexInSpaceMap;
}
function _getNodesAmountBySpace() internal view returns (SegmentTree.Tree storage) {
return _nodesAmountBySpace;
}
/**
* @dev Returns the index of a given node within the validator's node index.
*/
function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) {
uint i;
for (i = 0; i < validatorNodeIndexes.length; i++) {
if (validatorNodeIndexes[i] == nodeIndex) {
return i;
}
}
return validatorNodeIndexes.length;
}
/**
* @dev Moves a node to a new space mapping.
*/
function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private {
if (!_invisible[nodeIndex]) {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_removeNodeFromTree(space);
_addNodeToTree(newSpace);
_removeNodeFromSpaceToNodes(nodeIndex, space);
_addNodeToSpaceToNodes(nodeIndex, newSpace);
}
spaceOfNodes[nodeIndex].freeSpace = newSpace;
}
/**
* @dev Changes a node's status to Active.
*/
function _setNodeActive(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.Active;
numberOfActiveNodes = numberOfActiveNodes.add(1);
if (_invisible[nodeIndex]) {
_tryToMakeNodeVisible(nodeIndex);
} else {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_addNodeToSpaceToNodes(nodeIndex, space);
_addNodeToTree(space);
}
}
/**
* @dev Changes a node's status to In_Maintenance.
*/
function _setNodeInMaintenance(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.In_Maintenance;
numberOfActiveNodes = numberOfActiveNodes.sub(1);
_makeNodeInvisible(nodeIndex);
}
/**
* @dev Changes a node's status to Left.
*/
function _setNodeLeft(uint nodeIndex) private {
nodesIPCheck[nodes[nodeIndex].ip] = false;
nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false;
delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))];
if (nodes[nodeIndex].status == NodeStatus.Active) {
numberOfActiveNodes--;
} else {
numberOfLeavingNodes--;
}
nodes[nodeIndex].status = NodeStatus.Left;
numberOfLeftNodes++;
delete spaceOfNodes[nodeIndex].freeSpace;
}
/**
* @dev Changes a node's status to Leaving.
*/
function _setNodeLeaving(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.Leaving;
numberOfActiveNodes--;
numberOfLeavingNodes++;
_makeNodeInvisible(nodeIndex);
}
function _makeNodeInvisible(uint nodeIndex) private {
if (!_invisible[nodeIndex]) {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_removeNodeFromSpaceToNodes(nodeIndex, space);
_removeNodeFromTree(space);
_invisible[nodeIndex] = true;
}
}
function _tryToMakeNodeVisible(uint nodeIndex) private {
if (_invisible[nodeIndex] && _canBeVisible(nodeIndex)) {
_makeNodeVisible(nodeIndex);
}
}
function _makeNodeVisible(uint nodeIndex) private {
if (_invisible[nodeIndex]) {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
_addNodeToSpaceToNodes(nodeIndex, space);
_addNodeToTree(space);
delete _invisible[nodeIndex];
}
}
function _addNodeToSpaceToNodes(uint nodeIndex, uint8 space) private {
spaceToNodes[space].push(nodeIndex);
spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[space].length.sub(1);
}
function _addNodeToTree(uint8 space) private {
if (space > 0) {
_nodesAmountBySpace.addToPlace(space, 1);
}
}
function _removeNodeFromTree(uint8 space) private {
if (space > 0) {
_nodesAmountBySpace.removeFromPlace(space, 1);
}
}
function _checkValidatorPositionToMaintainNode(uint validatorId, uint position) private returns (bool) {
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId);
uint msr = ConstantsHolder(contractManager.getConstantsHolder()).msr();
return position.add(1).mul(msr) <= delegationsTotal;
}
function _checkNodeIndex(uint nodeIndex) private view {
require(nodeIndex < nodes.length, "Node with such index does not exist");
}
function _checkNodeOrNodeManager(uint nodeIndex, address sender) private view {
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
require(
isNodeExist(sender, nodeIndex) ||
hasRole(NODE_MANAGER_ROLE, msg.sender) ||
getValidatorId(nodeIndex) == validatorService.getValidatorId(sender),
"Sender is not permitted to call this function"
);
}
function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) {
bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1]));
bytes20 addr;
for (uint8 i = 12; i < 32; i++) {
addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8);
}
return address(addr);
}
function _canBeVisible(uint nodeIndex) private view returns (bool) {
return !incompliant[nodeIndex] && nodes[nodeIndex].status == NodeStatus.Active;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
FractionUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
library FractionUtils {
using SafeMath for uint;
struct Fraction {
uint numerator;
uint denominator;
}
function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) {
require(denominator > 0, "Division by zero");
Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator});
reduceFraction(fraction);
return fraction;
}
function createFraction(uint value) internal pure returns (Fraction memory) {
return createFraction(value, 1);
}
function reduceFraction(Fraction memory fraction) internal pure {
uint _gcd = gcd(fraction.numerator, fraction.denominator);
fraction.numerator = fraction.numerator.div(_gcd);
fraction.denominator = fraction.denominator.div(_gcd);
}
// numerator - is limited by 7*10^27, we could multiply it numerator * numerator - it would less than 2^256-1
function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) {
return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator));
}
function gcd(uint a, uint b) internal pure returns (uint) {
uint _a = a;
uint _b = b;
if (_b > _a) {
(_a, _b) = swap(_a, _b);
}
while (_b > 0) {
_a = _a.mod(_b);
(_a, _b) = swap (_a, _b);
}
return _a;
}
function swap(uint a, uint b) internal pure returns (uint, uint) {
return (b, a);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
MathUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
library MathUtils {
uint constant private _EPS = 1e6;
event UnderflowError(
uint a,
uint b
);
function boundedSub(uint256 a, uint256 b) internal returns (uint256) {
if (a >= b) {
return a - b;
} else {
emit UnderflowError(a, b);
return 0;
}
}
function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) {
if (a >= b) {
return a - b;
} else {
return 0;
}
}
function muchGreater(uint256 a, uint256 b) internal pure returns (bool) {
assert(uint(-1) - _EPS > b);
return a > b + _EPS;
}
function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) {
if (a > b) {
return a - b < _EPS;
} else {
return b - a < _EPS;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
DelegationPeriodManager.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../Permissions.sol";
import "../ConstantsHolder.sol";
/**
* @title Delegation Period Manager
* @dev This contract handles all delegation offerings. Delegations are held for
* a specified period (months), and different durations can have different
* returns or `stakeMultiplier`. Currently, only delegation periods can be added.
*/
contract DelegationPeriodManager is Permissions {
mapping (uint => uint) public stakeMultipliers;
bytes32 public constant DELEGATION_PERIOD_SETTER_ROLE = keccak256("DELEGATION_PERIOD_SETTER_ROLE");
/**
* @dev Emitted when a new delegation period is specified.
*/
event DelegationPeriodWasSet(
uint length,
uint stakeMultiplier
);
/**
* @dev Allows the Owner to create a new available delegation period and
* stake multiplier in the network.
*
* Emits a {DelegationPeriodWasSet} event.
*/
function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external {
require(hasRole(DELEGATION_PERIOD_SETTER_ROLE, msg.sender), "DELEGATION_PERIOD_SETTER_ROLE is required");
require(stakeMultipliers[monthsCount] == 0, "Delegation period is already set");
stakeMultipliers[monthsCount] = stakeMultiplier;
emit DelegationPeriodWasSet(monthsCount, stakeMultiplier);
}
/**
* @dev Checks whether given delegation period is allowed.
*/
function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) {
return stakeMultipliers[monthsCount] != 0;
}
/**
* @dev Initial delegation period and multiplier settings.
*/
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
stakeMultipliers[2] = 100; // 2 months at 100
// stakeMultipliers[6] = 150; // 6 months at 150
// stakeMultipliers[12] = 200; // 12 months at 200
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
PartialDifferences.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../utils/MathUtils.sol";
import "../utils/FractionUtils.sol";
/**
* @title Partial Differences Library
* @dev This library contains functions to manage Partial Differences data
* structure. Partial Differences is an array of value differences over time.
*
* For example: assuming an array [3, 6, 3, 1, 2], partial differences can
* represent this array as [_, 3, -3, -2, 1].
*
* This data structure allows adding values on an open interval with O(1)
* complexity.
*
* For example: add +5 to [3, 6, 3, 1, 2] starting from the second element (3),
* instead of performing [3, 6, 3+5, 1+5, 2+5] partial differences allows
* performing [_, 3, -3+5, -2, 1]. The original array can be restored by
* adding values from partial differences.
*/
library PartialDifferences {
using SafeMath for uint;
using MathUtils for uint;
struct Sequence {
// month => diff
mapping (uint => uint) addDiff;
// month => diff
mapping (uint => uint) subtractDiff;
// month => value
mapping (uint => uint) value;
uint firstUnprocessedMonth;
uint lastChangedMonth;
}
struct Value {
// month => diff
mapping (uint => uint) addDiff;
// month => diff
mapping (uint => uint) subtractDiff;
uint value;
uint firstUnprocessedMonth;
uint lastChangedMonth;
}
// functions for sequence
function addToSequence(Sequence storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
}
sequence.addDiff[month] = sequence.addDiff[month].add(diff);
if (sequence.lastChangedMonth != month) {
sequence.lastChangedMonth = month;
}
}
function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
}
sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff);
if (sequence.lastChangedMonth != month) {
sequence.lastChangedMonth = month;
}
}
function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) {
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]);
if (sequence.value[i] != nextValue) {
sequence.value[i] = nextValue;
}
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
sequence.firstUnprocessedMonth = month.add(1);
}
return sequence.value[month];
}
function getValueInSequence(Sequence storage sequence, uint month) internal view returns (uint) {
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value[sequence.firstUnprocessedMonth.sub(1)];
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]);
}
return value;
} else {
return sequence.value[month];
}
}
function getValuesInSequence(Sequence storage sequence) internal view returns (uint[] memory values) {
if (sequence.firstUnprocessedMonth == 0) {
return values;
}
uint begin = sequence.firstUnprocessedMonth.sub(1);
uint end = sequence.lastChangedMonth.add(1);
if (end <= begin) {
end = begin.add(1);
}
values = new uint[](end.sub(begin));
values[0] = sequence.value[sequence.firstUnprocessedMonth.sub(1)];
for (uint i = 0; i.add(1) < values.length; ++i) {
uint month = sequence.firstUnprocessedMonth.add(i);
values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]);
}
}
function reduceSequence(
Sequence storage sequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month) internal
{
require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
require(
reducingCoefficient.numerator <= reducingCoefficient.denominator,
"Increasing of values is not implemented");
if (sequence.firstUnprocessedMonth == 0) {
return;
}
uint value = getAndUpdateValueInSequence(sequence, month);
if (value.approximatelyEqual(0)) {
return;
}
sequence.value[month] = sequence.value[month]
.mul(reducingCoefficient.numerator)
.div(reducingCoefficient.denominator);
for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) {
sequence.subtractDiff[i] = sequence.subtractDiff[i]
.mul(reducingCoefficient.numerator)
.div(reducingCoefficient.denominator);
}
}
// functions for value
function addToValue(Value storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
sequence.lastChangedMonth = month;
}
if (month > sequence.lastChangedMonth) {
sequence.lastChangedMonth = month;
}
if (month >= sequence.firstUnprocessedMonth) {
sequence.addDiff[month] = sequence.addDiff[month].add(diff);
} else {
sequence.value = sequence.value.add(diff);
}
}
function subtractFromValue(Value storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
sequence.lastChangedMonth = month;
}
if (month > sequence.lastChangedMonth) {
sequence.lastChangedMonth = month;
}
if (month >= sequence.firstUnprocessedMonth) {
sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff);
} else {
sequence.value = sequence.value.boundedSub(diff);
}
}
function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) {
require(
month.add(1) >= sequence.firstUnprocessedMonth,
"Cannot calculate value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value;
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]);
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
if (sequence.value != value) {
sequence.value = value;
}
sequence.firstUnprocessedMonth = month.add(1);
}
return sequence.value;
}
function getValue(Value storage sequence, uint month) internal view returns (uint) {
require(
month.add(1) >= sequence.firstUnprocessedMonth,
"Cannot calculate value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value;
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]);
}
return value;
} else {
return sequence.value;
}
}
function getValues(Value storage sequence) internal view returns (uint[] memory values) {
if (sequence.firstUnprocessedMonth == 0) {
return values;
}
uint begin = sequence.firstUnprocessedMonth.sub(1);
uint end = sequence.lastChangedMonth.add(1);
if (end <= begin) {
end = begin.add(1);
}
values = new uint[](end.sub(begin));
values[0] = sequence.value;
for (uint i = 0; i.add(1) < values.length; ++i) {
uint month = sequence.firstUnprocessedMonth.add(i);
values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]);
}
}
function reduceValue(
Value storage sequence,
uint amount,
uint month)
internal returns (FractionUtils.Fraction memory)
{
require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return FractionUtils.createFraction(0);
}
uint value = getAndUpdateValue(sequence, month);
if (value.approximatelyEqual(0)) {
return FractionUtils.createFraction(0);
}
uint _amount = amount;
if (value < amount) {
_amount = value;
}
FractionUtils.Fraction memory reducingCoefficient =
FractionUtils.createFraction(value.boundedSub(_amount), value);
reduceValueByCoefficient(sequence, reducingCoefficient, month);
return reducingCoefficient;
}
function reduceValueByCoefficient(
Value storage sequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month)
internal
{
reduceValueByCoefficientAndUpdateSumIfNeeded(
sequence,
sequence,
reducingCoefficient,
month,
false);
}
function reduceValueByCoefficientAndUpdateSum(
Value storage sequence,
Value storage sumSequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month) internal
{
reduceValueByCoefficientAndUpdateSumIfNeeded(
sequence,
sumSequence,
reducingCoefficient,
month,
true);
}
function reduceValueByCoefficientAndUpdateSumIfNeeded(
Value storage sequence,
Value storage sumSequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month,
bool hasSumSequence) internal
{
require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
if (hasSumSequence) {
require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past");
}
require(
reducingCoefficient.numerator <= reducingCoefficient.denominator,
"Increasing of values is not implemented");
if (sequence.firstUnprocessedMonth == 0) {
return;
}
uint value = getAndUpdateValue(sequence, month);
if (value.approximatelyEqual(0)) {
return;
}
uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator);
if (hasSumSequence) {
subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month);
}
sequence.value = newValue;
for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) {
uint newDiff = sequence.subtractDiff[i]
.mul(reducingCoefficient.numerator)
.div(reducingCoefficient.denominator);
if (hasSumSequence) {
sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i]
.boundedSub(sequence.subtractDiff[i].boundedSub(newDiff));
}
sequence.subtractDiff[i] = newDiff;
}
}
function clear(Value storage sequence) internal {
for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) {
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
if (sequence.value > 0) {
delete sequence.value;
}
if (sequence.firstUnprocessedMonth > 0) {
delete sequence.firstUnprocessedMonth;
}
if (sequence.lastChangedMonth > 0) {
delete sequence.lastChangedMonth;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Punisher.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../Permissions.sol";
import "../interfaces/delegation/ILocker.sol";
import "./ValidatorService.sol";
import "./DelegationController.sol";
/**
* @title Punisher
* @dev This contract handles all slashing and forgiving operations.
*/
contract Punisher is Permissions, ILocker {
// holder => tokens
mapping (address => uint) private _locked;
bytes32 public constant FORGIVER_ROLE = keccak256("FORGIVER_ROLE");
/**
* @dev Emitted upon slashing condition.
*/
event Slash(
uint validatorId,
uint amount
);
/**
* @dev Emitted upon forgive condition.
*/
event Forgive(
address wallet,
uint amount
);
/**
* @dev Allows SkaleDKG contract to execute slashing on a validator and
* validator's delegations by an `amount` of tokens.
*
* Emits a {Slash} event.
*
* Requirements:
*
* - Validator must exist.
*/
function slash(uint validatorId, uint amount) external allow("SkaleDKG") {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
require(validatorService.validatorExists(validatorId), "Validator does not exist");
delegationController.confiscate(validatorId, amount);
emit Slash(validatorId, amount);
}
/**
* @dev Allows the Admin to forgive a slashing condition.
*
* Emits a {Forgive} event.
*
* Requirements:
*
* - All slashes must have been processed.
*/
function forgive(address holder, uint amount) external {
require(hasRole(FORGIVER_ROLE, msg.sender), "FORGIVER_ROLE is required");
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated");
if (amount > _locked[holder]) {
delete _locked[holder];
} else {
_locked[holder] = _locked[holder].sub(amount);
}
emit Forgive(holder, amount);
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev Allows DelegationController contract to execute slashing of
* delegations.
*/
function handleSlash(address holder, uint amount) external allow("DelegationController") {
_locked[holder] = _locked[holder].add(amount);
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
}
// private
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function _getAndUpdateLockedAmount(address wallet) private returns (uint) {
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
delegationController.processAllSlashes(wallet);
return _locked[wallet];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
TokenState.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../interfaces/delegation/ILocker.sol";
import "../Permissions.sol";
import "./DelegationController.sol";
import "./TimeHelpers.sol";
/**
* @title Token State
* @dev This contract manages lockers to control token transferability.
*
* The SKALE Network has three types of locked tokens:
*
* - Tokens that are transferrable but are currently locked into delegation with
* a validator.
*
* - Tokens that are not transferable from one address to another, but may be
* delegated to a validator `getAndUpdateLockedAmount`. This lock enforces
* Proof-of-Use requirements.
*
* - Tokens that are neither transferable nor delegatable
* `getAndUpdateForbiddenForDelegationAmount`. This lock enforces slashing.
*/
contract TokenState is Permissions, ILocker {
string[] private _lockers;
DelegationController private _delegationController;
bytes32 public constant LOCKER_MANAGER_ROLE = keccak256("LOCKER_MANAGER_ROLE");
modifier onlyLockerManager() {
require(hasRole(LOCKER_MANAGER_ROLE, msg.sender), "LOCKER_MANAGER_ROLE is required");
_;
}
/**
* @dev Emitted when a contract is added to the locker.
*/
event LockerWasAdded(
string locker
);
/**
* @dev Emitted when a contract is removed from the locker.
*/
event LockerWasRemoved(
string locker
);
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address holder) external override returns (uint) {
if (address(_delegationController) == address(0)) {
_delegationController =
DelegationController(contractManager.getContract("DelegationController"));
}
uint locked = 0;
if (_delegationController.getDelegationsByHolderLength(holder) > 0) {
// the holder ever delegated
for (uint i = 0; i < _lockers.length; ++i) {
ILocker locker = ILocker(contractManager.getContract(_lockers[i]));
locked = locked.add(locker.getAndUpdateLockedAmount(holder));
}
}
return locked;
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) {
uint forbidden = 0;
for (uint i = 0; i < _lockers.length; ++i) {
ILocker locker = ILocker(contractManager.getContract(_lockers[i]));
forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder));
}
return forbidden;
}
/**
* @dev Allows the Owner to remove a contract from the locker.
*
* Emits a {LockerWasRemoved} event.
*/
function removeLocker(string calldata locker) external onlyLockerManager {
uint index;
bytes32 hash = keccak256(abi.encodePacked(locker));
for (index = 0; index < _lockers.length; ++index) {
if (keccak256(abi.encodePacked(_lockers[index])) == hash) {
break;
}
}
if (index < _lockers.length) {
if (index < _lockers.length.sub(1)) {
_lockers[index] = _lockers[_lockers.length.sub(1)];
}
delete _lockers[_lockers.length.sub(1)];
_lockers.pop();
emit LockerWasRemoved(locker);
}
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
_setupRole(LOCKER_MANAGER_ROLE, msg.sender);
addLocker("DelegationController");
addLocker("Punisher");
}
/**
* @dev Allows the Owner to add a contract to the Locker.
*
* Emits a {LockerWasAdded} event.
*/
function addLocker(string memory locker) public onlyLockerManager {
_lockers.push(locker);
emit LockerWasAdded(locker);
}
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SegmentTree.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
/**
* @title Random
* @dev The library for generating of pseudo random numbers
*/
library Random {
using SafeMath for uint;
struct RandomGenerator {
uint seed;
}
/**
* @dev Create an instance of RandomGenerator
*/
function create(uint seed) internal pure returns (RandomGenerator memory) {
return RandomGenerator({seed: seed});
}
function createFromEntropy(bytes memory entropy) internal pure returns (RandomGenerator memory) {
return create(uint(keccak256(entropy)));
}
/**
* @dev Generates random value
*/
function random(RandomGenerator memory self) internal pure returns (uint) {
self.seed = uint(sha256(abi.encodePacked(self.seed)));
return self.seed;
}
/**
* @dev Generates random value in range [0, max)
*/
function random(RandomGenerator memory self, uint max) internal pure returns (uint) {
assert(max > 0);
uint maxRand = uint(-1).sub(uint(-1).mod(max));
if (uint(-1).sub(maxRand) == max.sub(1)) {
return random(self).mod(max);
} else {
uint rand = random(self);
while (rand >= maxRand) {
rand = random(self);
}
return rand.mod(max);
}
}
/**
* @dev Generates random value in range [min, max)
*/
function random(RandomGenerator memory self, uint min, uint max) internal pure returns (uint) {
assert(min < max);
return min.add(random(self, max.sub(min)));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SegmentTree.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Artem Payvin
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "./Random.sol";
/**
* @title SegmentTree
* @dev This library implements segment tree data structure
*
* Segment tree allows effectively calculate sum of elements in sub arrays
* by storing some amount of additional data.
*
* IMPORTANT: Provided implementation assumes that arrays is indexed from 1 to n.
* Size of initial array always must be power of 2
*
* Example:
*
* Array:
* +---+---+---+---+---+---+---+---+
* | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
* +---+---+---+---+---+---+---+---+
*
* Segment tree structure:
* +-------------------------------+
* | 36 |
* +---------------+---------------+
* | 10 | 26 |
* +-------+-------+-------+-------+
* | 3 | 7 | 11 | 15 |
* +---+---+---+---+---+---+---+---+
* | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
* +---+---+---+---+---+---+---+---+
*
* How the segment tree is stored in an array:
* +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+
* | 36 | 10 | 26 | 3 | 7 | 11 | 15 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
* +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+
*/
library SegmentTree {
using Random for Random.RandomGenerator;
using SafeMath for uint;
struct Tree {
uint[] tree;
}
/**
* @dev Allocates storage for segment tree of `size` elements
*
* Requirements:
*
* - `size` must be greater than 0
* - `size` must be power of 2
*/
function create(Tree storage segmentTree, uint size) external {
require(size > 0, "Size can't be 0");
require(size & size.sub(1) == 0, "Size is not power of 2");
segmentTree.tree = new uint[](size.mul(2).sub(1));
}
/**
* @dev Adds `delta` to element of segment tree at `place`
*
* Requirements:
*
* - `place` must be in range [1, size]
*/
function addToPlace(Tree storage self, uint place, uint delta) external {
require(_correctPlace(self, place), "Incorrect place");
uint leftBound = 1;
uint rightBound = getSize(self);
uint step = 1;
self.tree[0] = self.tree[0].add(delta);
while(leftBound < rightBound) {
uint middle = leftBound.add(rightBound).div(2);
if (place > middle) {
leftBound = middle.add(1);
step = step.add(step).add(1);
} else {
rightBound = middle;
step = step.add(step);
}
self.tree[step.sub(1)] = self.tree[step.sub(1)].add(delta);
}
}
/**
* @dev Subtracts `delta` from element of segment tree at `place`
*
* Requirements:
*
* - `place` must be in range [1, size]
* - initial value of target element must be not less than `delta`
*/
function removeFromPlace(Tree storage self, uint place, uint delta) external {
require(_correctPlace(self, place), "Incorrect place");
uint leftBound = 1;
uint rightBound = getSize(self);
uint step = 1;
self.tree[0] = self.tree[0].sub(delta);
while(leftBound < rightBound) {
uint middle = leftBound.add(rightBound).div(2);
if (place > middle) {
leftBound = middle.add(1);
step = step.add(step).add(1);
} else {
rightBound = middle;
step = step.add(step);
}
self.tree[step.sub(1)] = self.tree[step.sub(1)].sub(delta);
}
}
/**
* @dev Adds `delta` to element of segment tree at `toPlace`
* and subtracts `delta` from element at `fromPlace`
*
* Requirements:
*
* - `fromPlace` must be in range [1, size]
* - `toPlace` must be in range [1, size]
* - initial value of element at `fromPlace` must be not less than `delta`
*/
function moveFromPlaceToPlace(
Tree storage self,
uint fromPlace,
uint toPlace,
uint delta
)
external
{
require(_correctPlace(self, fromPlace) && _correctPlace(self, toPlace), "Incorrect place");
uint leftBound = 1;
uint rightBound = getSize(self);
uint step = 1;
uint middle = leftBound.add(rightBound).div(2);
uint fromPlaceMove = fromPlace > toPlace ? toPlace : fromPlace;
uint toPlaceMove = fromPlace > toPlace ? fromPlace : toPlace;
while (toPlaceMove <= middle || middle < fromPlaceMove) {
if (middle < fromPlaceMove) {
leftBound = middle.add(1);
step = step.add(step).add(1);
} else {
rightBound = middle;
step = step.add(step);
}
middle = leftBound.add(rightBound).div(2);
}
uint leftBoundMove = leftBound;
uint rightBoundMove = rightBound;
uint stepMove = step;
while(leftBoundMove < rightBoundMove && leftBound < rightBound) {
uint middleMove = leftBoundMove.add(rightBoundMove).div(2);
if (fromPlace > middleMove) {
leftBoundMove = middleMove.add(1);
stepMove = stepMove.add(stepMove).add(1);
} else {
rightBoundMove = middleMove;
stepMove = stepMove.add(stepMove);
}
self.tree[stepMove.sub(1)] = self.tree[stepMove.sub(1)].sub(delta);
middle = leftBound.add(rightBound).div(2);
if (toPlace > middle) {
leftBound = middle.add(1);
step = step.add(step).add(1);
} else {
rightBound = middle;
step = step.add(step);
}
self.tree[step.sub(1)] = self.tree[step.sub(1)].add(delta);
}
}
/**
* @dev Returns random position in range [`place`, size]
* with probability proportional to value stored at this position.
* If all element in range are 0 returns 0
*
* Requirements:
*
* - `place` must be in range [1, size]
*/
function getRandomNonZeroElementFromPlaceToLast(
Tree storage self,
uint place,
Random.RandomGenerator memory randomGenerator
)
external
view
returns (uint)
{
require(_correctPlace(self, place), "Incorrect place");
uint vertex = 1;
uint leftBound = 0;
uint rightBound = getSize(self);
uint currentFrom = place.sub(1);
uint currentSum = sumFromPlaceToLast(self, place);
if (currentSum == 0) {
return 0;
}
while(leftBound.add(1) < rightBound) {
if (_middle(leftBound, rightBound) <= currentFrom) {
vertex = _right(vertex);
leftBound = _middle(leftBound, rightBound);
} else {
uint rightSum = self.tree[_right(vertex).sub(1)];
uint leftSum = currentSum.sub(rightSum);
if (Random.random(randomGenerator, currentSum) < leftSum) {
// go left
vertex = _left(vertex);
rightBound = _middle(leftBound, rightBound);
currentSum = leftSum;
} else {
// go right
vertex = _right(vertex);
leftBound = _middle(leftBound, rightBound);
currentFrom = leftBound;
currentSum = rightSum;
}
}
}
return leftBound.add(1);
}
/**
* @dev Returns sum of elements in range [`place`, size]
*
* Requirements:
*
* - `place` must be in range [1, size]
*/
function sumFromPlaceToLast(Tree storage self, uint place) public view returns (uint sum) {
require(_correctPlace(self, place), "Incorrect place");
if (place == 1) {
return self.tree[0];
}
uint leftBound = 1;
uint rightBound = getSize(self);
uint step = 1;
while(leftBound < rightBound) {
uint middle = leftBound.add(rightBound).div(2);
if (place > middle) {
leftBound = middle.add(1);
step = step.add(step).add(1);
} else {
rightBound = middle;
step = step.add(step);
sum = sum.add(self.tree[step]);
}
}
sum = sum.add(self.tree[step.sub(1)]);
}
/**
* @dev Returns amount of elements in segment tree
*/
function getSize(Tree storage segmentTree) internal view returns (uint) {
if (segmentTree.tree.length > 0) {
return segmentTree.tree.length.div(2).add(1);
} else {
return 0;
}
}
/**
* @dev Checks if `place` is valid position in segment tree
*/
function _correctPlace(Tree storage self, uint place) private view returns (bool) {
return place >= 1 && place <= getSize(self);
}
/**
* @dev Calculates index of left child of the vertex
*/
function _left(uint vertex) private pure returns (uint) {
return vertex.mul(2);
}
/**
* @dev Calculates index of right child of the vertex
*/
function _right(uint vertex) private pure returns (uint) {
return vertex.mul(2).add(1);
}
/**
* @dev Calculates arithmetical mean of 2 numbers
*/
function _middle(uint left, uint right) private pure returns (uint) {
return left.add(right).div(2);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ILocker.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
/**
* @dev Interface of the Locker functions.
*/
interface ILocker {
/**
* @dev Returns and updates the total amount of locked tokens of a given
* `holder`.
*/
function getAndUpdateLockedAmount(address wallet) external returns (uint);
/**
* @dev Returns and updates the total non-transferrable and un-delegatable
* amount of a given `holder`.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint);
}
pragma solidity ^0.6.0;
// ----------------------------------------------------------------------------
// BokkyPooBah's DateTime Library v1.01
//
// A gas-efficient Solidity date and time library
//
// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
//
// Tested date range 1970/01/01 to 2345/12/31
//
// Conventions:
// Unit | Range | Notes
// :-------- |:-------------:|:-----
// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC
// year | 1970 ... 2345 |
// month | 1 ... 12 |
// day | 1 ... 31 |
// hour | 0 ... 23 |
// minute | 0 ... 59 |
// second | 0 ... 59 |
// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday
//
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.
// ----------------------------------------------------------------------------
library BokkyPooBahsDateTimeLibrary {
uint constant SECONDS_PER_DAY = 24 * 60 * 60;
uint constant SECONDS_PER_HOUR = 60 * 60;
uint constant SECONDS_PER_MINUTE = 60;
int constant OFFSET19700101 = 2440588;
uint constant DOW_MON = 1;
uint constant DOW_TUE = 2;
uint constant DOW_WED = 3;
uint constant DOW_THU = 4;
uint constant DOW_FRI = 5;
uint constant DOW_SAT = 6;
uint constant DOW_SUN = 7;
// ------------------------------------------------------------------------
// Calculate the number of days from 1970/01/01 to year/month/day using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and subtracting the offset 2440588 so that 1970/01/01 is day 0
//
// days = day
// - 32075
// + 1461 * (year + 4800 + (month - 14) / 12) / 4
// + 367 * (month - 2 - (month - 14) / 12 * 12) / 12
// - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4
// - offset
// ------------------------------------------------------------------------
function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) {
require(year >= 1970);
int _year = int(year);
int _month = int(month);
int _day = int(day);
int __days = _day
- 32075
+ 1461 * (_year + 4800 + (_month - 14) / 12) / 4
+ 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12
- 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4
- OFFSET19700101;
_days = uint(__days);
}
// ------------------------------------------------------------------------
// Calculate year/month/day from the number of days since 1970/01/01 using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and adding the offset 2440588 so that 1970/01/01 is day 0
//
// int L = days + 68569 + offset
// int N = 4 * L / 146097
// L = L - (146097 * N + 3) / 4
// year = 4000 * (L + 1) / 1461001
// L = L - 1461 * year / 4 + 31
// month = 80 * L / 2447
// dd = L - 2447 * month / 80
// L = month / 11
// month = month + 2 - 12 * L
// year = 100 * (N - 49) + year + L
// ------------------------------------------------------------------------
function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) {
int __days = int(_days);
int L = __days + 68569 + OFFSET19700101;
int N = 4 * L / 146097;
L = L - (146097 * N + 3) / 4;
int _year = 4000 * (L + 1) / 1461001;
L = L - 1461 * _year / 4 + 31;
int _month = 80 * L / 2447;
int _day = L - 2447 * _month / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint(_year);
month = uint(_month);
day = uint(_day);
}
function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY;
}
function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second;
}
function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
secs = secs % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
second = secs % SECONDS_PER_MINUTE;
}
function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) {
if (year >= 1970 && month > 0 && month <= 12) {
uint daysInMonth = _getDaysInMonth(year, month);
if (day > 0 && day <= daysInMonth) {
valid = true;
}
}
}
function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) {
if (isValidDate(year, month, day)) {
if (hour < 24 && minute < 60 && second < 60) {
valid = true;
}
}
}
function isLeapYear(uint timestamp) internal pure returns (bool leapYear) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
leapYear = _isLeapYear(year);
}
function _isLeapYear(uint year) internal pure returns (bool leapYear) {
leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
function isWeekDay(uint timestamp) internal pure returns (bool weekDay) {
weekDay = getDayOfWeek(timestamp) <= DOW_FRI;
}
function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) {
weekEnd = getDayOfWeek(timestamp) >= DOW_SAT;
}
function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
daysInMonth = _getDaysInMonth(year, month);
}
function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
daysInMonth = 31;
} else if (month != 2) {
daysInMonth = 30;
} else {
daysInMonth = _isLeapYear(year) ? 29 : 28;
}
}
// 1 = Monday, 7 = Sunday
function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) {
uint _days = timestamp / SECONDS_PER_DAY;
dayOfWeek = (_days + 3) % 7 + 1;
}
function getYear(uint timestamp) internal pure returns (uint year) {
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getMonth(uint timestamp) internal pure returns (uint month) {
uint year;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getDay(uint timestamp) internal pure returns (uint day) {
uint year;
uint month;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getHour(uint timestamp) internal pure returns (uint hour) {
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
}
function getMinute(uint timestamp) internal pure returns (uint minute) {
uint secs = timestamp % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
}
function getSecond(uint timestamp) internal pure returns (uint second) {
second = timestamp % SECONDS_PER_MINUTE;
}
function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year += _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
month += _months;
year += (month - 1) / 12;
month = (month - 1) % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _days * SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _hours * SECONDS_PER_HOUR;
require(newTimestamp >= timestamp);
}
function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE;
require(newTimestamp >= timestamp);
}
function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _seconds;
require(newTimestamp >= timestamp);
}
function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year -= _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint yearMonth = year * 12 + (month - 1) - _months;
year = yearMonth / 12;
month = yearMonth % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _days * SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _hours * SECONDS_PER_HOUR;
require(newTimestamp <= timestamp);
}
function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE;
require(newTimestamp <= timestamp);
}
function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _seconds;
require(newTimestamp <= timestamp);
}
function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) {
require(fromTimestamp <= toTimestamp);
uint fromYear;
uint fromMonth;
uint fromDay;
uint toYear;
uint toMonth;
uint toDay;
(fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_years = toYear - fromYear;
}
function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) {
require(fromTimestamp <= toTimestamp);
uint fromYear;
uint fromMonth;
uint fromDay;
uint toYear;
uint toMonth;
uint toDay;
(fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;
}
function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) {
require(fromTimestamp <= toTimestamp);
_days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY;
}
function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) {
require(fromTimestamp <= toTimestamp);
_hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR;
}
function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) {
require(fromTimestamp <= toTimestamp);
_minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE;
}
function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) {
require(fromTimestamp <= toTimestamp);
_seconds = toTimestamp - fromTimestamp;
}
} | Allows Admin to enable a validator by adding their ID to the trusted list. Emits a {ValidatorWasEnabled} event. Requirements: - Validator must not already be enabled./ | function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyValidatorManager {
require(!_trustedValidators[validatorId], "Validator is already enabled");
_trustedValidators[validatorId] = true;
trustedValidatorsList.push(validatorId);
emit ValidatorWasEnabled(validatorId);
}
| 6,301,320 |
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
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);
}
library SafeMathUpgradeable {
/**
* @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;
}
}
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 in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* // importANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
library SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// 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;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view 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;
}
contract SettAccessControl is Initializable {
address public governance;
address public strategist;
address public keeper;
// ===== MODIFIERS =====
function _onlyGovernance() internal view {
require(msg.sender == governance, "onlyGovernance");
}
function _onlyGovernanceOrStrategist() internal view {
require(msg.sender == strategist || msg.sender == governance, "onlyGovernanceOrStrategist");
}
function _onlyAuthorizedActors() internal view {
require(msg.sender == keeper || msg.sender == governance, "onlyAuthorizedActors");
}
// ===== PERMISSIONED ACTIONS =====
/// @notice Change strategist address
/// @notice Can only be changed by governance itself
function setStrategist(address _strategist) external {
_onlyGovernance();
strategist = _strategist;
}
/// @notice Change keeper address
/// @notice Can only be changed by governance itself
function setKeeper(address _keeper) external {
_onlyGovernance();
keeper = _keeper;
}
/// @notice Change governance address
/// @notice Can only be changed by governance itself
function setGovernance(address _governance) public {
_onlyGovernance();
governance = _governance;
}
uint256[50] private __gap;
}
library MathUpgradeable {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
interface IController {
function withdraw(address, uint256) external;
function withdrawAll(address) external;
function strategies(address) external view returns (address);
function approvedStrategies(address, address) external view returns (address);
function balanceOf(address) external view returns (uint256);
function earn(address, uint256) external;
function approveStrategy(address, address) external;
function setStrategy(address, address) external;
function setVault(address, address) external;
function want(address) external view returns (address);
function rewards() external view returns (address);
function vaults(address) external view returns (address);
}
interface IStrategy {
function want() external view returns (address);
function deposit() external;
// NOTE: must exclude any tokens used in the yield
// Controller role - withdraw should return to Controller
function withdrawOther(address) external returns (uint256 balance);
// Controller | Vault role - withdraw should always return to Vault
function withdraw(uint256) external;
// Controller | Vault role - withdraw should always return to Vault
function withdrawAll() external returns (uint256);
function balanceOf() external view returns (uint256);
function balanceOfPool() external view returns (uint256);
function balanceOfWant() external view returns (uint256);
function getName() external pure returns (string memory);
function setStrategist(address _strategist) external;
function setWithdrawalFee(uint256 _withdrawalFee) external;
function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external;
function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external;
function setGovernance(address _governance) external;
function setController(address _controller) external;
function controller() external returns (address);
function governance() external returns (address);
function tend() external;
function harvest() external;
}
abstract contract BaseStrategy is PausableUpgradeable, SettAccessControl {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
event Withdraw(uint256 amount);
event WithdrawAll(uint256 balance);
event WithdrawOther(address token, uint256 amount);
event SetStrategist(address strategist);
event SetGovernance(address governance);
event SetController(address controller);
event SetWithdrawalFee(uint256 withdrawalFee);
event SetPerformanceFeeStrategist(uint256 performanceFeeStrategist);
event SetPerformanceFeeGovernance(uint256 performanceFeeGovernance);
event Harvest(uint256 harvested, uint256 indexed blockNumber);
event Tend(uint256 tended);
address public want; // Want: Curve.fi renBTC/wBTC (crvRenWBTC) LP token
uint256 public performanceFeeGovernance;
uint256 public performanceFeeStrategist;
uint256 public withdrawalFee;
uint256 public constant MAX_FEE = 10000;
address public controller;
address public guardian;
uint256 public withdrawalMaxDeviationThreshold;
function __BaseStrategy_init(
address _governance,
address _strategist,
address _controller,
address _keeper,
address _guardian
) public initializer whenNotPaused {
__Pausable_init();
governance = _governance;
strategist = _strategist;
keeper = _keeper;
controller = _controller;
guardian = _guardian;
withdrawalMaxDeviationThreshold = 50;
}
// ===== Modifiers =====
function _onlyController() internal view {
require(msg.sender == controller, "onlyController");
}
function _onlyAuthorizedActorsOrController() internal view {
require(msg.sender == keeper || msg.sender == governance || msg.sender == controller, "onlyAuthorizedActorsOrController");
}
function _onlyAuthorizedPausers() internal view {
require(msg.sender == guardian || msg.sender == governance, "onlyPausers");
}
/// ===== View Functions =====
function baseStrategyVersion() public view returns (string memory) {
return "1.2";
}
/// @notice Get the balance of want held idle in the Strategy
function balanceOfWant() public view returns (uint256) {
return IERC20Upgradeable(want).balanceOf(address(this));
}
/// @notice Get the total balance of want realized in the strategy, whether idle or active in Strategy positions.
function balanceOf() public virtual view returns (uint256) {
return balanceOfWant().add(balanceOfPool());
}
function isTendable() public virtual view returns (bool) {
return false;
}
function isProtectedToken(address token) public view returns (bool) {
address[] memory protectedTokens = getProtectedTokens();
for (uint256 i = 0; i < protectedTokens.length; i++) {
if (token == protectedTokens[i]) {
return true;
}
}
return false;
}
/// ===== Permissioned Actions: Governance =====
function setGuardian(address _guardian) external {
_onlyGovernance();
guardian = _guardian;
}
function setWithdrawalFee(uint256 _withdrawalFee) external {
_onlyGovernance();
require(_withdrawalFee <= MAX_FEE, "base-strategy/excessive-withdrawal-fee");
withdrawalFee = _withdrawalFee;
}
function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external {
_onlyGovernance();
require(_performanceFeeStrategist <= MAX_FEE, "base-strategy/excessive-strategist-performance-fee");
performanceFeeStrategist = _performanceFeeStrategist;
}
function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external {
_onlyGovernance();
require(_performanceFeeGovernance <= MAX_FEE, "base-strategy/excessive-governance-performance-fee");
performanceFeeGovernance = _performanceFeeGovernance;
}
function setController(address _controller) external {
_onlyGovernance();
controller = _controller;
}
function setWithdrawalMaxDeviationThreshold(uint256 _threshold) external {
_onlyGovernance();
require(_threshold <= MAX_FEE, "base-strategy/excessive-max-deviation-threshold");
withdrawalMaxDeviationThreshold = _threshold;
}
function deposit() public virtual whenNotPaused {
_onlyAuthorizedActorsOrController();
uint256 _want = IERC20Upgradeable(want).balanceOf(address(this));
if (_want > 0) {
_deposit(_want);
}
_postDeposit();
}
// ===== Permissioned Actions: Controller =====
/// @notice Controller-only function to Withdraw partial funds, normally used with a vault withdrawal
function withdrawAll() external virtual whenNotPaused returns (uint256 balance) {
_onlyController();
_withdrawAll();
_transferToVault(IERC20Upgradeable(want).balanceOf(address(this)));
}
/// @notice Withdraw partial funds from the strategy, unrolling from strategy positions as necessary
/// @notice Processes withdrawal fee if present
/// @dev If it fails to recover sufficient funds (defined by withdrawalMaxDeviationThreshold), the withdrawal should fail so that this unexpected behavior can be investigated
function withdraw(uint256 _amount) external virtual whenNotPaused {
_onlyController();
// Withdraw from strategy positions, typically taking from any idle want first.
_withdrawSome(_amount);
uint256 _postWithdraw = IERC20Upgradeable(want).balanceOf(address(this));
// Sanity check: Ensure we were able to retrieve sufficent want from strategy positions
// If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold
if (_postWithdraw < _amount) {
uint256 diff = _diff(_amount, _postWithdraw);
// Require that difference between expected and actual values is less than the deviation threshold percentage
require(diff <= _amount.mul(withdrawalMaxDeviationThreshold).div(MAX_FEE), "base-strategy/withdraw-exceed-max-deviation-threshold");
}
// Return the amount actually withdrawn if less than amount requested
uint256 _toWithdraw = MathUpgradeable.min(_postWithdraw, _amount);
// Process withdrawal fee
uint256 _fee = _processWithdrawalFee(_toWithdraw);
// Transfer remaining to Vault to handle withdrawal
_transferToVault(_toWithdraw.sub(_fee));
}
// NOTE: must exclude any tokens used in the yield
// Controller role - withdraw should return to Controller
function withdrawOther(address _asset) external virtual whenNotPaused returns (uint256 balance) {
_onlyController();
_onlyNotProtectedTokens(_asset);
balance = IERC20Upgradeable(_asset).balanceOf(address(this));
IERC20Upgradeable(_asset).safeTransfer(controller, balance);
}
/// ===== Permissioned Actions: Authoized Contract Pausers =====
function pause() external {
_onlyAuthorizedPausers();
_pause();
}
function unpause() external {
_onlyGovernance();
_unpause();
}
/// ===== Internal Helper Functions =====
/// @notice If withdrawal fee is active, take the appropriate amount from the given value and transfer to rewards recipient
/// @return The withdrawal fee that was taken
function _processWithdrawalFee(uint256 _amount) internal returns (uint256) {
if (withdrawalFee == 0) {
return 0;
}
uint256 fee = _amount.mul(withdrawalFee).div(MAX_FEE);
IERC20Upgradeable(want).safeTransfer(IController(controller).rewards(), fee);
return fee;
}
/// @dev Helper function to process an arbitrary fee
/// @dev If the fee is active, transfers a given portion in basis points of the specified value to the recipient
/// @return The fee that was taken
function _processFee(
address token,
uint256 amount,
uint256 feeBps,
address recipient
) internal returns (uint256) {
if (feeBps == 0) {
return 0;
}
uint256 fee = amount.mul(feeBps).div(MAX_FEE);
IERC20Upgradeable(token).safeTransfer(recipient, fee);
return fee;
}
function _transferToVault(uint256 _amount) internal {
address _vault = IController(controller).vaults(address(want));
require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds
IERC20Upgradeable(want).safeTransfer(_vault, _amount);
}
/// @notice Utility function to diff two numbers, expects higher value in first position
function _diff(uint256 a, uint256 b) internal pure returns (uint256) {
require(a >= b, "diff/expected-higher-number-in-first-position");
return a.sub(b);
}
// ===== Abstract Functions: To be implemented by specific Strategies =====
/// @dev Internal deposit logic to be implemented by Stratgies
function _deposit(uint256 _want) internal virtual;
function _postDeposit() internal virtual {
//no-op by default
}
/// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther()
function _onlyNotProtectedTokens(address _asset) internal virtual;
function getProtectedTokens() public virtual view returns (address[] memory) {
return new address[](0);
}
/// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible
function _withdrawAll() internal virtual;
/// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible.
/// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this
function _withdrawSome(uint256 _amount) internal virtual returns (uint256);
/// @dev Realize returns from positions
/// @dev Returns can be reinvested into positions, or distributed in another fashion
/// @dev Performance fees should also be implemented in this function
/// @dev Override function stub is removed as each strategy can have it's own return signature for STATICCALL
// function harvest() external virtual;
/// @dev User-friendly name for this strategy for purposes of convenient reading
function getName() external virtual pure returns (string memory);
/// @dev Balance of want currently held in strategy positions
function balanceOfPool() public virtual view returns (uint256);
uint256[49] private __gap;
}
contract BaseSwapper {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
/// @dev Reset approval and approve exact amount
function _safeApproveHelper(
address token,
address recipient,
uint256 amount
) internal {
IERC20Upgradeable(token).safeApprove(recipient, 0);
IERC20Upgradeable(token).safeApprove(recipient, amount);
}
}
interface IUniswapRouterV2 {
function factory() external view returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
interface IUniswapV2Factory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint256
);
function getPair(address tokenA, address tokenB)
external
view
returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
}
contract UniswapSwapper is BaseSwapper {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
address internal constant uniswap = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap router
address internal constant sushiswap = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // Sushiswap router
function _swapExactTokensForTokens(
address router,
address startToken,
uint256 balance,
address[] memory path
) internal {
_safeApproveHelper(startToken, router, balance);
IUniswapRouterV2(router).swapExactTokensForTokens(balance, 0, path, address(this), now);
}
function _swapExactETHForTokens(
address router,
uint256 balance,
address[] memory path
) internal {
IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}(0, path, address(this), now);
}
function _swapExactTokensForETH(
address router,
address startToken,
uint256 balance,
address[] memory path
) internal {
_safeApproveHelper(startToken, router, balance);
IUniswapRouterV2(router).swapExactTokensForETH(balance, 0, path, address(this), now);
}
function _getPair(
address router,
address token0,
address token1
) internal view returns (address) {
address factory = IUniswapRouterV2(router).factory();
return IUniswapV2Factory(factory).getPair(token0, token1);
}
/// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible
function _addMaxLiquidity(
address router,
address token0,
address token1
) internal {
uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this));
uint256 _token1Balance = IERC20Upgradeable(token1).balanceOf(address(this));
_safeApproveHelper(token0, router, _token0Balance);
_safeApproveHelper(token1, router, _token1Balance);
IUniswapRouterV2(router).addLiquidity(token0, token1, _token0Balance, _token1Balance, 0, 0, address(this), block.timestamp);
}
function _addMaxLiquidityEth(address router, address token0) internal {
uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this));
uint256 _ethBalance = address(this).balance;
_safeApproveHelper(token0, router, _token0Balance);
IUniswapRouterV2(router).addLiquidityETH{value: address(this).balance}(token0, _token0Balance, 0, 0, address(this), block.timestamp);
}
}
interface IUnitVaultParameters {
function tokenDebtLimit(address asset) external view returns (uint256);
}
interface IUnitVault {
function calculateFee(
address asset,
address user,
uint256 amount
) external view returns (uint256);
function getTotalDebt(address asset, address user) external view returns (uint256);
function debts(address asset, address user) external view returns (uint256);
function collaterals(address asset, address user) external view returns (uint256);
function tokenDebts(address asset) external view returns (uint256);
}
interface IUnitCDPManager {
function exit(
address asset,
uint256 assetAmount,
uint256 usdpAmount
) external returns (uint256);
function join(
address asset,
uint256 assetAmount,
uint256 usdpAmount
) external;
function oracleRegistry() external view returns (address);
}
interface IUnitUsdOracle {
// returns Q112-encoded value
// returned value 10**18 * 2**112 is $1
function assetToUsd(address asset, uint256 amount) external view returns (uint256);
}
interface IUnitOracleRegistry {
function oracleByAsset(address asset) external view returns (address);
}
abstract contract StrategyUnitProtocolMeta is BaseStrategy, UniswapSwapper {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
// Unit Protocol module: https://github.com/unitprotocol/core/blob/master/CONTRACTS.md
address public constant cdpMgr01 = 0x0e13ab042eC5AB9Fc6F43979406088B9028F66fA;
address public constant unitVault = 0xb1cFF81b9305166ff1EFc49A129ad2AfCd7BCf19;
address public constant unitVaultParameters = 0xB46F8CF42e504Efe8BEf895f848741daA55e9f1D;
address public constant debtToken = 0x1456688345527bE1f37E9e627DA0837D6f08C925;
address public constant eth_usd = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419;
bool public useUnitUsdOracle = true;
// sub-strategy related constants
address public collateral;
uint256 public collateralDecimal = 1e18;
address public unitOracle;
uint256 public collateralPriceDecimal = 1;
bool public collateralPriceEth = false;
// configurable minimum collateralization percent this strategy would hold for CDP
uint256 public minRatio = 150;
// collateralization percent buffer in CDP debt actions
uint256 public ratioBuff = 200;
uint256 public constant ratioBuffMax = 10000;
// used as dust to avoid closing out a debt repayment
uint256 public dustMinDebt = 10000;
uint256 public constant Q112 = 2**112;
// **** Modifiers **** //
function _onlyCDPInUse() internal view {
uint256 collateralAmt = getCollateralBalance();
require(collateralAmt > 0, "!zeroCollateral");
uint256 debtAmt = getDebtBalance();
require(debtAmt > 0, "!zeroDebt");
}
// **** Getters ****
function getCollateralBalance() public view returns (uint256) {
return IUnitVault(unitVault).collaterals(collateral, address(this));
}
function getDebtBalance() public view returns (uint256) {
return IUnitVault(unitVault).getTotalDebt(collateral, address(this));
}
function getDebtWithoutFee() public view returns (uint256) {
return IUnitVault(unitVault).debts(collateral, address(this));
}
function getDueFee() public view returns (uint256) {
uint256 totalDebt = getDebtBalance();
uint256 borrowed = getDebtWithoutFee();
return totalDebt > borrowed? totalDebt.sub(borrowed) : 0;
}
function debtLimit() public view returns (uint256) {
return IUnitVaultParameters(unitVaultParameters).tokenDebtLimit(collateral);
}
function debtUsed() public view returns (uint256) {
return IUnitVault(unitVault).tokenDebts(collateral);
}
/// @dev Balance of want currently held in strategy positions
function balanceOfPool() public override view returns (uint256) {
return getCollateralBalance();
}
function collateralValue(uint256 collateralAmt) public view returns (uint256) {
uint256 collateralPrice = getLatestCollateralPrice();
return collateralAmt.mul(collateralPrice).mul(1e18).div(collateralDecimal).div(collateralPriceDecimal); // debtToken in 1e18 decimal
}
function currentRatio() public view returns (uint256) {
_onlyCDPInUse();
uint256 collateralAmt = collateralValue(getCollateralBalance()).mul(100);
uint256 debtAmt = getDebtBalance();
return collateralAmt.div(debtAmt);
}
// if borrow is true (for addCollateralAndBorrow): return (maxDebt - currentDebt) if positive value, otherwise return 0
// if borrow is false (for repayAndRedeemCollateral): return (currentDebt - maxDebt) if positive value, otherwise return 0
function calculateDebtFor(uint256 collateralAmt, bool borrow) public view returns (uint256) {
uint256 maxDebt = collateralAmt > 0 ? collateralValue(collateralAmt).mul(ratioBuffMax).div(_getBufferedMinRatio(ratioBuffMax)) : 0;
uint256 debtAmt = getDebtBalance();
uint256 debt = 0;
if (borrow && maxDebt >= debtAmt) {
debt = maxDebt.sub(debtAmt);
} else if (!borrow && debtAmt >= maxDebt) {
debt = debtAmt.sub(maxDebt);
}
return (debt > 0) ? debt : 0;
}
function _getBufferedMinRatio(uint256 _multiplier) internal view returns (uint256) {
require(ratioBuffMax > 0, "!ratioBufferMax");
require(minRatio > 0, "!minRatio");
return minRatio.mul(_multiplier).mul(ratioBuffMax.add(ratioBuff)).div(ratioBuffMax).div(100);
}
function borrowableDebt() public view returns (uint256) {
uint256 collateralAmt = getCollateralBalance();
return calculateDebtFor(collateralAmt, true);
}
function requiredPaidDebt(uint256 _redeemCollateralAmt) public view returns (uint256) {
uint256 totalCollateral = getCollateralBalance();
uint256 collateralAmt = _redeemCollateralAmt >= totalCollateral ? 0 : totalCollateral.sub(_redeemCollateralAmt);
return calculateDebtFor(collateralAmt, false);
}
// **** sub-strategy implementation ****
function _depositUSDP(uint256 _usdpAmt) internal virtual;
function _withdrawUSDP(uint256 _usdpAmt) internal virtual;
// **** Oracle (using chainlink) ****
function getLatestCollateralPrice() public view returns (uint256) {
if (useUnitUsdOracle) {
address unitOracleRegistry = IUnitCDPManager(cdpMgr01).oracleRegistry();
address unitUsdOracle = IUnitOracleRegistry(unitOracleRegistry).oracleByAsset(collateral);
uint256 usdPriceInQ122 = IUnitUsdOracle(unitUsdOracle).assetToUsd(collateral, collateralDecimal);
return uint256(usdPriceInQ122 / Q112).mul(collateralPriceDecimal).div(1e18); // usd price from unit protocol oracle in 1e18 decimal
}
require(unitOracle != address(0), "!_collateralOracle");
(, int256 price, , , ) = IChainlinkAggregator(unitOracle).latestRoundData();
if (price > 0) {
if (collateralPriceEth) {
(, int256 ethPrice, , , ) = IChainlinkAggregator(eth_usd).latestRoundData(); // eth price from chainlink in 1e8 decimal
return uint256(price).mul(collateralPriceDecimal).mul(uint256(ethPrice)).div(1e8).div(collateralPriceEth ? 1e18 : 1);
} else {
return uint256(price).mul(collateralPriceDecimal).div(1e8);
}
} else {
return 0;
}
}
// **** Setters ****
function setMinRatio(uint256 _minRatio) external {
_onlyGovernance();
minRatio = _minRatio;
}
function setRatioBuff(uint256 _ratioBuff) external {
_onlyGovernance();
ratioBuff = _ratioBuff;
}
function setDustMinDebt(uint256 _dustDebt) external {
_onlyGovernance();
dustMinDebt = _dustDebt;
}
function setUseUnitUsdOracle(bool _useUnitUsdOracle) external {
_onlyGovernance();
useUnitUsdOracle = _useUnitUsdOracle;
}
// **** Unit Protocol CDP actions ****
function addCollateralAndBorrow(uint256 _collateralAmt, uint256 _usdpAmt) internal {
require(_usdpAmt.add(debtUsed()) < debtLimit(), "!exceedLimit");
_safeApproveHelper(collateral, unitVault, _collateralAmt);
IUnitCDPManager(cdpMgr01).join(collateral, _collateralAmt, _usdpAmt);
}
function repayAndRedeemCollateral(uint256 _collateralAmt, uint256 _usdpAmt) internal {
_safeApproveHelper(debtToken, unitVault, _usdpAmt);
IUnitCDPManager(cdpMgr01).exit(collateral, _collateralAmt, _usdpAmt);
}
// **** State Mutation functions ****
function keepMinRatio() external {
_onlyCDPInUse();
_onlyAuthorizedActorsOrController();
uint256 requiredPaidback = requiredPaidDebt(0);
if (requiredPaidback > 0) {
_withdrawUSDP(requiredPaidback);
uint256 _currentDebtVal = IERC20Upgradeable(debtToken).balanceOf(address(this));
uint256 _actualPaidDebt = _currentDebtVal;
uint256 _totalDebtWithoutFee = getDebtWithoutFee();
uint256 _fee = getDebtBalance().sub(_totalDebtWithoutFee);
require(_actualPaidDebt > _fee, "!notEnoughForFee");
_actualPaidDebt = _actualPaidDebt.sub(_fee); // unit protocol will charge fee first
_actualPaidDebt = _capMaxDebtPaid(_actualPaidDebt, _totalDebtWithoutFee);
require(_currentDebtVal >= _actualPaidDebt.add(_fee), "!notEnoughRepayment");
repayAndRedeemCollateral(0, _actualPaidDebt);
}
}
/// @dev Internal deposit logic to be implemented by Strategies
function _deposit(uint256 _want) internal override {
if (_want > 0) {
uint256 _newDebt = calculateDebtFor(_want.add(getCollateralBalance()), true);
if (_newDebt > 0) {
addCollateralAndBorrow(_want, _newDebt);
uint256 wad = IERC20Upgradeable(debtToken).balanceOf(address(this));
_depositUSDP(_newDebt > wad ? wad : _newDebt);
}
}
}
// to avoid repay all debt resulting to close the CDP unexpectedly
function _capMaxDebtPaid(uint256 _actualPaidDebt, uint256 _totalDebtWithoutFee) internal view returns (uint256) {
uint256 _maxDebtToRepay = _totalDebtWithoutFee.sub(dustMinDebt);
return _actualPaidDebt >= _maxDebtToRepay ? _maxDebtToRepay : _actualPaidDebt;
}
/// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible.
/// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this
function _withdrawSome(uint256 _amount) internal override returns (uint256) {
if (_amount == 0) {
return _amount;
}
uint256 requiredPaidback = requiredPaidDebt(_amount);
if (requiredPaidback > 0) {
_withdrawUSDP(requiredPaidback);
}
bool _fullWithdraw = _amount >= balanceOfPool();
uint256 _wantBefore = IERC20Upgradeable(want).balanceOf(address(this));
if (!_fullWithdraw) {
uint256 _currentDebtVal = IERC20Upgradeable(debtToken).balanceOf(address(this));
uint256 _actualPaidDebt = _currentDebtVal;
uint256 _totalDebtWithoutFee = getDebtWithoutFee();
uint256 _fee = getDebtBalance().sub(_totalDebtWithoutFee);
require(_actualPaidDebt > _fee, "!notEnoughForFee");
_actualPaidDebt = _actualPaidDebt.sub(_fee); // unit protocol will charge fee first
_actualPaidDebt = _capMaxDebtPaid(_actualPaidDebt, _totalDebtWithoutFee);
require(_currentDebtVal >= _actualPaidDebt.add(_fee), "!notEnoughRepayment");
repayAndRedeemCollateral(_amount, _actualPaidDebt);
} else {
require(IERC20Upgradeable(debtToken).balanceOf(address(this)) >= getDebtBalance(), "!notEnoughFullRepayment");
repayAndRedeemCollateral(_amount, getDebtBalance());
require(getDebtBalance() == 0, "!leftDebt");
require(getCollateralBalance() == 0, "!leftCollateral");
}
uint256 _wantAfter = IERC20Upgradeable(want).balanceOf(address(this));
return _wantAfter.sub(_wantBefore);
}
/// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible
function _withdrawAll() internal override {
_withdrawSome(balanceOfPool());
}
}
interface IChainlinkAggregator {
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
interface IBaseRewardsPool {
//balance
function balanceOf(address _account) external view returns (uint256);
//withdraw to a convex tokenized deposit
function withdraw(uint256 _amount, bool _claim) external returns (bool);
//withdraw directly to curve LP token
function withdrawAndUnwrap(uint256 _amount, bool _claim) external returns (bool);
//claim rewards
function getReward() external returns (bool);
//stake a convex tokenized deposit
function stake(uint256 _amount) external returns (bool);
//stake a convex tokenized deposit for another address(transfering ownership)
function stakeFor(address _account, uint256 _amount) external returns (bool);
function getReward(address _account, bool _claimExtras) external returns (bool);
function rewards(address _account) external view returns (uint256);
function earned(address _account) external view returns (uint256);
function stakingToken() external view returns (address);
}
interface IBooster {
struct PoolInfo {
address lptoken;
address token;
address gauge;
address crvRewards;
address stash;
bool shutdown;
}
function poolInfo(uint256 _pid) external view returns (PoolInfo memory);
function deposit(
uint256 _pid,
uint256 _amount,
bool _stake
) external returns (bool);
function depositAll(uint256 _pid, bool _stake) external returns (bool);
function withdraw(uint256 _pid, uint256 _amount) external returns (bool);
function withdrawAll(uint256 _pid) external returns (bool);
}
interface ICvxMinter {
function reductionPerCliff() external view returns (uint256);
function totalCliffs() external view returns (uint256);
function maxSupply() external view returns (uint256);
}
interface ICurveExchange {
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
function get_dy(
int128,
int128 j,
uint256 dx
) external view returns (uint256);
function calc_token_amount(uint256[2] calldata amounts, bool deposit) external view returns (uint256 amount);
function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external;
function remove_liquidity(uint256 _amount, uint256[2] calldata min_amounts) external;
function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 max_burn_amount) external;
function remove_liquidity_one_coin(
uint256 _token_amounts,
int128 i,
uint256 min_amount
) external;
}
interface ICurveFi {
function get_virtual_price() external view returns (uint256 out);
function add_liquidity(
// renbtc/tbtc pool
uint256[2] calldata amounts,
uint256 min_mint_amount
) external;
function add_liquidity(
// sBTC pool
uint256[3] calldata amounts,
uint256 min_mint_amount
) external;
function add_liquidity(
// bUSD pool
uint256[4] calldata amounts,
uint256 min_mint_amount
) external;
function get_dy(
int128 i,
int128 j,
uint256 dx
) external returns (uint256 out);
function get_dy_underlying(
int128 i,
int128 j,
uint256 dx
) external returns (uint256 out);
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
uint256 deadline
) external;
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy,
uint256 deadline
) external;
function remove_liquidity(
uint256 _amount,
uint256 deadline,
uint256[2] calldata min_amounts
) external;
function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 deadline) external;
function remove_liquidity_imbalance(uint256[3] calldata amounts, uint256 max_burn_amount) external;
function remove_liquidity(uint256 _amount, uint256[3] calldata amounts) external;
function remove_liquidity_imbalance(uint256[4] calldata amounts, uint256 max_burn_amount) external;
function remove_liquidity(uint256 _amount, uint256[4] calldata amounts) external;
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 _min_amount
) external;
function commit_new_parameters(
int128 amplification,
int128 new_fee,
int128 new_admin_fee
) external;
function apply_new_parameters() external;
function revert_new_parameters() external;
function commit_transfer_ownership(address _owner) external;
function apply_transfer_ownership() external;
function revert_transfer_ownership() external;
function withdraw_admin_fees() external;
function coins(int128 arg0) external returns (address out);
function underlying_coins(int128 arg0) external returns (address out);
function balances(int128 arg0) external returns (uint256 out);
function A() external returns (int128 out);
function fee() external returns (int128 out);
function admin_fee() external returns (int128 out);
function owner() external returns (address out);
function admin_actions_deadline() external returns (uint256 out);
function transfer_ownership_deadline() external returns (uint256 out);
function future_A() external returns (int128 out);
function future_fee() external returns (int128 out);
function future_admin_fee() external returns (int128 out);
function future_owner() external returns (address out);
function calc_withdraw_one_coin(uint256 _token_amount, int128 _i) external view returns (uint256 out);
}
interface ICurveGauge {
function deposit(uint256 _value) external;
function deposit(uint256 _value, address addr) external;
function balanceOf(address arg0) external view returns (uint256);
function withdraw(uint256 _value) external;
function withdraw(uint256 _value, bool claim_rewards) external;
function claim_rewards() external;
function claim_rewards(address addr) external;
function claimable_tokens(address addr) external view returns (uint256);
function claimable_reward(address addr) external view returns (uint256);
function integrate_fraction(address arg0) external view returns (uint256);
}
interface ICurveMintr {
function mint(address) external;
function minted(address arg0, address arg1) external view returns (uint256);
}
contract StrategyUnitProtocolRenbtc is StrategyUnitProtocolMeta {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
// strategy specific
address public constant renbtc_collateral = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D;
uint256 public constant renbtc_collateral_decimal = 1e8;
address public constant renbtc_oracle = 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c;
uint256 public constant renbtc_price_decimal = 1;
bool public constant renbtc_price_eth = false;
bool public harvestToRepay = false;
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 public constant weth_decimal = 1e18;
address public constant usdp3crv = 0x7Eb40E450b9655f4B3cC4259BCC731c63ff55ae6;
address public constant usdp = debtToken;
address public constant curvePool = 0x42d7025938bEc20B69cBae5A77421082407f053A;
uint256 public constant usdp_decimal = 1e18;
// yield-farming in usdp-3crv pool & Convex Finance
address public stakingPool = 0xF403C135812408BFbE8713b5A23a04b3D48AAE31;
uint256 public stakingPoolId = 28;
address public constant rewardTokenCRV = 0xD533a949740bb3306d119CC777fa900bA034cd52;
address public constant rewardTokenCVX = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B;
address public rewardPool = 0x24DfFd1949F888F91A0c8341Fc98a3F280a782a8;
// slippage protection for one-sided ape in/out
uint256 public slippageRepayment = 500; // max 5%
uint256 public slippageProtectionIn = 50; // max 0.5%
uint256 public slippageProtectionOut = 50; // max 0.5%
uint256 public keepCRV;
uint256 public keepCVX;
event RenBTCStratHarvest(
uint256 crvHarvested,
uint256 cvxHarvested,
uint256 usdpRepaid,
uint256 wantProcessed,
uint256 governancePerformanceFee,
uint256 strategistPerformanceFee
);
struct HarvestData {
uint256 crvHarvested;
uint256 cvxHarvested;
uint256 usdpRepaid;
uint256 wantProcessed;
uint256 governancePerformanceFee;
uint256 strategistPerformanceFee;
}
//
// feeConfig: governance/strategist/withdrawal/keepCRV
//
function initialize(
address _governance,
address _strategist,
address _controller,
address _keeper,
address _guardian,
address[1] memory _wantConfig,
uint256[4] memory _feeConfig
) public initializer {
__BaseStrategy_init(_governance, _strategist, _controller, _keeper, _guardian);
require(_wantConfig[0] == renbtc_collateral, "!want");
want = _wantConfig[0];
collateral = renbtc_collateral;
collateralDecimal = renbtc_collateral_decimal;
unitOracle = renbtc_oracle;
collateralPriceDecimal = renbtc_price_decimal;
collateralPriceEth = renbtc_price_eth;
performanceFeeGovernance = _feeConfig[0];
performanceFeeStrategist = _feeConfig[1];
withdrawalFee = _feeConfig[2];
keepCRV = _feeConfig[3];
keepCVX = keepCRV;
// avoid empty value after clones
minRatio = 150;
ratioBuff = 200;
useUnitUsdOracle = true;
dustMinDebt = 10000;
slippageRepayment = 500;
slippageProtectionIn = 50;
slippageProtectionOut = 50;
stakingPoolId = 28;
}
// **** Setters ****
function setSlippageRepayment(uint256 _repaymentSlippage) public{
_onlyGovernance();
require(_repaymentSlippage < MAX_FEE && _repaymentSlippage > 0, "!_repaymentSlippage");
slippageRepayment = _repaymentSlippage;
}
function setStakingPoolId(uint256 _poolId) public{
_onlyGovernance();
stakingPoolId = _poolId;
}
function setStakingPool(address _pool) public{
_onlyGovernance();
stakingPool = _pool;
}
function setRewardPool(address _pool) public{
_onlyGovernance();
rewardPool = _pool;
}
function setSlippageProtectionIn(uint256 _slippage) external {
_onlyGovernance();
require(_slippage < MAX_FEE && _slippage > 0, "!_slippageProtectionIn");
slippageProtectionIn = _slippage;
}
function setSlippageProtectionOut(uint256 _slippage) external {
_onlyGovernance();
require(_slippage < MAX_FEE && _slippage > 0, "!_slippageProtectionOut");
slippageProtectionOut = _slippage;
}
function setKeepCRV(uint256 _keepCRV) external {
_onlyGovernance();
keepCRV = _keepCRV;
}
function setKeepCVX(uint256 _keepCVX) external {
_onlyGovernance();
keepCVX = _keepCVX;
}
function setHarvestToRepay(bool _repay) public{
_onlyGovernance();
harvestToRepay = _repay;
}
// **** State Mutation functions ****
function harvest() external whenNotPaused returns (HarvestData memory) {
_onlyAuthorizedActors();
HarvestData memory harvestData;
(uint256 _crvRecycled, uint256 _cvxRecycled) = _collectStakingRewards(harvestData);
// Convert CRV & CVX Rewards to WETH
_convertRewards();
// Repay borrowed debt
uint256 _wethAmount = IERC20Upgradeable(weth).balanceOf(address(this));
if (_wethAmount > 0){
harvestData.usdpRepaid = _repayDebt(_wethAmount);
}
// Convert WETH to Want for reinvestement
_wethAmount = IERC20Upgradeable(weth).balanceOf(address(this));
if (_wethAmount > 0 && !harvestToRepay) {
address[] memory path = new address[](2);
path[0] = weth;
path[1] = want;
_swapExactTokensForTokens(uniswap, weth, _wethAmount, path);
}
// Take fees from want increase, and deposit remaining
harvestData.wantProcessed = IERC20Upgradeable(want).balanceOf(address(this));
uint256 _wantDeposited;
if (harvestData.wantProcessed > 0 && !harvestToRepay) {
(harvestData.governancePerformanceFee, harvestData.strategistPerformanceFee) = _processPerformanceFees(harvestData.wantProcessed);
// Reinvest remaining want
_wantDeposited = IERC20Upgradeable(want).balanceOf(address(this));
if (_wantDeposited > 0) {
_deposit(_wantDeposited);
}
}
emit RenBTCStratHarvest(harvestData.crvHarvested, harvestData.cvxHarvested, harvestData.usdpRepaid, harvestData.wantProcessed, harvestData.governancePerformanceFee, harvestData.strategistPerformanceFee);
emit Harvest(_wantDeposited, block.number);
return harvestData;
}
function _collectStakingRewards(HarvestData memory harvestData) internal returns(uint256, uint256){
uint256 _before = IERC20Upgradeable(want).balanceOf(address(this));
uint256 _beforeCrv = IERC20Upgradeable(rewardTokenCRV).balanceOf(address(this));
uint256 _beforeCvx = IERC20Upgradeable(rewardTokenCVX).balanceOf(address(this));
// Harvest from Convex Finance
IBaseRewardsPool(rewardPool).getReward(address(this), true);
uint256 _afterCrv = IERC20Upgradeable(rewardTokenCRV).balanceOf(address(this));
uint256 _afterCvx = IERC20Upgradeable(rewardTokenCVX).balanceOf(address(this));
harvestData.crvHarvested = _afterCrv.sub(_beforeCrv);
harvestData.cvxHarvested = _afterCvx.sub(_beforeCvx);
uint256 _crv = _afterCrv;
uint256 _cvx = _afterCvx;
// Transfer CRV & CVX token to Rewards wallet as configured
uint256 _keepCrv = _crv.mul(keepCRV).div(MAX_FEE);
uint256 _keepCvx = _cvx.mul(keepCVX).div(MAX_FEE);
IERC20Upgradeable(rewardTokenCRV).safeTransfer(IController(controller).rewards(), _keepCrv);
IERC20Upgradeable(rewardTokenCVX).safeTransfer(IController(controller).rewards(), _keepCvx);
uint256 _crvRecycled = _crv.sub(_keepCrv);
uint256 _cvxRecycled = _cvx.sub(_keepCvx);
return (_crvRecycled, _cvxRecycled);
}
function _repayDebt(uint256 _wethAmount) internal returns(uint256) {
uint256 _repaidDebt;
if (harvestToRepay){
// Repay debt ONLY to skip reinvest in case of strategy migration period
_repaidDebt = _swapRewardsToDebt(_wethAmount);
} else {
// Repay debt first
uint256 dueFee = getDueFee();
if (dueFee > 0){
uint256 _swapIn = calcETHSwappedForFeeRepayment(dueFee, _wethAmount);
_repaidDebt = _swapRewardsToDebt(_swapIn);
require(IERC20Upgradeable(debtToken).balanceOf(address(this)) >= dueFee, '!notEnoughRepaymentDuringHarvest');
uint256 debtTotalBefore = getDebtBalance();
repayAndRedeemCollateral(0, dueFee);
require(getDebtBalance() < debtTotalBefore, '!repayDebtDuringHarvest');
}
}
return _repaidDebt;
}
function _convertRewards() internal {
uint256 _rewardCRV = IERC20Upgradeable(rewardTokenCRV).balanceOf(address(this));
uint256 _rewardCVX = IERC20Upgradeable(rewardTokenCVX).balanceOf(address(this));
if (_rewardCRV > 0) {
address[] memory _swapPath = new address[](2);
_swapPath[0] = rewardTokenCRV;
_swapPath[1] = weth;
_swapExactTokensForTokens(sushiswap, rewardTokenCRV, _rewardCRV, _swapPath);
}
if (_rewardCVX > 0) {
address[] memory _swapPath = new address[](2);
_swapPath[0] = rewardTokenCVX;
_swapPath[1] = weth;
_swapExactTokensForTokens(sushiswap, rewardTokenCVX, _rewardCVX, _swapPath);
}
}
function _swapRewardsToDebt(uint256 _swapIn) internal returns (uint256){
address[] memory _swapPath = new address[](2);
_swapPath[0] = weth;
_swapPath[1] = debtToken;
uint256 _beforeDebt = IERC20Upgradeable(debtToken).balanceOf(address(this));
_swapExactTokensForTokens(sushiswap, weth, _swapIn, _swapPath);
return IERC20Upgradeable(debtToken).balanceOf(address(this)).sub(_beforeDebt);
}
function calcETHSwappedForFeeRepayment(uint256 _dueFee, uint256 _toSwappedETHBal) public view returns (uint256){
(,int ethPrice,,,) = IChainlinkAggregator(eth_usd).latestRoundData();// eth price from chainlink in 1e8 decimal
uint256 toSwapped = _dueFee.mul(weth_decimal).div(usdp_decimal).mul(1e8).div(uint256(ethPrice));
uint256 _swapIn = toSwapped.mul(MAX_FEE.add(slippageRepayment)).div(MAX_FEE);
return _swapIn > _toSwappedETHBal ? _toSwappedETHBal : _swapIn;
}
function _processPerformanceFees(uint256 _amount) internal returns (uint256 governancePerformanceFee, uint256 strategistPerformanceFee) {
governancePerformanceFee = _processFee(want, _amount, performanceFeeGovernance, IController(controller).rewards());
strategistPerformanceFee = _processFee(want, _amount, performanceFeeStrategist, strategist);
}
function estimateMinCrvLPFromDeposit(uint256 _usdpAmt) public view returns(uint256){
uint256 _expectedOut = estimateRequiredUsdp3crv(_usdpAmt);
_expectedOut = _expectedOut.mul(MAX_FEE.sub(slippageProtectionIn)).div(MAX_FEE);
return _expectedOut;
}
function _depositUSDP(uint256 _usdpAmt) internal override {
uint256 _maxSlip = estimateMinCrvLPFromDeposit(_usdpAmt);
if (_usdpAmt > 0 && checkSlip(_usdpAmt, _maxSlip)) {
_safeApproveHelper(debtToken, curvePool, _usdpAmt);
uint256[2] memory amounts = [_usdpAmt, 0];
ICurveFi(curvePool).add_liquidity(amounts, _maxSlip);
}
uint256 _usdp3crv = IERC20Upgradeable(usdp3crv).balanceOf(address(this));
if (_usdp3crv > 0) {
_safeApproveHelper(usdp3crv, stakingPool, _usdp3crv);
IBooster(stakingPool).depositAll(stakingPoolId, true);
}
}
function _withdrawUSDP(uint256 _usdpAmt) internal override {
uint256 _requiredUsdp3crv = estimateRequiredUsdp3crv(_usdpAmt);
_requiredUsdp3crv = _requiredUsdp3crv.mul(MAX_FEE.add(slippageProtectionOut)).div(MAX_FEE); // try to remove bit more
uint256 _usdp3crv = IERC20Upgradeable(usdp3crv).balanceOf(address(this));
uint256 _withdrawFromStaking = _usdp3crv < _requiredUsdp3crv ? _requiredUsdp3crv.sub(_usdp3crv) : 0;
if (_withdrawFromStaking > 0) {
uint256 maxInStaking = IBaseRewardsPool(rewardPool).balanceOf(address(this));
uint256 _toWithdraw = maxInStaking < _withdrawFromStaking ? maxInStaking : _withdrawFromStaking;
IBaseRewardsPool(rewardPool).withdrawAndUnwrap(_toWithdraw, false);
}
_usdp3crv = IERC20Upgradeable(usdp3crv).balanceOf(address(this));
if (_usdp3crv > 0) {
_requiredUsdp3crv = _requiredUsdp3crv > _usdp3crv ? _usdp3crv : _requiredUsdp3crv;
uint256 maxSlippage = _requiredUsdp3crv.mul(MAX_FEE.sub(slippageProtectionOut)).div(MAX_FEE);
_safeApproveHelper(usdp3crv, curvePool, _requiredUsdp3crv);
ICurveFi(curvePool).remove_liquidity_one_coin(_requiredUsdp3crv, 0, maxSlippage);
}
}
// **** Views ****
function virtualPriceToWant() public view returns (uint256) {
return ICurveFi(curvePool).get_virtual_price();
}
function estimateRequiredUsdp3crv(uint256 _usdpAmt) public view returns (uint256) {
return _usdpAmt.mul(1e18).div(virtualPriceToWant());
}
function checkSlip(uint256 _usdpAmt, uint256 _maxSlip) public view returns (bool) {
uint256[2] memory amounts = [_usdpAmt, 0];
return ICurveExchange(curvePool).calc_token_amount(amounts, true) >= _maxSlip;
}
function balanceOfCrvLPToken() public view returns (uint256){
uint256 lpAmt = IBaseRewardsPool(rewardPool).balanceOf(address(this));
return lpAmt.add(IERC20Upgradeable(usdp3crv).balanceOf(address(this)));
}
function usdpOfPool() public view returns (uint256){
uint256 lpAmt = balanceOfCrvLPToken();
return usdp3crvToUsdp(lpAmt);
}
function usdp3crvToUsdp(uint256 _usdp3crv) public view returns (uint256) {
if (_usdp3crv == 0) {
return 0;
}
return virtualPriceToWant().mul(_usdp3crv).div(1e18);
}
/// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther()
function _onlyNotProtectedTokens(address _asset) internal override {
require(usdp3crv != _asset, "!usdp3crv");
require(debtToken != _asset, "!usdp");
require(renbtc_collateral != _asset, "!renbtc");
}
function getProtectedTokens() public override view returns (address[] memory) {
address[] memory protectedTokens = new address[](3);
protectedTokens[0] = renbtc_collateral;
protectedTokens[1] = debtToken;
protectedTokens[2] = usdp3crv;
return protectedTokens;
}
/// @dev User-friendly name for this strategy for purposes of convenient reading
function getName() external override pure returns (string memory) {
return "StrategyUnitProtocolRenbtc";
}
// only include CRV earned
function getHarvestable() public view returns (uint256) {
return IBaseRewardsPool(rewardPool).earned(address(this));
}
// https://etherscan.io/address/0x4e3fbd56cd56c3e72c1403e103b45db9da5b9d2b#code#L1091
function mintableCVX(uint256 _amount) public view returns (uint256) {
uint256 _toMint = 0;
uint256 supply = IERC20Upgradeable(rewardTokenCVX).totalSupply();
uint256 cliff = supply.div(ICvxMinter(rewardTokenCVX).reductionPerCliff());
uint256 totalCliffs = ICvxMinter(rewardTokenCVX).totalCliffs();
if (cliff < totalCliffs){
uint256 reduction = totalCliffs.sub(cliff);
_amount = _amount.mul(reduction).div(totalCliffs);
uint256 amtTillMax = ICvxMinter(rewardTokenCVX).maxSupply().sub(supply);
if (_amount > amtTillMax){
_amount = amtTillMax;
}
_toMint = _amount;
}
return _toMint;
}
function getHarvestableCVX() public view returns (uint256) {
uint256 _crvEarned = getHarvestable();
return mintableCVX(_crvEarned);
}
} | balancewithdraw to a convex tokenized depositwithdraw directly to curve LP tokenclaim rewardsstake a convex tokenized depositstake a convex tokenized deposit for another address(transfering ownership) | interface IBaseRewardsPool {
function balanceOf(address _account) external view returns (uint256);
function withdraw(uint256 _amount, bool _claim) external returns (bool);
function withdrawAndUnwrap(uint256 _amount, bool _claim) external returns (bool);
function getReward() external returns (bool);
function stake(uint256 _amount) external returns (bool);
function stakeFor(address _account, uint256 _amount) external returns (bool);
function getReward(address _account, bool _claimExtras) external returns (bool);
function rewards(address _account) external view returns (uint256);
function earned(address _account) external view returns (uint256);
function stakingToken() external view returns (address);
}
| 1,553,305 |
//Address: 0xab37d7c4a2ae9ad4451aa796171dc8ac0fa429f4
//Contract name: IcoToken
//Balance: 0 Ether
//Verification Date: 2/2/2018
//Transacion Count: 95
// CODE STARTS HERE
//File: node_modules/zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
pragma solidity ^0.4.18;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
//File: node_modules/zeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.4.18;
/**
* @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;
}
}
//File: node_modules/zeppelin-solidity/contracts/token/ERC20/BasicToken.sol
pragma solidity ^0.4.18;
/**
* @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]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
//File: node_modules/zeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.4.18;
/**
* @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: node_modules/zeppelin-solidity/contracts/token/ERC20/StandardToken.sol
pragma solidity ^0.4.18;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_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);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public 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, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
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, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
//File: node_modules/zeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.4.18;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
//File: node_modules/zeppelin-solidity/contracts/token/ERC20/MintableToken.sol
pragma solidity ^0.4.18;
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(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;
MintFinished();
return true;
}
}
//File: node_modules/zeppelin-solidity/contracts/crowdsale/Crowdsale.sol
pragma solidity ^0.4.18;
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
MintableToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// how many token units a buyer gets per wei
uint256 public rate;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != address(0));
token = createTokenContract();
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
}
// fallback function can be used to buy tokens
function () external payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return now > endTime;
}
// creates the token to be sold.
// override this method to have crowdsale of a specific mintable token.
function createTokenContract() internal returns (MintableToken) {
return new MintableToken();
}
// Override this method to have a way to add business logic to your crowdsale when buying
function getTokenAmount(uint256 weiAmount) internal view returns(uint256) {
return weiAmount.mul(rate);
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
}
//File: node_modules/zeppelin-solidity/contracts/lifecycle/Pausable.sol
pragma solidity ^0.4.18;
/**
* @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;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
//File: node_modules/zeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.4.18;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
//File: node_modules/zeppelin-solidity/contracts/token/ERC20/TokenVesting.sol
pragma solidity ^0.4.18;
/**
* @title TokenVesting
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
*/
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
event Revoked();
// beneficiary of tokens after they are released
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* _beneficiary, gradually in a linear fashion until _start + _duration. By then all
* of the balance will have vested.
* @param _beneficiary address of the beneficiary to whom vested tokens are transferred
* @param _cliff duration in seconds of the cliff in which tokens will begin to vest
* @param _duration duration in seconds of the period in which the tokens will vest
* @param _revocable whether the vesting is revocable or not
*/
function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.safeTransfer(beneficiary, unreleased);
Released(unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(owner, refund);
Revoked();
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
/**
* @dev Calculates the amount that has already vested.
* @param token ERC20 token which is being vested
*/
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (now < cliff) {
return 0;
} else if (now >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(now.sub(start)).div(duration);
}
}
}
//File: node_modules/zeppelin-solidity/contracts/token/ERC20/PausableToken.sol
pragma solidity ^0.4.18;
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
//File: src/contracts/ico/DividendToken.sol
/**
* @title Dividend contract
*
* @version 1.0
* @author Validity Labs AG <[email protected]>
*/
pragma solidity ^0.4.18;
contract DividendToken is StandardToken, Ownable {
using SafeMath for uint256;
// time before dividendEndTime during which dividend cannot be claimed by token holders
// instead the unclaimed dividend can be claimed by treasury in that time span
uint256 public claimTimeout = 20 days;
uint256 public dividendCycleTime = 350 days;
uint256 public currentDividend;
mapping(address => uint256) unclaimedDividend;
// tracks when the dividend balance has been updated last time
mapping(address => uint256) public lastUpdate;
uint256 public lastDividendIncreaseDate;
// allow payment of dividend only by special treasury account (treasury can be set and altered by owner,
// multiple treasurer accounts are possible
mapping(address => bool) public isTreasurer;
uint256 public dividendEndTime = 0;
event Payin(address _owner, uint256 _value, uint256 _endTime);
event Payout(address _tokenHolder, uint256 _value);
event Reclaimed(uint256 remainingBalance, uint256 _endTime, uint256 _now);
event ChangedTreasurer(address treasurer, bool active);
/**
* @dev Deploy the DividendToken contract and set the owner of the contract
*/
function DividendToken() public {
isTreasurer[owner] = true;
}
/**
* @dev Request payout dividend (claim) (requested by tokenHolder -> pull)
* dividends that have not been claimed within 330 days expire and cannot be claimed anymore by the token holder.
*/
function claimDividend() public returns (bool) {
// unclaimed dividend fractions should expire after 330 days and the owner can reclaim that fraction
require(dividendEndTime > 0 && dividendEndTime.sub(claimTimeout) > now);
updateDividend(msg.sender);
uint256 payment = unclaimedDividend[msg.sender];
unclaimedDividend[msg.sender] = 0;
msg.sender.transfer(payment);
// Trigger payout event
Payout(msg.sender, payment);
return true;
}
/**
* @dev Transfer dividend (fraction) to new token holder
* @param _from address The address of the old token holder
* @param _to address The address of the new token holder
* @param _value uint256 Number of tokens to transfer
*/
function transferDividend(address _from, address _to, uint256 _value) internal {
updateDividend(_from);
updateDividend(_to);
uint256 transAmount = unclaimedDividend[_from].mul(_value).div(balanceOf(_from));
unclaimedDividend[_from] = unclaimedDividend[_from].sub(transAmount);
unclaimedDividend[_to] = unclaimedDividend[_to].add(transAmount);
}
/**
* @dev Update the dividend of hodler
* @param _hodler address The Address of the hodler
*/
function updateDividend(address _hodler) internal {
// last update in previous period -> reset claimable dividend
if (lastUpdate[_hodler] < lastDividendIncreaseDate) {
unclaimedDividend[_hodler] = calcDividend(_hodler, totalSupply_);
lastUpdate[_hodler] = now;
}
}
/**
* @dev Get claimable dividend for the hodler
* @param _hodler address The Address of the hodler
*/
function getClaimableDividend(address _hodler) public constant returns (uint256 claimableDividend) {
if (lastUpdate[_hodler] < lastDividendIncreaseDate) {
return calcDividend(_hodler, totalSupply_);
} else {
return (unclaimedDividend[_hodler]);
}
}
/**
* @dev Overrides transfer method from BasicToken
* transfer token for 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) {
transferDividend(msg.sender, _to, _value);
// Return from inherited transfer method
return super.transfer(_to, _value);
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
// Prevent dividend to be claimed twice
transferDividend(_from, _to, _value);
// Return from inherited transferFrom method
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Set / alter treasurer "account". This can be done from owner only
* @param _treasurer address Address of the treasurer to create/alter
* @param _active bool Flag that shows if the treasurer account is active
*/
function setTreasurer(address _treasurer, bool _active) public onlyOwner {
isTreasurer[_treasurer] = _active;
ChangedTreasurer(_treasurer, _active);
}
/**
* @dev Request unclaimed ETH, payback to beneficiary (owner) wallet
* dividend payment is possible every 330 days at the earliest - can be later, this allows for some flexibility,
* e.g. board meeting had to happen a bit earlier this year than previous year.
*/
function requestUnclaimed() public onlyOwner {
// Send remaining ETH to beneficiary (back to owner) if dividend round is over
require(now >= dividendEndTime.sub(claimTimeout));
msg.sender.transfer(this.balance);
Reclaimed(this.balance, dividendEndTime, now);
}
/**
* @dev ETH Payin for Treasurer
* Only owner or treasurer can do a payin for all token holder.
* Owner / treasurer can also increase dividend by calling fallback function multiple times.
*/
function() public payable {
require(isTreasurer[msg.sender]);
require(dividendEndTime < now);
// pay back unclaimed dividend that might not have been claimed by owner yet
if (this.balance > msg.value) {
uint256 payout = this.balance.sub(msg.value);
owner.transfer(payout);
Reclaimed(payout, dividendEndTime, now);
}
currentDividend = this.balance;
// No active dividend cycle found, initialize new round
dividendEndTime = now.add(dividendCycleTime);
// Trigger payin event
Payin(msg.sender, msg.value, dividendEndTime);
lastDividendIncreaseDate = now;
}
/**
* @dev calculate the dividend
* @param _hodler address
* @param _totalSupply uint256
*/
function calcDividend(address _hodler, uint256 _totalSupply) public view returns(uint256) {
return (currentDividend.mul(balanceOf(_hodler))).div(_totalSupply);
}
}
//File: src/contracts/ico/IcoToken.sol
/**
* @title ICO token
* @version 1.0
* @author Validity Labs AG <[email protected]>
*/
pragma solidity ^0.4.18;
contract IcoToken is MintableToken, PausableToken, DividendToken {
string public constant name = "Tend Token";
string public constant symbol = "TND";
uint8 public constant decimals = 18;
/**
* @dev Constructor of IcoToken that instantiate a new DividendToken
*/
function IcoToken() public DividendToken() {
// token should not be transferrable until after all tokens have been issued
paused = true;
}
}
//File: src/contracts/ico/IcoCrowdsale.sol
/**
* @title IcoCrowdsale
* Simple time and capped based crowdsale.
*
* @version 1.0
* @author Validity Labs AG <[email protected]>
*/
pragma solidity ^0.4.18;
contract IcoCrowdsale is Crowdsale, Ownable {
/*** CONSTANTS ***/
// Different levels of caps per allotment
uint256 public constant MAX_TOKEN_CAP = 13e6 * 1e18; // 13 million * 1e18
// // Bottom three should add to above
uint256 public constant ICO_ENABLERS_CAP = 15e5 * 1e18; // 1.5 million * 1e18
uint256 public constant DEVELOPMENT_TEAM_CAP = 2e6 * 1e18; // 2 million * 1e18
uint256 public constant ICO_TOKEN_CAP = 9.5e6 * 1e18; // 9.5 million * 1e18
uint256 public constant CHF_CENT_PER_TOKEN = 1000; // standard CHF per token rate - in cents - 10 CHF => 1000 CHF cents
uint256 public constant MIN_CONTRIBUTION_CHF = 250;
uint256 public constant VESTING_CLIFF = 1 years;
uint256 public constant VESTING_DURATION = 3 years;
// Amount of discounted tokens per discount stage (2 stages total; each being the same amount)
uint256 public constant DISCOUNT_TOKEN_AMOUNT_T1 = 3e6 * 1e18; // 3 million * 1e18
uint256 public constant DISCOUNT_TOKEN_AMOUNT_T2 = DISCOUNT_TOKEN_AMOUNT_T1 * 2;
// Track tokens depending which stage that the ICO is in
uint256 public tokensToMint; // tokens to be minted after confirmation
uint256 public tokensMinted; // already minted tokens (maximally = cap)
uint256 public icoEnablersTokensMinted;
uint256 public developmentTeamTokensMinted;
uint256 public minContributionInWei;
uint256 public tokenPerWei;
uint256 public totalTokensPurchased;
bool public capReached;
bool public tier1Reached;
bool public tier2Reached;
address public underwriter;
// allow managers to blacklist and confirm contributions by manager accounts
// (managers can be set and altered by owner, multiple manager accounts are possible
mapping(address => bool) public isManager;
// true if addess is not allowed to invest
mapping(address => bool) public isBlacklisted;
uint256 public confirmationPeriod;
bool public confirmationPeriodOver; // can be set by owner to finish confirmation in under 30 days
// for convenience we store vesting wallets
address[] public vestingWallets;
uint256 public investmentIdLastAttemptedToSettle;
struct Payment {
address investor;
address beneficiary;
uint256 weiAmount;
uint256 tokenAmount;
bool confirmed;
bool attemptedSettlement;
bool completedSettlement;
}
Payment[] public investments;
/*** EVENTS ***/
event ChangedInvestorBlacklisting(address investor, bool blacklisted);
event ChangedManager(address manager, bool active);
event ChangedInvestmentConfirmation(uint256 investmentId, address investor, bool confirmed);
/*** MODIFIERS ***/
modifier onlyUnderwriter() {
require(msg.sender == underwriter);
_;
}
modifier onlyManager() {
require(isManager[msg.sender]);
_;
}
modifier onlyNoneZero(address _to, uint256 _amount) {
require(_to != address(0));
require(_amount > 0);
_;
}
modifier onlyConfirmPayment() {
require(now > endTime && now <= endTime.add(confirmationPeriod));
require(!confirmationPeriodOver);
_;
}
modifier onlyConfirmationOver() {
require(confirmationPeriodOver || now > endTime.add(confirmationPeriod));
_;
}
/**
* @dev Deploy capped ico crowdsale contract
* @param _startTime uint256 Start time of the crowdsale
* @param _endTime uint256 End time of the crowdsale
* @param _rateChfPerEth uint256 CHF per ETH rate
* @param _wallet address Wallet address of the crowdsale
* @param _confirmationPeriodDays uint256 Confirmation period in days
* @param _underwriter address of the underwriter
*/
function IcoCrowdsale(
uint256 _startTime,
uint256 _endTime,
uint256 _rateChfPerEth,
address _wallet,
uint256 _confirmationPeriodDays,
address _underwriter
)
public
Crowdsale(_startTime, _endTime, _rateChfPerEth, _wallet)
{
require(MAX_TOKEN_CAP == ICO_ENABLERS_CAP.add(ICO_TOKEN_CAP).add(DEVELOPMENT_TEAM_CAP));
require(_underwriter != address(0));
setManager(msg.sender, true);
tokenPerWei = (_rateChfPerEth.mul(1e2)).div(CHF_CENT_PER_TOKEN);
minContributionInWei = (MIN_CONTRIBUTION_CHF.mul(1e18)).div(_rateChfPerEth);
confirmationPeriod = _confirmationPeriodDays * 1 days;
underwriter = _underwriter;
}
/**
* @dev Set / alter manager / blacklister account. This can be done from owner only
* @param _manager address address of the manager to create/alter
* @param _active bool flag that shows if the manager account is active
*/
function setManager(address _manager, bool _active) public onlyOwner {
isManager[_manager] = _active;
ChangedManager(_manager, _active);
}
/**
* @dev blacklist investor from participating in the crowdsale
* @param _investor address address of the investor to disallowed participation
*/
function blackListInvestor(address _investor, bool _active) public onlyManager {
isBlacklisted[_investor] = _active;
ChangedInvestorBlacklisting(_investor, _active);
}
/**
* @dev override (not extend! because we only issues tokens after final KYC confirm phase)
* core functionality by blacklist check and registration of payment
* @param _beneficiary address address of the beneficiary to receive tokens after they have been confirmed
*/
function buyTokens(address _beneficiary) public payable {
require(_beneficiary != address(0));
require(validPurchase());
require(!isBlacklisted[msg.sender]);
uint256 weiAmount = msg.value;
uint256 tokenAmount;
uint256 purchasedTokens = weiAmount.mul(tokenPerWei);
uint256 tempTotalTokensPurchased = totalTokensPurchased.add(purchasedTokens);
uint256 overflowTokens;
uint256 overflowTokens2;
// 20% discount bonus amount
uint256 tier1BonusTokens;
// 10% discount bonus amount
uint256 tier2BonusTokens;
// tier 1 20% discount - 1st 3 million tokens purchased
if (!tier1Reached) {
// tx tokens overflowed into next tier 2 - 10% discount - mark tier1Reached! else all tokens are tier 1 discounted
if (tempTotalTokensPurchased > DISCOUNT_TOKEN_AMOUNT_T1) {
tier1Reached = true;
overflowTokens = tempTotalTokensPurchased.sub(DISCOUNT_TOKEN_AMOUNT_T1);
tier1BonusTokens = purchasedTokens.sub(overflowTokens);
// tx tokens did not overflow into next tier 2 (10% discount)
} else {
tier1BonusTokens = purchasedTokens;
}
//apply discount
tier1BonusTokens = tier1BonusTokens.mul(10).div(8);
tokenAmount = tokenAmount.add(tier1BonusTokens);
}
// tier 2 10% discount - 2nd 3 million tokens purchased
if (tier1Reached && !tier2Reached) {
// tx tokens overflowed into next tier 3 - 0% - marked tier2Reached! else all tokens are tier 2 discounted
if (tempTotalTokensPurchased > DISCOUNT_TOKEN_AMOUNT_T2) {
tier2Reached = true;
overflowTokens2 = tempTotalTokensPurchased.sub(DISCOUNT_TOKEN_AMOUNT_T2);
tier2BonusTokens = purchasedTokens.sub(overflowTokens2);
// tx tokens did not overflow into next tier 3 (tier 3 == no discount)
} else {
// tokens overflowed from tier1 else this tx started in tier2
if (overflowTokens > 0) {
tier2BonusTokens = overflowTokens;
} else {
tier2BonusTokens = purchasedTokens;
}
}
// apply discount for tier 2 tokens
tier2BonusTokens = tier2BonusTokens.mul(10).div(9);
tokenAmount = tokenAmount.add(tier2BonusTokens).add(overflowTokens2);
}
// this triggers when both tier 1 and tier 2 discounted tokens have be filled - but ONLY afterwards, not if the flags got set during the same tx
// aka this is tier 3
if (tier2Reached && tier1Reached && tier2BonusTokens == 0) {
tokenAmount = purchasedTokens;
}
/*** Record & update state variables ***/
// Tracks purchased tokens for 2 tiers of discounts
totalTokensPurchased = totalTokensPurchased.add(purchasedTokens);
// Tracks total tokens pending to be minted - this includes presale tokens
tokensToMint = tokensToMint.add(tokenAmount);
weiRaised = weiRaised.add(weiAmount);
TokenPurchase(msg.sender, _beneficiary, weiAmount, tokenAmount);
// register payment so that later on it can be confirmed (and tokens issued and Ether paid out)
Payment memory newPayment = Payment(msg.sender, _beneficiary, weiAmount, tokenAmount, false, false, false);
investments.push(newPayment);
}
/**
* @dev confirms payment
* @param _investmentId uint256 uint256 of the investment id to confirm
*/
function confirmPayment(uint256 _investmentId) public onlyManager onlyConfirmPayment {
investments[_investmentId].confirmed = true;
ChangedInvestmentConfirmation(_investmentId, investments[_investmentId].investor, true);
}
/**
* @dev confirms payments via a batch method
* @param _investmentIds uint256[] array of uint256 of the investment ids to confirm
*/
function batchConfirmPayments(uint256[] _investmentIds) public onlyManager onlyConfirmPayment {
uint256 investmentId;
for (uint256 c; c < _investmentIds.length; c = c.add(1)) {
investmentId = _investmentIds[c]; // gas optimization
confirmPayment(investmentId);
}
}
/**
* @dev unconfirms payment made via investment id
* @param _investmentId uint256 uint256 of the investment to unconfirm
*/
function unConfirmPayment(uint256 _investmentId) public onlyManager onlyConfirmPayment {
investments[_investmentId].confirmed = false;
ChangedInvestmentConfirmation(_investmentId, investments[_investmentId].investor, false);
}
/**
* @dev allows contract owner to mint tokens for presale or non-ETH contributions in batches
* @param _toList address[] array of the beneficiaries to receive tokens
* @param _tokenList uint256[] array of the token amounts to mint for the corresponding users
*/
function batchMintTokenDirect(address[] _toList, uint256[] _tokenList) public onlyOwner {
require(_toList.length == _tokenList.length);
for (uint256 i; i < _toList.length; i = i.add(1)) {
mintTokenDirect(_toList[i], _tokenList[i]);
}
}
/**
* @dev allows contract owner to mint tokens for presale or non-ETH contributions
* @param _to address of the beneficiary to receive tokens
* @param _tokens uint256 of the token amount to mint
*/
function mintTokenDirect(address _to, uint256 _tokens) public onlyOwner {
require(tokensToMint.add(_tokens) <= ICO_TOKEN_CAP);
tokensToMint = tokensToMint.add(_tokens);
// register payment so that later on it can be confirmed (and tokens issued and Ether paid out)
Payment memory newPayment = Payment(address(0), _to, 0, _tokens, false, false, false);
investments.push(newPayment);
TokenPurchase(msg.sender, _to, 0, _tokens);
}
/**
* @dev allows contract owner to mint tokens for ICO enablers respecting the ICO_ENABLERS_CAP (no vesting)
* @param _to address for beneficiary
* @param _tokens uint256 token amount to mint
*/
function mintIcoEnablersTokens(address _to, uint256 _tokens) public onlyOwner onlyNoneZero(_to, _tokens) {
require(icoEnablersTokensMinted.add(_tokens) <= ICO_ENABLERS_CAP);
token.mint(_to, _tokens);
icoEnablersTokensMinted = icoEnablersTokensMinted.add(_tokens);
}
/**
* @dev allows contract owner to mint team tokens per DEVELOPMENT_TEAM_CAP and transfer to the development team's wallet (yes vesting)
* @param _to address for beneficiary
* @param _tokens uint256 token amount to mint
*/
function mintDevelopmentTeamTokens(address _to, uint256 _tokens) public onlyOwner onlyNoneZero(_to, _tokens) {
require(developmentTeamTokensMinted.add(_tokens) <= DEVELOPMENT_TEAM_CAP);
developmentTeamTokensMinted = developmentTeamTokensMinted.add(_tokens);
TokenVesting newVault = new TokenVesting(_to, now, VESTING_CLIFF, VESTING_DURATION, false);
vestingWallets.push(address(newVault)); // for convenience we keep them in storage so that they are easily accessible via MEW or etherscan
token.mint(address(newVault), _tokens);
}
/**
* @dev returns number of elements in the vestinWallets array
*/
function getVestingWalletLength() public view returns (uint256) {
return vestingWallets.length;
}
/**
* @dev set final the confirmation period
*/
function finalizeConfirmationPeriod() public onlyOwner onlyConfirmPayment {
confirmationPeriodOver = true;
}
/**
* @dev settlement of investment made via investment id
* @param _investmentId uint256 uint256 being the investment id
*/
function settleInvestment(uint256 _investmentId) public onlyConfirmationOver {
Payment storage p = investments[_investmentId];
// investment should not be settled already (prevent double token issueing or repayment)
require(!p.completedSettlement);
// investments have to be processed in right order
// unless we're at first investment, the previous has needs to have undergone an attempted settlement
require(_investmentId == 0 || investments[_investmentId.sub(1)].attemptedSettlement);
p.attemptedSettlement = true;
// just so that we can see which one we attempted last time and can continue with next
investmentIdLastAttemptedToSettle = _investmentId;
if (p.confirmed && !capReached) {
// if confirmed -> issue tokens, send ETH to wallet and complete settlement
// calculate number of tokens to be issued to investor
uint256 tokens = p.tokenAmount;
// check to see if this purchase sets it over the crowdsale token cap
// if so, refund
if (tokensMinted.add(tokens) > ICO_TOKEN_CAP) {
capReached = true;
if (p.weiAmount > 0) {
p.investor.send(p.weiAmount); // does not throw (otherwise we'd block all further settlements)
}
} else {
tokensToMint = tokensToMint.sub(tokens);
tokensMinted = tokensMinted.add(tokens);
// mint tokens for beneficiary
token.mint(p.beneficiary, tokens);
if (p.weiAmount > 0) {
// send Ether to project wallet (throws if wallet throws)
wallet.transfer(p.weiAmount);
}
}
p.completedSettlement = true;
} else {
// if not confirmed -> reimburse ETH or if fiat (presale) investor: do nothing
// only complete settlement if investor got their money back
// (does not throw (as .transfer would)
// otherwise we would block settlement process of all following investments)
if (p.investor != address(0) && p.weiAmount > 0) {
if (p.investor.send(p.weiAmount)) {
p.completedSettlement = true;
}
}
}
}
/**
* @dev allows the batch settlement of investments made
* @param _investmentIds uint256[] array of uint256 of investment ids
*/
function batchSettleInvestments(uint256[] _investmentIds) public {
for (uint256 c; c < _investmentIds.length; c = c.add(1)) {
settleInvestment(_investmentIds[c]);
}
}
/**
* @dev allows contract owner to finalize the ICO, unpause tokens, set treasurer, finish minting, and transfer ownship of the token contract
*/
function finalize() public onlyUnderwriter onlyConfirmationOver {
Pausable(token).unpause();
// this crowdsale also should not be treasurer of the token anymore
IcoToken(token).setTreasurer(this, false);
// do not allow new owner to mint further tokens
MintableToken(token).finishMinting();
// until now the owner of the token is this crowdsale contract
// in order for a human owner to make use of the tokens onlyOwner functions
// we need to transfer the ownership
// in the end the owner of this crowdsale will also be the owner of the token
Ownable(token).transferOwnership(owner);
}
/**
* @dev Create new instance of ico token contract
*/
function createTokenContract() internal returns (MintableToken) {
return new IcoToken();
}
/**
* @dev extend base functionality with min investment amount
*/
function validPurchase() internal view returns (bool) {
// minimal investment: 250 CHF (represented in wei)
require (msg.value >= minContributionInWei);
return super.validPurchase();
}
}
| confirms payments via a batch method _investmentIds uint256[] array of uint256 of the investment ids to confirm/ | function batchConfirmPayments(uint256[] _investmentIds) public onlyManager onlyConfirmPayment {
uint256 investmentId;
for (uint256 c; c < _investmentIds.length; c = c.add(1)) {
confirmPayment(investmentId);
}
}
| 13,074,883 |
./full_match/80001/0xd0BE417Fbe925eb1322dAe0fdF8f6f6bC60B0e7c/sources/_openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol | Returns the downcasted int176 from int256, reverting on overflow (when the input is less than smallest int176 or greater than largest int176). Counterpart to Solidity's `int176` operator. Requirements: - input must fit into 176 bits _Available since v4.7._/ | function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
}
| 858,561 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
// File: @openzeppelin/contracts/math/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
/**
* @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/vaults/ValueVaultMaster.sol
/*
* Here we have a list of constants. In order to get access to an address
* managed by ValueVaultMaster, the calling contract should copy and define
* some of these constants and use them as keys.
* Keys themselves are immutable. Addresses can be immutable or mutable.
*
* Vault addresses are immutable once set, and the list may grow:
* K_VAULT_WETH = 0;
* K_VAULT_ETH_USDC_UNI_V2_LP = 1;
* K_VAULT_ETH_WBTC_UNI_V2_LP = 2;
*
* Strategy addresses are mutable:
* K_STRATEGY_WETH_SODA_POOL = 0;
* K_STRATEGY_WETH_MULTI_POOL = 1;
* K_STRATEGY_ETHUSDC_MULTIPOOL = 100;
* K_STRATEGY_ETHWBTC_MULTIPOOL = 200;
*/
/*
* ValueVaultMaster manages all the vaults and strategies of our Value Vaults system.
*/
contract ValueVaultMaster {
address public governance;
address public bank;
address public minorPool;
address public profitSharer;
address public govToken; // VALUE
address public yfv; // When harvesting, convert some parts to YFV for govVault
address public usdc; // we only used USDC to estimate APY
address public govVault; // YFV -> VALUE, vUSD, vETH and 6.7% profit from Value Vaults
address public insuranceFund = 0xb7b2Ea8A1198368f950834875047aA7294A2bDAa; // set to Governance Multisig at start
address public performanceReward = 0x7Be4D5A99c903C437EC77A20CB6d0688cBB73c7f; // set to deploy wallet at start
uint256 public constant FEE_DENOMINATOR = 10000;
uint256 public govVaultProfitShareFee = 670; // 6.7% | VIP-1 (https://yfv.finance/vip-vote/vip_1)
uint256 public gasFee = 50; // 0.5% at start and can be set by governance decision
uint256 public minStakeTimeToClaimVaultReward = 24 hours;
mapping(address => bool) public isVault;
mapping(uint256 => address) public vaultByKey;
mapping(address => bool) public isStrategy;
mapping(uint256 => address) public strategyByKey;
mapping(address => uint256) public strategyQuota;
constructor(address _govToken, address _yfv, address _usdc) public {
govToken = _govToken;
yfv = _yfv;
usdc = _usdc;
governance = tx.origin;
}
function setGovernance(address _governance) external {
require(msg.sender == governance, "!governance");
governance = _governance;
}
// Immutable once set.
function setBank(address _bank) external {
require(msg.sender == governance, "!governance");
require(bank == address(0));
bank = _bank;
}
// Mutable in case we want to upgrade the pool.
function setMinorPool(address _minorPool) external {
require(msg.sender == governance, "!governance");
minorPool = _minorPool;
}
// Mutable in case we want to upgrade this module.
function setProfitSharer(address _profitSharer) external {
require(msg.sender == governance, "!governance");
profitSharer = _profitSharer;
}
// Mutable, in case governance want to upgrade VALUE to new version
function setGovToken(address _govToken) external {
require(msg.sender == governance, "!governance");
govToken = _govToken;
}
// Immutable once added, and you can always add more.
function addVault(uint256 _key, address _vault) external {
require(msg.sender == governance, "!governance");
require(vaultByKey[_key] == address(0), "vault: key is taken");
isVault[_vault] = true;
vaultByKey[_key] = _vault;
}
// Mutable and removable.
function addStrategy(uint256 _key, address _strategy) external {
require(msg.sender == governance, "!governance");
isStrategy[_strategy] = true;
strategyByKey[_key] = _strategy;
}
// Set 0 to disable quota (no limit)
function setStrategyQuota(address _strategy, uint256 _quota) external {
require(msg.sender == governance, "!governance");
strategyQuota[_strategy] = _quota;
}
function removeStrategy(uint256 _key) external {
require(msg.sender == governance, "!governance");
isStrategy[strategyByKey[_key]] = false;
delete strategyByKey[_key];
}
function setGovVault(address _govVault) public {
require(msg.sender == governance, "!governance");
govVault = _govVault;
}
function setInsuranceFund(address _insuranceFund) public {
require(msg.sender == governance, "!governance");
insuranceFund = _insuranceFund;
}
function setPerformanceReward(address _performanceReward) public{
require(msg.sender == governance, "!governance");
performanceReward = _performanceReward;
}
function setGovVaultProfitShareFee(uint256 _govVaultProfitShareFee) public {
require(msg.sender == governance, "!governance");
govVaultProfitShareFee = _govVaultProfitShareFee;
}
function setGasFee(uint256 _gasFee) public {
require(msg.sender == governance, "!governance");
gasFee = _gasFee;
}
function setMinStakeTimeToClaimVaultReward(uint256 _minStakeTimeToClaimVaultReward) public {
require(msg.sender == governance, "!governance");
minStakeTimeToClaimVaultReward = _minStakeTimeToClaimVaultReward;
}
/**
* This function allows governance to take unsupported tokens out of the contract.
* This is in an effort to make someone whole, should they seriously mess up.
* There is no guarantee governance will vote to return these.
* It also allows for removal of airdropped tokens.
*/
function governanceRecoverUnsupported(IERC20x _token, uint256 amount, address to) external {
require(msg.sender == governance, "!governance");
_token.transfer(to, amount);
}
}
interface IERC20x {
function transfer(address recipient, uint256 amount) external returns (bool);
}
// File: contracts/vaults/strategies/WETHMultiPoolStrategy.sol
interface IStrategyV2p1 {
function approve(IERC20 _token) external;
function approveForSpender(IERC20 _token, address spender) external;
// Deposit tokens to a farm to yield more tokens.
function deposit(address _vault, uint256 _amount) external; // IStrategy
function deposit(uint256 _poolId, uint256 _amount) external; // IStrategyV2
// Claim farming tokens
function claim(address _vault) external; // IStrategy
function claim(uint256 _poolId) external; // IStrategyV2
// The vault request to harvest the profit
function harvest(uint256 _bankPoolId) external; // IStrategy
function harvest(uint256 _bankPoolId, uint256 _poolId) external; // IStrategyV2
// Withdraw the principal from a farm.
function withdraw(address _vault, uint256 _amount) external; // IStrategy
function withdraw(uint256 _poolId, uint256 _amount) external; // IStrategyV2
// Set 0 to disable quota (no limit)
function poolQuota(uint256 _poolId) external view returns (uint256);
// Use when we want to switch between strategies
function forwardToAnotherStrategy(address _dest, uint256 _amount) external returns (uint256);
function switchBetweenPoolsByGov(uint256 _sourcePoolId, uint256 _destPoolId, uint256 _amount) external; // IStrategyV2p1
// Source LP token of this strategy
function getLpToken() external view returns(address);
// Target farming token of this strategy.
function getTargetToken(address _vault) external view returns(address); // IStrategy
function getTargetToken(uint256 _poolId) external view returns(address); // IStrategyV2
function balanceOf(address _vault) external view returns (uint256); // IStrategy
function balanceOf(uint256 _poolId) external view returns (uint256); // IStrategyV2
function pendingReward(address _vault) external view returns (uint256); // IStrategy
function pendingReward(uint256 _poolId) external view returns (uint256); // IStrategyV2
function expectedAPY(address _vault) external view returns (uint256); // IStrategy
function expectedAPY(uint256 _poolId, uint256 _lpTokenUsdcPrice) external view returns (uint256); // IStrategyV2
function governanceRescueToken(IERC20 _token) external returns (uint256);
}
interface IOneSplit {
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
) external view returns(
uint256 returnAmount,
uint256[] memory distribution
);
}
interface IUniswapRouter {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
interface IStakingRewards {
// Views
function lastTimeRewardApplicable() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
function rewardRate() external view returns (uint256);
function earned(address account) external view returns (uint256);
function getRewardForDuration() external view returns (uint256);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
// Mutative
function stake(uint256 amount) external;
function withdraw(uint256 amount) external;
function getReward() external;
function exit() external;
}
interface ISushiPool {
function deposit(uint256 _poolId, uint256 _amount) external;
function withdraw(uint256 _poolId, uint256 _amount) external;
}
interface ISodaPool {
function deposit(uint256 _poolId, uint256 _amount) external;
function claim(uint256 _poolId) external;
function withdraw(uint256 _poolId, uint256 _amount) external;
}
interface IProfitSharer {
function shareProfit() external returns (uint256);
}
interface IValueVaultBank {
function make_profit(uint256 _poolId, uint256 _amount) external;
}
// This contract is owned by Timelock.
// What it does is simple: deposit WETH to pools, and wait for ValueVaultBank's command.
// Atm we support 3 pool types: IStakingRewards (golff.finance), ISushiPool (chickenswap.org), ISodaPool (soda.finance)
contract WETHMultiPoolStrategy is IStrategyV2p1 {
using SafeMath for uint256;
address public governance; // will be a Timelock contract
address public operator; // can be EOA for non-fund transferring operation
uint256 public constant FEE_DENOMINATOR = 10000;
IOneSplit public onesplit = IOneSplit(0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e);
IUniswapRouter public unirouter = IUniswapRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
ValueVaultMaster public valueVaultMaster;
IERC20 public lpToken; // WETH
mapping(address => mapping(address => address[])) public uniswapPaths; // [input -> output] => uniswap_path
struct PoolInfo {
address vault;
IERC20 targetToken;
address targetPool;
uint256 targetPoolId; // poolId in soda/chicken pool (no use for IStakingRewards pool eg. golff.finance)
uint256 minHarvestForTakeProfit;
uint8 poolType; // 0: IStakingRewards, 1: ISushiPool, 2: ISodaPool
uint256 poolQuota; // set 0 to disable quota (no limit)
uint256 balance;
}
mapping(uint256 => PoolInfo) public poolMap; // poolIndex -> poolInfo
uint256 public totalBalance;
bool public aggressiveMode; // will try to stake all lpTokens available (be forwarded from bank or from another strategies)
uint8[] public poolPreferredIds; // sorted by preference
// weth = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"
// golffToken = "0x7AfB39837Fd244A651e4F0C5660B4037214D4aDF"
// poolMap[0].targetPool = "0x74BCb8b78996F49F46497be185174B2a89191fD6"
constructor(ValueVaultMaster _valueVaultMaster,
IERC20 _lpToken,
bool _aggressiveMode) public {
valueVaultMaster = _valueVaultMaster;
lpToken = _lpToken;
aggressiveMode = _aggressiveMode;
governance = tx.origin;
operator = msg.sender;
// Approve all
lpToken.approve(valueVaultMaster.bank(), type(uint256).max);
lpToken.approve(address(unirouter), type(uint256).max);
}
// targetToken: golffToken = 0x7AfB39837Fd244A651e4F0C5660B4037214D4aDF
// targetPool: poolMap[0].targetPool = 0x74BCb8b78996F49F46497be185174B2a89191fD6
function setPoolInfo(uint256 _poolId, address _vault, IERC20 _targetToken, address _targetPool, uint256 _targetPoolId, uint256 _minHarvestForTakeProfit, uint8 _poolType, uint256 _poolQuota) external {
require(msg.sender == governance || msg.sender == operator, "!governance && !operator");
poolMap[_poolId].vault = _vault;
poolMap[_poolId].targetToken = _targetToken;
poolMap[_poolId].targetPool = _targetPool;
poolMap[_poolId].targetPoolId = _targetPoolId;
poolMap[_poolId].minHarvestForTakeProfit = _minHarvestForTakeProfit;
poolMap[_poolId].poolType = _poolType;
poolMap[_poolId].poolQuota = _poolQuota;
_targetToken.approve(address(unirouter), type(uint256).max);
lpToken.approve(_vault, type(uint256).max);
lpToken.approve(address(_targetPool), type(uint256).max);
}
function approve(IERC20 _token) external override {
require(msg.sender == governance || msg.sender == operator, "!governance && !operator");
_token.approve(valueVaultMaster.bank(), type(uint256).max);
_token.approve(address(unirouter), type(uint256).max);
}
function approveForSpender(IERC20 _token, address spender) external override {
require(msg.sender == governance || msg.sender == operator, "!governance && !operator");
_token.approve(spender, type(uint256).max);
}
function setGovernance(address _governance) external {
require(msg.sender == governance, "!governance");
governance = _governance;
}
function setOperator(address _operator) external {
require(msg.sender == governance || msg.sender == operator, "!governance && !operator");
operator = _operator;
}
function setPoolPreferredIds(uint8[] memory _poolPreferredIds) public {
require(msg.sender == governance || msg.sender == operator, "!governance && !operator");
delete poolPreferredIds;
for (uint8 i = 0; i < _poolPreferredIds.length; ++i) {
poolPreferredIds.push(_poolPreferredIds[i]);
}
}
function setMinHarvestForTakeProfit(uint256 _poolId, uint256 _minHarvestForTakeProfit) external {
require(msg.sender == governance || msg.sender == operator, "!governance && !operator");
poolMap[_poolId].minHarvestForTakeProfit = _minHarvestForTakeProfit;
}
function setPoolQuota(uint256 _poolId, uint256 _poolQuota) external {
require(msg.sender == governance || msg.sender == operator, "!governance && !operator");
poolMap[_poolId].poolQuota = _poolQuota;
}
// Sometime the balance could be slightly changed (due to the pool, or because we call xxxByGov methods)
function setPoolBalance(uint256 _poolId, uint256 _balance) external {
require(msg.sender == governance || msg.sender == operator, "!governance && !operator");
poolMap[_poolId].balance = _balance;
}
function setTotalBalance(uint256 _totalBalance) external {
require(msg.sender == governance || msg.sender == operator, "!governance && !operator");
totalBalance = _totalBalance;
}
function setAggressiveMode(bool _aggressiveMode) external {
require(msg.sender == governance || msg.sender == operator, "!governance && !operator");
aggressiveMode = _aggressiveMode;
}
function setOnesplit(IOneSplit _onesplit) external {
require(msg.sender == governance || msg.sender == operator, "!governance && !operator");
onesplit = _onesplit;
}
function setUnirouter(IUniswapRouter _unirouter) external {
require(msg.sender == governance || msg.sender == operator, "!governance && !operator");
unirouter = _unirouter;
}
/**
* @dev See {IStrategy-deposit}.
*/
function deposit(address _vault, uint256 _amount) public override {
require(valueVaultMaster.isVault(msg.sender), "sender not vault");
require(poolPreferredIds.length > 0, "no pool");
for (uint256 i = 0; i < poolPreferredIds.length; ++i) {
uint256 _pid = poolPreferredIds[i];
if (poolMap[_pid].vault == _vault) {
uint256 _quota = poolMap[_pid].poolQuota;
if (_quota == 0 || balanceOf(_pid) < _quota) {
_deposit(_pid, _amount);
return;
}
}
}
revert("Exceeded pool quota");
}
/**
* @dev See {IStrategyV2-deposit}.
*/
function deposit(uint256 _poolId, uint256 _amount) public override {
require(poolMap[_poolId].vault == msg.sender, "sender not vault");
_deposit(_poolId, _amount);
}
function _deposit(uint256 _poolId, uint256 _amount) internal {
if (aggressiveMode) {
_amount = lpToken.balanceOf(address(this));
}
if (poolMap[_poolId].poolType == 0) {
IStakingRewards(poolMap[_poolId].targetPool).stake(_amount);
} else {
ISushiPool(poolMap[_poolId].targetPool).deposit(poolMap[_poolId].targetPoolId, _amount);
}
poolMap[_poolId].balance = poolMap[_poolId].balance.add(_amount);
totalBalance = totalBalance.add(_amount);
}
/**
* @dev See {IStrategy-claim}.
*/
function claim(address _vault) external override {
require(valueVaultMaster.isVault(_vault), "not vault");
require(poolPreferredIds.length > 0, "no pool");
for (uint256 i = 0; i < poolPreferredIds.length; ++i) {
uint256 _pid = poolPreferredIds[i];
if (poolMap[_pid].vault == _vault) {
_claim(_pid);
}
}
}
/**
* @dev See {IStrategyV2-claim}.
*/
function claim(uint256 _poolId) external override {
require(poolMap[_poolId].vault == msg.sender, "sender not vault");
_claim(_poolId);
}
function _claim(uint256 _poolId) internal {
if (poolMap[_poolId].poolType == 0) {
IStakingRewards(poolMap[_poolId].targetPool).getReward();
} else if (poolMap[_poolId].poolType == 1) {
ISushiPool(poolMap[_poolId].targetPool).deposit(poolMap[_poolId].targetPoolId, 0);
} else {
ISodaPool(poolMap[_poolId].targetPool).claim(poolMap[_poolId].targetPoolId);
}
}
/**
* @dev See {IStrategy-withdraw}.
*/
function withdraw(address _vault, uint256 _amount) external override {
require(valueVaultMaster.isVault(msg.sender), "sender not vault");
require(poolPreferredIds.length > 0, "no pool");
for (uint256 i = poolPreferredIds.length; i >= 1; --i) {
uint256 _pid = poolPreferredIds[i - 1];
if (poolMap[_pid].vault == _vault) {
uint256 _bal = poolMap[_pid].balance;
if (_bal > 0) {
_withdraw(_pid, (_bal > _amount) ? _amount : _bal);
uint256 strategyBal = lpToken.balanceOf(address(this));
lpToken.transfer(valueVaultMaster.bank(), strategyBal);
if (strategyBal >= _amount) break;
if (strategyBal > 0) _amount = _amount - strategyBal;
}
}
}
}
/**
* @dev See {IStrategyV2-withdraw}.
*/
function withdraw(uint256 _poolId, uint256 _amount) external override {
require(poolMap[_poolId].vault == msg.sender, "sender not vault");
if (lpToken.balanceOf(address(this)) >= _amount) return; // has enough balance, no need to withdraw from pool
_withdraw(_poolId, _amount);
}
function _withdraw(uint256 _poolId, uint256 _amount) internal {
if (poolMap[_poolId].poolType == 0) {
IStakingRewards(poolMap[_poolId].targetPool).withdraw(_amount);
} else {
ISushiPool(poolMap[_poolId].targetPool).withdraw(poolMap[_poolId].targetPoolId, _amount);
}
if (poolMap[_poolId].balance < _amount) {
_amount = poolMap[_poolId].balance;
}
poolMap[_poolId].balance = poolMap[_poolId].balance - _amount;
if (totalBalance >= _amount) totalBalance = totalBalance - _amount;
}
function depositByGov(address pool, uint8 _poolType, uint256 _targetPoolId, uint256 _amount) external {
require(msg.sender == governance, "!governance");
if (_poolType == 0) {
IStakingRewards(pool).stake(_amount);
} else {
ISushiPool(pool).deposit(_targetPoolId, _amount);
}
}
function claimByGov(address pool, uint8 _poolType, uint256 _targetPoolId) external {
require(msg.sender == governance, "!governance");
if (_poolType == 0) {
IStakingRewards(pool).getReward();
} else if (_poolType == 1) {
ISushiPool(pool).deposit(_targetPoolId, 0);
} else {
ISodaPool(pool).claim(_targetPoolId);
}
}
function withdrawByGov(address pool, uint8 _poolType, uint256 _targetPoolId, uint256 _amount) external {
require(msg.sender == governance, "!governance");
if (_poolType == 0) {
IStakingRewards(pool).withdraw(_amount);
} else {
ISushiPool(pool).withdraw(_targetPoolId, _amount);
}
}
function switchBetweenPoolsByGov(uint256 _sourcePoolId, uint256 _destPoolId, uint256 _amount) external override {
require(msg.sender == governance, "!governance");
_withdraw(_sourcePoolId, _amount);
_deposit(_destPoolId, _amount);
}
/**
* @dev See {IStrategyV2-poolQuota}
*/
function poolQuota(uint256 _poolId) external override view returns (uint256) {
return poolMap[_poolId].poolQuota;
}
/**
* @dev See {IStrategyV2-forwardToAnotherStrategy}
*/
function forwardToAnotherStrategy(address _dest, uint256 _amount) external override returns (uint256 sent) {
require(valueVaultMaster.isVault(msg.sender) || msg.sender == governance, "!vault && !governance");
require(valueVaultMaster.isStrategy(_dest), "not strategy");
require(IStrategyV2p1(_dest).getLpToken() == address(lpToken), "!lpToken");
uint256 lpTokenBal = lpToken.balanceOf(address(this));
sent = (_amount < lpTokenBal) ? _amount : lpTokenBal;
lpToken.transfer(_dest, sent);
}
function setUnirouterPath(address _input, address _output, address [] memory _path) public {
require(msg.sender == governance || msg.sender == operator, "!governance && !operator");
uniswapPaths[_input][_output] = _path;
}
function _swapTokens(address _input, address _output, uint256 _amount) internal {
address[] memory path = uniswapPaths[_input][_output];
if (path.length == 0) {
// path: _input -> _output
path = new address[](2);
path[0] = _input;
path[1] = _output;
}
// swapExactTokensForTokens(amountIn, amountOutMin, path, to, deadline)
unirouter.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(1800));
}
/**
* @dev See {IStrategy-harvest}.
*/
function harvest(uint256 _bankPoolId) external override {
address _vault = msg.sender;
require(valueVaultMaster.isVault(_vault), "!vault"); // additional protection so we don't burn the funds
require(poolPreferredIds.length > 0, "no pool");
for (uint256 i = 0; i < poolPreferredIds.length; ++i) {
uint256 _pid = poolPreferredIds[i];
if (poolMap[_pid].vault == _vault) {
_harvest(_bankPoolId, _pid);
}
}
}
/**
* @dev See {IStrategy-harvest}.
*/
function harvest(uint256 _bankPoolId, uint256 _poolId) external override {
require(valueVaultMaster.isVault(msg.sender), "!vault"); // additional protection so we don't burn the funds
_harvest(_bankPoolId, _poolId);
}
uint256 public log_golffBal;
uint256 public log_wethBal;
uint256 public log_yfvGovVault;
function _harvest(uint256 _bankPoolId, uint256 _poolId) internal {
_claim(_poolId);
IERC20 targetToken = poolMap[_poolId].targetToken;
uint256 targetTokenBal = targetToken.balanceOf(address(this));
log_golffBal = targetTokenBal;
if (targetTokenBal < poolMap[_poolId].minHarvestForTakeProfit) return;
_swapTokens(address(targetToken), address(lpToken), targetTokenBal);
uint256 wethBal = lpToken.balanceOf(address(this));
log_wethBal = wethBal;
if (wethBal > 0) {
address profitSharer = valueVaultMaster.profitSharer();
address performanceReward = valueVaultMaster.performanceReward();
address bank = valueVaultMaster.bank();
if (valueVaultMaster.govVaultProfitShareFee() > 0 && profitSharer != address(0)) {
address yfv = valueVaultMaster.yfv();
uint256 _govVaultProfitShareFee = wethBal.mul(valueVaultMaster.govVaultProfitShareFee()).div(FEE_DENOMINATOR);
_swapTokens(address(lpToken), yfv, _govVaultProfitShareFee);
log_yfvGovVault = IERC20(yfv).balanceOf(address(this));
IERC20(yfv).transfer(profitSharer, IERC20(yfv).balanceOf(address(this)));
IProfitSharer(profitSharer).shareProfit();
}
if (valueVaultMaster.gasFee() > 0 && performanceReward != address(0)) {
uint256 _gasFee = wethBal.mul(valueVaultMaster.gasFee()).div(FEE_DENOMINATOR);
lpToken.transfer(performanceReward, _gasFee);
}
uint256 balanceLeft = lpToken.balanceOf(address(this));
if (lpToken.allowance(address(this), bank) < balanceLeft) {
lpToken.approve(bank, 0);
lpToken.approve(bank, balanceLeft);
}
IValueVaultBank(bank).make_profit(_bankPoolId, balanceLeft);
}
}
/**
* @dev See {IStrategyV2-getLpToken}.
*/
function getLpToken() external view override returns(address) {
return address(lpToken);
}
/**
* @dev See {IStrategy-getTargetToken}.
* Always use pool 0 (default).
*/
function getTargetToken(address) external override view returns(address) {
return address(poolMap[0].targetToken);
}
/**
* @dev See {IStrategyV2-getTargetToken}.
*/
function getTargetToken(uint256 _poolId) external override view returns(address) {
return address(poolMap[_poolId].targetToken);
}
function balanceOf(address _vault) public override view returns (uint256 _balanceOfVault) {
_balanceOfVault = 0;
for (uint256 i = 0; i < poolPreferredIds.length; ++i) {
uint256 _pid = poolPreferredIds[i];
if (poolMap[_pid].vault == _vault) {
_balanceOfVault = _balanceOfVault.add(poolMap[_pid].balance);
}
}
}
function balanceOf(uint256 _poolId) public override view returns (uint256) {
return poolMap[_poolId].balance;
}
function pendingReward(address) public override view returns (uint256) {
return pendingReward(0);
}
// Only support IStakingRewards pool
function pendingReward(uint256 _poolId) public override view returns (uint256) {
if (poolMap[_poolId].poolType != 0) return 0; // do not support other pool types
return IStakingRewards(poolMap[_poolId].targetPool).earned(address(this));
}
// always use pool 0 (default)
function expectedAPY(address) public override view returns (uint256) {
return expectedAPY(0, 0);
}
// Helper function - should never use it on-chain.
// Only support IStakingRewards pool.
// Return 10000x of APY. _lpTokenUsdcPrice is not used.
function expectedAPY(uint256 _poolId, uint256) public override view returns (uint256) {
if (poolMap[_poolId].poolType != 0) return 0; // do not support other pool types
IStakingRewards targetPool = IStakingRewards(poolMap[_poolId].targetPool);
uint256 totalSupply = targetPool.totalSupply();
if (totalSupply == 0) return 0;
uint256 investAmt = poolMap[_poolId].balance;
uint256 oneHourReward = targetPool.rewardRate().mul(3600);
uint256 returnAmt = oneHourReward.mul(investAmt).div(totalSupply);
IERC20 usdc = IERC20(valueVaultMaster.usdc());
(uint256 investInUSDC, ) = onesplit.getExpectedReturn(lpToken, usdc, investAmt, 10, 0);
(uint256 returnInUSDC, ) = onesplit.getExpectedReturn(poolMap[_poolId].targetToken, usdc, returnAmt, 10, 0);
return returnInUSDC.mul(8760).mul(FEE_DENOMINATOR).div(investInUSDC); // 100 -> 1%
}
event ExecuteTransaction(address indexed target, uint value, string signature, bytes data);
/**
* @dev This is from Timelock contract, the governance should be a Timelock contract before calling this
*/
function executeTransaction(address target, uint value, string memory signature, bytes memory data) public returns (bytes memory) {
require(msg.sender == governance, "!governance");
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call{value: value}(callData);
require(success, "WETHSodaPoolStrategy::executeTransaction: Transaction execution reverted.");
emit ExecuteTransaction(target, value, signature, data);
return returnData;
}
/**
* @dev if there is any token stuck we will need governance support to rescue the fund
*/
function governanceRescueToken(IERC20 _token) external override returns (uint256 balance) {
address bank = valueVaultMaster.bank();
require(bank == msg.sender, "sender not bank");
balance = _token.balanceOf(address(this));
_token.transfer(bank, balance);
}
} | See {IStrategy-harvest}./ | function harvest(uint256 _bankPoolId, uint256 _poolId) external override {
_harvest(_bankPoolId, _poolId);
}
uint256 public log_golffBal;
uint256 public log_wethBal;
uint256 public log_yfvGovVault;
| 11,958,460 |
// to test issue with nodes breaking with large clients over WS
// fixed in web3 with fragmentationThreshold: 8192
pragma solidity ^0.4.17;
contract BigFreakingContract {
event Transfer(address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
mapping( address => uint ) _balances;
mapping( address => mapping( address => uint ) ) _approvals;
uint public _supply;
constructor( uint initial_balance ) public {
_balances[msg.sender] = initial_balance;
_supply = initial_balance;
}
function totalSupply() public constant returns (uint supply) {
return _supply;
}
function balanceOf( address who ) public constant returns (uint value) {
return _balances[who];
}
function transfer( address to, uint value) public returns (bool ok) {
if( _balances[msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
_balances[msg.sender] -= value;
_balances[to] += value;
emit Transfer( msg.sender, to, value );
return true;
}
function transferFrom( address from, address to, uint value) public returns (bool ok) {
// if you don't have enough balance, throw
if( _balances[from] < value ) {
revert();
}
// if you don't have approval, throw
if( _approvals[from][msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
// transfer and return true
_approvals[from][msg.sender] -= value;
_balances[from] -= value;
_balances[to] += value;
emit Transfer( from, to, value );
return true;
}
function approve(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function allowance(address owner, address spender) public constant returns (uint _allowance) {
return _approvals[owner][spender];
}
function safeToAdd(uint a, uint b) internal pure returns (bool) {
return (a + b >= a);
}
function isAvailable() public pure returns (bool) {
return false;
}
function approve_1(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_2(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_3(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_4(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_5(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_6(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_7(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_8(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_9(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_10(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_11(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_12(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_13(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_14(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_15(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_16(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_17(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_18(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_19(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_20(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_21(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_22(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_23(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_24(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_25(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_26(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_27(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_28(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_29(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_30(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_31(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_32(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_33(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_34(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_35(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_36(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_37(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_38(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_39(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_40(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_41(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_42(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_43(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_44(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_45(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_46(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_47(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_48(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_49(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_50(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_51(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_52(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_53(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_54(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_55(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_56(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_57(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_58(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_59(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_60(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_61(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_62(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_63(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_64(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_65(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_66(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_67(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_68(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_69(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_70(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_71(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_72(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_73(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_74(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_75(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_76(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_77(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_78(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_79(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_80(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_81(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_82(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_83(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_84(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_85(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_86(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_87(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_88(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_89(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_90(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_91(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_92(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_93(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_94(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_95(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_96(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_97(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_98(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_99(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_100(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_101(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_102(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_103(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_104(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_105(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_106(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_107(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_108(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_109(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_110(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_111(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_112(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_113(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_114(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_115(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_116(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_117(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_118(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_119(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_120(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_121(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_122(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_123(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_124(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_125(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_126(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_127(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_128(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_129(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_130(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_131(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_132(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_133(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_134(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_135(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_136(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_137(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_138(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_139(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_140(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_141(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_142(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_143(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_144(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_145(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_146(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_147(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_148(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_149(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_150(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_151(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_152(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_153(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_154(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_155(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_156(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_157(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_158(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_159(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_160(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_161(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_162(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_163(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_164(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_165(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_166(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_167(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_168(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_169(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_170(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_171(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_172(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_173(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_174(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_175(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_176(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_177(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_178(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_179(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_180(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_181(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_182(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_183(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_184(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_185(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_186(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_187(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_188(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_189(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_190(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_191(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_192(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_193(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_194(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_195(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_196(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_197(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_198(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_199(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_200(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_201(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_202(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_203(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_204(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_205(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_206(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_207(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_208(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_209(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_210(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_211(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_212(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_213(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_214(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_215(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_216(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_217(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_218(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_219(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_220(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_221(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_222(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_223(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_224(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_225(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_226(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_227(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_228(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_229(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_230(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_231(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_232(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_233(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_234(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_235(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_236(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_237(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_238(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_239(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_240(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_241(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_242(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_243(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_244(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_245(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_246(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_247(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_248(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_249(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_250(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_251(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_252(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_253(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_254(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_255(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_256(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_257(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_258(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_259(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_260(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_261(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_262(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_263(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_264(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_265(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_266(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_267(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_268(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_269(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_270(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_271(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_272(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_273(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_274(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_275(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_276(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_277(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_278(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_279(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_280(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_281(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_282(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_283(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_284(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_285(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_286(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_287(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_288(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_289(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_290(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_291(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_292(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_293(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_294(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_295(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_296(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_297(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_298(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_299(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_300(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_301(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_302(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_303(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_304(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_305(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_306(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_307(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_308(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_309(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_310(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_311(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_312(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_313(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_314(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_315(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_316(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_317(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_318(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_319(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_320(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_321(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_322(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_323(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_324(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_325(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_326(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_327(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_328(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_329(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_330(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_331(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_332(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_333(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_334(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_335(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_336(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_337(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_338(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_339(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_340(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_341(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_342(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_343(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_344(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_345(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_346(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_347(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_348(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_349(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_350(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_351(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_352(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_353(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_354(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_355(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_356(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_357(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_358(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_359(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_360(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_361(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_362(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_363(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_364(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_365(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_366(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_367(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_368(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_369(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_370(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_371(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_372(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_373(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_374(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_375(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_376(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_377(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_378(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_379(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_380(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_381(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_382(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_383(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_384(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_385(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_386(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_387(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_388(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_389(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_390(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_391(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_392(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_393(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_394(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_395(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_396(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_397(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_398(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_399(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_400(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_401(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_402(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_403(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_404(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_405(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_406(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_407(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_408(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_409(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_410(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_411(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_412(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_413(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_414(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_415(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_416(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_417(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_418(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_419(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_420(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_421(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_422(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_423(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_424(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_425(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_426(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_427(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_428(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_429(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_430(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_431(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_432(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_433(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_434(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_435(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_436(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_437(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_438(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_439(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_440(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_441(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_442(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_443(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_444(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_445(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_446(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_447(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_448(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_449(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_450(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_451(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_452(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_453(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_454(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_455(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_456(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_457(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_458(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_459(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_460(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_461(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_462(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_463(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_464(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_465(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_466(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_467(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_468(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_469(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_470(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_471(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_472(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_473(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_474(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_475(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_476(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_477(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_478(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_479(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_480(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_481(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_482(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_483(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_484(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_485(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_486(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_487(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_488(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_489(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_490(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_491(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_492(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_493(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_494(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_495(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_496(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_497(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_498(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_499(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_500(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_501(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_502(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_503(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_504(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_505(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_506(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_507(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_508(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_509(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_510(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_511(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_512(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_513(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_514(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_515(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_516(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_517(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_518(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_519(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_520(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_521(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_522(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_523(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_524(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_525(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_526(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_527(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_528(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_529(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_530(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_531(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_532(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_533(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_534(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_535(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_536(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_537(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_538(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_539(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_540(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_541(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_542(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_543(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_544(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_545(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_546(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_547(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_548(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_549(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_550(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_551(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_552(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_553(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_554(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_555(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_556(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_557(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_558(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_559(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_560(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_561(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_562(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_563(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_564(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_565(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_566(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_567(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_568(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_569(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_570(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_571(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_572(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_573(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_574(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_575(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_576(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_577(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_578(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_579(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_580(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_581(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_582(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_583(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_584(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_585(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_586(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_587(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_588(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_589(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_590(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_591(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_592(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_593(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_594(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_595(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_596(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_597(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_598(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_599(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_600(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_601(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_602(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_603(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_604(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_605(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_606(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_607(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_608(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_609(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_610(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_611(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_612(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_613(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_614(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_615(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_616(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_617(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_618(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_619(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_620(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_621(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_622(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_623(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_624(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_625(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_626(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_627(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_628(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_629(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_630(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_631(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_632(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_633(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_634(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_635(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_636(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_637(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_638(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_639(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_640(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_641(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_642(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_643(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_644(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_645(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_646(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_647(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_648(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_649(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_650(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_651(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_652(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_653(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_654(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_655(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_656(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_657(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_658(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_659(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_660(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_661(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_662(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_663(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_664(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_665(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_666(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_667(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_668(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_669(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_670(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_671(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_672(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_673(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_674(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_675(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_676(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_677(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_678(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_679(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_680(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_681(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_682(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_683(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_684(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_685(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_686(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_687(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_688(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_689(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_690(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_691(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_692(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_693(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_694(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_695(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_696(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_697(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_698(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_699(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_700(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_701(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_702(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_703(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_704(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_705(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_706(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_707(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_708(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_709(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_710(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_711(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_712(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_713(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_714(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_715(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_716(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_717(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_718(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_719(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_720(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_721(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_722(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_723(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_724(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_725(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_726(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_727(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_728(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_729(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_730(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_731(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_732(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_733(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_734(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_735(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_736(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_737(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_738(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_739(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_740(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_741(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_742(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_743(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_744(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_745(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_746(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_747(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_748(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_749(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_750(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_751(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_752(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_753(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_754(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_755(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_756(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_757(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_758(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_759(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_760(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_761(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_762(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_763(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_764(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_765(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_766(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_767(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_768(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_769(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_770(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_771(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_772(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_773(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_774(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_775(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_776(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_777(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_778(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_779(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_780(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_781(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_782(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_783(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_784(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_785(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_786(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_787(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_788(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_789(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_790(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_791(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_792(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_793(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_794(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_795(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_796(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_797(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_798(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_799(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_800(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_801(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_802(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_803(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_804(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_805(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_806(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_807(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_808(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_809(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_810(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_811(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_812(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_813(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_814(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_815(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_816(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_817(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_818(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_819(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_820(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_821(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_822(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_823(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_824(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_825(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_826(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_827(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_828(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_829(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_830(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_831(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_832(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_833(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_834(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_835(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_836(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_837(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_838(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_839(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_840(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_841(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_842(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_843(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_844(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_845(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_846(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_847(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_848(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_849(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_850(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_851(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_852(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_853(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_854(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_855(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_856(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_857(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_858(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_859(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_860(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_861(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_862(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_863(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_864(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_865(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_866(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_867(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_868(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_869(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_870(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_871(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_872(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_873(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_874(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_875(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_876(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_877(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_878(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_879(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_880(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_881(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_882(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_883(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_884(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_885(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_886(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_887(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_888(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_889(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_890(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_891(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_892(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_893(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_894(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_895(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_896(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_897(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_898(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_899(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_900(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_901(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
}
| TODO: should increase instead | function approve_750(address spender, uint value) public returns (bool ok) {
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
| 6,454,463 |
/**
* Copyright BOOSTRY Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
import "./Ownable.sol";
import "./OTCExchangeStorageModel.sol";
/// @title Exchangeコントラクトの取引情報を永続化するためのEternalStorage
/// @dev Storageのアクセスは認可したExchangeコントラクト限定
contract OTCExchangeStorage is Ownable, OTCExchangeStorageModel {
constructor() {}
// -------------------------------------------------------------------
// 最新バージョンのExchangeコントラクトアドレス
// -------------------------------------------------------------------
// 最新バージョンのExchangeコントラクトアドレス
address public latestVersion;
/// @notice Exchangeコントラクトのバージョン更新
/// @dev コントラクトオーナーのみ実行が可能
/// @param _newVersion 新しいExchangeコントラクトのアドレス
function upgradeVersion(address _newVersion)
public
onlyOwner()
{
latestVersion = _newVersion;
}
/// @dev 実行者が最新バージョンのExchangeアドレスであることをチェック
modifier onlyLatestVersion() {
require(msg.sender == latestVersion);
_;
}
// -------------------------------------------------------------------
// 残高数量
// -------------------------------------------------------------------
// 残高情報
// account => token => balance
mapping(address => mapping(address => uint256)) private balances;
/// @notice 残高の更新
/// @dev 最新バージョンのExchangeコントラクトのみ実行が可能
/// @param _account アドレス
/// @param _token トークンアドレス
/// @param _value 更新後の残高数量
/// @return 処理結果
function setBalance(address _account, address _token, uint256 _value)
public
onlyLatestVersion()
returns (bool)
{
balances[_account][_token] = _value;
return true;
}
/// @notice 残高数量の参照
/// @param _account アドレス
/// @param _token トークンアドレス
/// @return 残高数量
function getBalance(address _account, address _token)
public
view
returns (uint256)
{
return balances[_account][_token];
}
// -------------------------------------------------------------------
// 拘束数量(約定済みの数量)
// -------------------------------------------------------------------
// 拘束数量
// account => token => order commitment
mapping(address => mapping(address => uint256)) private commitments;
/// @notice 拘束数量の更新
/// @dev 最新バージョンのExchangeコントラクトのみ実行が可能
/// @param _account アドレス
/// @param _token トークンアドレス
/// @param _value 更新後の残高数量
function setCommitment(address _account, address _token, uint256 _value)
public
onlyLatestVersion()
{
commitments[_account][_token] = _value;
}
/// @notice 拘束数量の参照
/// @param _account アドレス
/// @param _token トークンアドレス
/// @return 拘束数量
function getCommitment(address _account, address _token)
public
view
returns (uint256)
{
return commitments[_account][_token];
}
// -------------------------------------------------------------------
// 注文情報
// -------------------------------------------------------------------
// 注文情報
// orderId => order
mapping(uint256 => OTCExchangeStorageModel.OTCOrder) private orderBook;
/// @notice 注文情報の更新
/// @dev 最新バージョンのExchangeコントラクトのみ実行が可能
/// @param _orderId 注文ID
/// @param _order 注文情報
function setOrder(uint256 _orderId, OTCExchangeStorageModel.OTCOrder memory _order)
public
onlyLatestVersion()
{
orderBook[_orderId] = _order;
}
/// @notice 注文情報の更新(取引実行者(売り手)EOAアドレス)
/// @dev 最新バージョンのExchangeコントラクトのみ実行が可能
/// @param _orderId 注文ID
/// @param _owner 取引実行者(売り手)EOAアドレス
function setOrderOwner(uint256 _orderId, address _owner)
public
onlyLatestVersion()
{
orderBook[_orderId].owner = _owner;
}
/// @notice 注文情報の更新(買い手EOAアドレス)
/// @dev 最新バージョンのExchangeコントラクトのみ実行が可能
/// @param _orderId 注文ID
/// @param _counterpart 買い手EOAアドレス
function setOrderCounterpart(uint256 _orderId, address _counterpart)
public
onlyLatestVersion()
{
orderBook[_orderId].counterpart = _counterpart;
}
/// @notice 注文情報の更新(トークンアドレス)
/// @dev 最新バージョンのExchangeコントラクトのみ実行が可能
/// @param _orderId 注文ID
/// @param _token トークンアドレス
function setOrderToken(uint256 _orderId, address _token)
public
onlyLatestVersion()
{
orderBook[_orderId].token = _token;
}
/// @notice 注文情報の更新(注文数量)
/// @dev 最新バージョンのExchangeコントラクトのみ実行が可能
/// @param _orderId 注文ID
/// @param _amount 注文数量
function setOrderAmount(uint256 _orderId, uint256 _amount)
public
onlyLatestVersion()
{
orderBook[_orderId].amount = _amount;
}
/// @notice 注文情報の更新(注文単価)
/// @dev 最新バージョンのExchangeコントラクトのみ実行が可能
/// @param _orderId 注文ID
/// @param _price 注文単価
function setOrderPrice(uint256 _orderId, uint256 _price)
public
onlyLatestVersion()
{
orderBook[_orderId].price = _price;
}
/// @notice 注文情報の更新(決済業者のEOAアドレス)
/// @dev 最新バージョンのExchangeコントラクトのみ実行が可能
/// @param _orderId 注文ID
/// @param _agent 決済業者のEOAアドレス
function setOrderAgent(uint256 _orderId, address _agent)
public
onlyLatestVersion()
{
orderBook[_orderId].agent = _agent;
}
/// @notice 注文情報の更新(キャンセル済み状態)
/// @dev 最新バージョンのExchangeコントラクトのみ実行が可能
/// @param _orderId 注文ID
/// @param _canceled キャンセル済み状態
function setOrderCanceled(uint256 _orderId, bool _canceled)
public
onlyLatestVersion()
{
orderBook[_orderId].canceled = _canceled;
}
/// @notice 注文情報の参照
/// @param _orderId 注文ID
/// @return 注文情報
function getOrder(uint256 _orderId)
public
view
returns (OTCExchangeStorageModel.OTCOrder memory)
{
return orderBook[_orderId];
}
/// @notice 注文情報の参照(取引実行者EOAアドレス)
/// @param _orderId 注文ID
/// @return 取引実行者EOAアドレス
function getOrderOwner(uint256 _orderId)
public
view
returns(address)
{
return orderBook[_orderId].owner;
}
/// @notice 注文情報の参照(買い手EOAアドレス)
/// @param _orderId 注文ID
/// @return 買い手EOAアドレス
function getOrderCounterpart(uint256 _orderId)
public
view
returns(address)
{
return orderBook[_orderId].counterpart;
}
/// @notice 注文情報の参照(トークンアドレス)
/// @param _orderId 注文ID
/// @return トークンアドレス
function getOrderToken(uint256 _orderId)
public
view
returns(address)
{
return orderBook[_orderId].token;
}
/// @notice 注文情報の参照(注文数量)
/// @param _orderId 注文ID
/// @return 注文数量
function getOrderAmount(uint256 _orderId)
public
view
returns(uint256)
{
return orderBook[_orderId].amount;
}
/// @notice 注文情報の参照(注文単価)
/// @param _orderId 注文ID
/// @return 注文単価
function getOrderPrice(uint256 _orderId)
public
view
returns(uint256)
{
return orderBook[_orderId].price;
}
/// @notice 注文情報の参照(決済業者のEOAアドレス)
/// @param _orderId 注文ID
/// @return 決済業者のEOAアドレス
function getOrderAgent(uint256 _orderId)
public
view
returns(address)
{
return orderBook[_orderId].agent;
}
/// @notice 注文情報の参照(キャンセル済み状態)
/// @param _orderId 注文ID
/// @return キャンセル済み状態
function getOrderCanceled(uint256 _orderId)
public
view
returns(bool)
{
return orderBook[_orderId].canceled;
}
// -------------------------------------------------------------------
// 直近注文ID
// -------------------------------------------------------------------
// 直近注文ID
uint256 public latestOrderId = 0;
/// @notice 直近注文IDの更新
/// @dev 最新バージョンのExchangeコントラクトのみ実行が可能
/// @param _latestOrderId 直近注文ID
function setLatestOrderId(uint256 _latestOrderId)
public
onlyLatestVersion()
{
latestOrderId = _latestOrderId;
}
/// @notice 直近注文IDの参照
/// @return 直近注文ID
function getLatestOrderId()
public
view
returns (uint256)
{
return latestOrderId;
}
// -------------------------------------------------------------------
// 約定情報
// -------------------------------------------------------------------
// 約定情報
// orderId => agreementId => Agreement
mapping(uint256 => mapping(uint256 => OTCExchangeStorageModel.OTCAgreement)) public agreements;
/// @notice 約定情報の更新
/// @dev 最新バージョンのExchangeコントラクトのみ実行が可能
/// @param _orderId 注文ID
/// @param _agreementId 約定ID
/// @param _agreement 約定情報
function setAgreement(
uint256 _orderId, uint256 _agreementId,
OTCExchangeStorageModel.OTCAgreement memory _agreement
)
public
onlyLatestVersion()
{
agreements[_orderId][_agreementId] = _agreement;
}
/// @notice 約定情報の更新(約定相手EOAアドレス)
/// @dev 最新バージョンのExchangeコントラクトのみ実行が可能
/// @param _orderId 注文ID
/// @param _agreementId 約定ID
/// @param _counterpart 約定相手EOAアドレス
function setAgreementCounterpart(
uint256 _orderId,
uint256 _agreementId,
address _counterpart
)
public
onlyLatestVersion()
{
agreements[_orderId][_agreementId].counterpart = _counterpart;
}
/// @notice 約定情報の更新(約定数量)
/// @dev 最新バージョンのExchangeコントラクトのみ実行が可能
/// @param _orderId 注文ID
/// @param _agreementId 約定ID
/// @param _amount 約定数量
function setAgreementAmount(
uint256 _orderId,
uint256 _agreementId,
uint256 _amount
)
public
onlyLatestVersion()
{
agreements[_orderId][_agreementId].amount = _amount;
}
/// @notice 約定情報の更新(約定単価)
/// @dev 最新バージョンのExchangeコントラクトのみ実行が可能
/// @param _orderId 注文ID
/// @param _agreementId 約定ID
/// @param _price 約定単価
function setAgreementPrice(
uint256 _orderId,
uint256 _agreementId,
uint256 _price
)
public
onlyLatestVersion()
{
agreements[_orderId][_agreementId].price = _price;
}
/// @notice 約定情報の更新(キャンセル済み状態)
/// @dev 最新バージョンのExchangeコントラクトのみ実行が可能
/// @param _orderId 注文ID
/// @param _agreementId 約定ID
/// @param _canceled キャンセル済み状態
function setAgreementCanceled(
uint256 _orderId,
uint256 _agreementId,
bool _canceled
)
public
onlyLatestVersion()
{
agreements[_orderId][_agreementId].canceled = _canceled;
}
/// @notice 約定情報の更新(支払済状態)
/// @dev 最新バージョンのExchangeコントラクトのみ実行が可能
/// @param _orderId 注文ID
/// @param _agreementId 約定ID
/// @param _paid 支払済状態
function setAgreementPaid(
uint256 _orderId,
uint256 _agreementId,
bool _paid
)
public
onlyLatestVersion()
{
agreements[_orderId][_agreementId].paid = _paid;
}
/// @notice 約定情報の更新(有効期限)
/// @dev 最新バージョンのExchangeコントラクトのみ実行が可能
/// @param _orderId 注文ID
/// @param _agreementId 約定ID
/// @param _expiry 有効期限
function setAgreementExpiry(
uint256 _orderId,
uint256 _agreementId,
uint256 _expiry
)
public
onlyLatestVersion()
{
agreements[_orderId][_agreementId].expiry = _expiry;
}
/// @notice 約定情報の参照
/// @param _orderId 注文ID
/// @param _agreementId 約定ID
/// @return 約定情報
function getAgreement(uint256 _orderId, uint256 _agreementId)
public
view
returns (OTCExchangeStorageModel.OTCAgreement memory)
{
return agreements[_orderId][_agreementId];
}
/// @notice 約定情報の参照(約定相手EOAアドレス)
/// @param _orderId 注文ID
/// @param _agreementId 約定ID
/// @return 約定相手EOAアドレス
function getAgreementCounterpart(uint256 _orderId, uint256 _agreementId)
public
view
returns(address)
{
return agreements[_orderId][_agreementId].counterpart;
}
/// @notice 約定情報の参照(約定数量)
/// @param _orderId 注文ID
/// @param _agreementId 約定ID
/// @return 約定数量
function getAgreementAmount(uint256 _orderId, uint256 _agreementId)
public
view
returns(uint256)
{
return agreements[_orderId][_agreementId].amount;
}
/// @notice 約定情報の参照(約定単価)
/// @param _orderId 注文ID
/// @param _agreementId 約定ID
/// @return 約定単価
function getAgreementPrice(uint256 _orderId, uint256 _agreementId)
public
view
returns(uint256)
{
return agreements[_orderId][_agreementId].price;
}
/// @notice 約定情報の参照(キャンセル済み状態)
/// @param _orderId 注文ID
/// @param _agreementId 約定ID
/// @return キャンセル済み状態
function getAgreementCanceled(uint256 _orderId, uint256 _agreementId)
public
view
returns(bool)
{
return agreements[_orderId][_agreementId].canceled;
}
/// @notice 約定情報の参照(支払済状態)
/// @param _orderId 注文ID
/// @param _agreementId 約定ID
/// @return 支払済状態
function getAgreementPaid(uint256 _orderId, uint256 _agreementId)
public
view
returns(bool)
{
return agreements[_orderId][_agreementId].paid;
}
/// @notice 約定情報の参照(有効期限)
/// @param _orderId 注文ID
/// @param _agreementId 約定ID
/// @return 有効期限
function getAgreementExpiry(uint256 _orderId, uint256 _agreementId)
public
view
returns(uint256)
{
return agreements[_orderId][_agreementId].expiry;
}
// -------------------------------------------------------------------
// 直近約定ID
///-------------------------------------------------------------------
// 直近約定ID
// orderId => latestAgreementId
mapping(uint256 => uint256) public latestAgreementIds;
/// @notice 直近約定IDの更新
/// @dev 最新バージョンのExchangeコントラクトのみ実行が可能
/// @param _orderId 注文ID
/// @param _latestAgreementId 直近約定ID
function setLatestAgreementId(uint256 _orderId, uint256 _latestAgreementId)
public
onlyLatestVersion()
{
latestAgreementIds[_orderId] = _latestAgreementId;
}
/// @notice 直近約定IDの参照
/// @param _orderId 注文ID
/// @return 直近約定ID
function getLatestAgreementId(uint256 _orderId)
public
view
returns (uint256)
{
return latestAgreementIds[_orderId];
}
}
| 約定情報の参照(約定単価) _orderId 注文ID _agreementId 約定ID return 約定単価 | function getAgreementPrice(uint256 _orderId, uint256 _agreementId)
public
view
returns(uint256)
{
return agreements[_orderId][_agreementId].price;
}
| 2,574,578 |
./partial_match/1/0x1A963Df363D01EEBB2816b366d61C917F20e1EbE/sources/src/ComptrollerG7.sol | Calculate number of tokens of collateral asset to seize given an underlying amount Used in liquidation (called in cToken.liquidateBorrowFresh) cTokenBorrowed The address of the borrowed cToken cTokenCollateral The address of the collateral cToken actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation)/ Read oracle prices for borrowed and collateral markets / | function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint256 actualRepayAmount
)
external
view
override
returns (uint256, uint256)
{
uint256 priceBorrowedMantissa =
oracle.getUnderlyingPrice(CToken(cTokenBorrowed));
uint256 priceCollateralMantissa =
oracle.getUnderlyingPrice(CToken(cTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint256(Error.PRICE_ERROR), 0);
}
uint256 seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
numerator = mul_(
);
denominator = mul_(
);
ratio = div_(numerator, denominator);
seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount);
return (uint256(Error.NO_ERROR), seizeTokens);
}
| 2,595,075 |
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "./IERC721Receiver.sol";
import "./Pausable.sol";
import "./Squuid.sol";
import "./SQUID.sol";
import "./ReentrancyGuard.sol";
contract Arena is Ownable, IERC721Receiver, Pausable {
// maximum alpha score for a Guard
uint8 public constant MAX_ALPHA = 8;
// struct to store a stake's token, owner, and earning values
struct Stake {
uint16 tokenId;
uint80 value;
address owner;
}
event TokenStaked(address owner, uint256 tokenId, uint256 value);
event PlayerClaimed(uint256 tokenId, uint256 earned, bool unstaked);
event GuardClaimed(uint256 tokenId, uint256 earned, bool unstaked);
// reference to the Squuid NFT contract
Squuid squuid;
// reference to the $SQUID contract for minting $SQUID earnings
SQUID squid;
// maps tokenId to stake
mapping(uint256 => Stake) public arena;
// maps alpha to all Guard stakes with that alpha
mapping(uint256 => Stake[]) public pack;
// tracks location of each Guard in Pack
mapping(uint256 => uint256) public packIndices;
// total alpha scores staked
uint256 public totalAlphaStaked = 0;
// any rewards distributed when no wolves are staked
uint256 public unaccountedRewards = 0;
// amount of $SQUID due for each alpha point staked
uint256 public squidPerAlpha = 0;
// player earn 10000 $SQUID per day
uint256 public constant DAILY_SQUID_RATE = 5000 ether;
// player must have 2 days worth of $SQUID to unstake or else it's too cold
uint256 public constant MINIMUM_TO_EXIT = 2 days;
// wolves take a 20% tax on all $SQUID claimed
uint256 public constant SQUID_CLAIM_TAX_PERCENTAGE = 20;
// there will only ever be (roughly) 2.4 billion $SQUID earned through staking
uint256 public constant MAXIMUM_GLOBAL_SQUID = 6000000000 ether;
// amount of $SQUID earned so far
uint256 public totalSquidEarned;
// number of Player staked in the Arena
uint256 public totalPlayerStaked;
// the last time $SQUID was claimed
uint256 public lastClaimTimestamp;
// emergency rescue to allow unstaking without any checks but without $SQUID
bool public rescueEnabled = false;
/**
* @param _squuid reference to the Squuid NFT contract
* @param _squid reference to the $SQUID token
*/
constructor(address _squuid, address _squid) {
squuid = Squuid(_squuid);
squid = SQUID(_squid);
}
/** STAKING */
/**
* adds Player and Wolves to the Arena and Pack
* @param account the address of the staker
* @param tokenIds the IDs of the Player and Wolves to stake
*/
function addManyToArenaAndPack(address account, uint16[] calldata tokenIds) external {
require(account == _msgSender() || _msgSender() == address(squuid), "DONT GIVE YOUR TOKENS AWAY");
for (uint i = 0; i < tokenIds.length; i++) {
if (_msgSender() != address(squuid)) { // dont do this step if its a mint + stake
require(squuid.ownerOf(tokenIds[i]) == _msgSender(), "AINT YO TOKEN");
squuid.transferFrom(_msgSender(), address(this), tokenIds[i]);
} else if (tokenIds[i] == 0) {
continue; // there may be gaps in the array for stolen tokens
}
if (isPlayer(tokenIds[i]))
_addPlayerToArena(account, tokenIds[i]);
else
_addGuardToPack(account, tokenIds[i]);
}
}
/**
* adds a single Player to the Arena
* @param account the address of the staker
* @param tokenId the ID of the Player to add to the Arena
*/
function _addPlayerToArena(address account, uint256 tokenId) internal whenNotPaused _updateEarnings {
arena[tokenId] = Stake({
owner: account,
tokenId: uint16(tokenId),
value: uint80(block.timestamp)
});
totalPlayerStaked += 1;
emit TokenStaked(account, tokenId, block.timestamp);
}
/**
* adds a single Guard to the Pack
* @param account the address of the staker
* @param tokenId the ID of the Guard to add to the Pack
*/
function _addGuardToPack(address account, uint256 tokenId) internal {
uint256 alpha = _alphaForGuard(tokenId);
totalAlphaStaked += alpha; // Portion of earnings ranges from 8 to 5
packIndices[tokenId] = pack[alpha].length; // Store the location of the guard in the Pack
pack[alpha].push(Stake({
owner: account,
tokenId: uint16(tokenId),
value: uint80(squidPerAlpha)
})); // Add the guard to the Pack
emit TokenStaked(account, tokenId, squidPerAlpha);
}
/** CLAIMING / UNSTAKING */
/**
* realize $SQUID earnings and optionally unstake tokens from the Arena / Pack
* to unstake a Player it will require it has 2 days worth of $SQUID unclaimed
* @param tokenIds the IDs of the tokens to claim earnings from
* @param unstake whether or not to unstake ALL of the tokens listed in tokenIds
*/
function claimManyFromArenaAndPack(uint16[] calldata tokenIds, bool unstake) external whenNotPaused _updateEarnings {
uint256 owed = 0;
for (uint i = 0; i < tokenIds.length; i++) {
if (isPlayer(tokenIds[i]))
owed += _claimPlayerFromArena(tokenIds[i], unstake);
else
owed += _claimGuardFromPack(tokenIds[i], unstake);
}
if (owed == 0) return;
squid.mint(_msgSender(), owed);
}
/**
* realize $SQUID earnings for a single Player and optionally unstake it
* if not unstaking, pay a 20% tax to the staked Wolves
* if unstaking, there is a 50% chance all $SQUID is stolen
* @param tokenId the ID of the Player to claim earnings from
* @param unstake whether or not to unstake the Player
* @return owed - the amount of $SQUID earned
*/
function _claimPlayerFromArena(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
Stake memory stake = arena[tokenId];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
require(!(unstake && block.timestamp - stake.value < MINIMUM_TO_EXIT), "GONNA BE COLD WITHOUT TWO DAY'S SQUID");
if (totalSquidEarned < MAXIMUM_GLOBAL_SQUID) {
owed = (block.timestamp - stake.value) * DAILY_SQUID_RATE / 1 days;
} else if (stake.value > lastClaimTimestamp) {
owed = 0; // $SQUID production stopped already
} else {
owed = (lastClaimTimestamp - stake.value) * DAILY_SQUID_RATE / 1 days; // stop earning additional $SQUID if it's all been earned
}
if (unstake) {
if (random(tokenId) & 1 == 1) { // 50% chance of all $SQUID stolen
_payGuardTax(owed);
owed = 0;
}
delete arena[tokenId];
squuid.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Player
totalPlayerStaked -= 1;
} else {
_payGuardTax(owed * SQUID_CLAIM_TAX_PERCENTAGE / 100); // percentage tax to staked wolves
owed = owed * (100 - SQUID_CLAIM_TAX_PERCENTAGE) / 100; // remainder goes to Player owner
arena[tokenId] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(block.timestamp)
}); // reset stake
}
emit PlayerClaimed(tokenId, owed, unstake);
}
/**
* realize $SQUID earnings for a single Guard and optionally unstake it
* Wolves earn $SQUID proportional to their Alpha rank
* @param tokenId the ID of the Guard to claim earnings from
* @param unstake whether or not to unstake the Guard
* @return owed - the amount of $SQUID earned
*/
function _claimGuardFromPack(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
require(squuid.ownerOf(tokenId) == address(this), "AINT A PART OF THE PACK");
uint256 alpha = _alphaForGuard(tokenId);
Stake memory stake = pack[alpha][packIndices[tokenId]];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
owed = (alpha) * (squidPerAlpha - stake.value); // Calculate portion of tokens based on Alpha
if (unstake) {
totalAlphaStaked -= alpha; // Remove Alpha from total staked
Stake memory lastStake = pack[alpha][pack[alpha].length - 1];
pack[alpha][packIndices[tokenId]] = lastStake; // Shuffle last Guard to current position
packIndices[lastStake.tokenId] = packIndices[tokenId];
pack[alpha].pop(); // Remove duplicate
delete packIndices[tokenId]; // Delete old mapping
squuid.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // Send back Guard
} else {
pack[alpha][packIndices[tokenId]] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(squidPerAlpha)
}); // reset stake
}
emit GuardClaimed(tokenId, owed, unstake);
}
/**
* emergency unstake tokens
* @param tokenIds the IDs of the tokens to claim earnings from
*/
function rescue(uint256[] calldata tokenIds) external {
require(rescueEnabled, "RESCUE DISABLED");
uint256 tokenId;
Stake memory stake;
Stake memory lastStake;
uint256 alpha;
for (uint i = 0; i < tokenIds.length; i++) {
tokenId = tokenIds[i];
if (isPlayer(tokenId)) {
stake = arena[tokenId];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
delete arena[tokenId];
squuid.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // send back Player
totalPlayerStaked -= 1;
emit PlayerClaimed(tokenId, 0, true);
} else {
alpha = _alphaForGuard(tokenId);
stake = pack[alpha][packIndices[tokenId]];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
totalAlphaStaked -= alpha; // Remove Alpha from total staked
lastStake = pack[alpha][pack[alpha].length - 1];
pack[alpha][packIndices[tokenId]] = lastStake; // Shuffle last Guard to current position
packIndices[lastStake.tokenId] = packIndices[tokenId];
pack[alpha].pop(); // Remove duplicate
delete packIndices[tokenId]; // Delete old mapping
squuid.safeTransferFrom(address(this), _msgSender(), tokenId, ""); // Send back Guard
emit GuardClaimed(tokenId, 0, true);
}
}
}
/** ACCOUNTING */
/**
* add $SQUID to claimable pot for the Pack
* @param amount $SQUID to add to the pot
*/
function _payGuardTax(uint256 amount) internal {
if (totalAlphaStaked == 0) { // if there's no staked wolves
unaccountedRewards += amount; // keep track of $SQUID due to wolves
return;
}
// makes sure to include any unaccounted $SQUID
squidPerAlpha += (amount + unaccountedRewards) / totalAlphaStaked;
unaccountedRewards = 0;
}
/**
* tracks $SQUID earnings to ensure it stops once 2.4 billion is eclipsed
*/
modifier _updateEarnings() {
if (totalSquidEarned < MAXIMUM_GLOBAL_SQUID) {
totalSquidEarned +=
(block.timestamp - lastClaimTimestamp)
* totalPlayerStaked
* DAILY_SQUID_RATE / 1 days;
lastClaimTimestamp = block.timestamp;
}
_;
}
/** ADMIN */
/**
* allows owner to enable "rescue mode"
* simplifies accounting, prioritizes tokens out in emergency
*/
function setRescueEnabled(bool _enabled) external onlyOwner {
rescueEnabled = _enabled;
}
/**
* enables owner to pause / unpause minting
*/
function setPaused(bool _paused) external onlyOwner {
if (_paused) _pause();
else _unpause();
}
/** READ ONLY */
/**
* checks if a token is a Player
* @param tokenId the ID of the token to check
* @return player - whether or not a token is a Player
*/
function isPlayer(uint256 tokenId) public view returns (bool player) {
(player, , , , , , , , , ) = squuid.tokenTraits(tokenId);
}
/**
* gets the alpha score for a Guard
* @param tokenId the ID of the Guard to get the alpha score for
* @return the alpha score of the Guard (5-8)
*/
function _alphaForGuard(uint256 tokenId) internal view returns (uint8) {
( , , , , , , , , , uint8 alphaIndex) = squuid.tokenTraits(tokenId);
return MAX_ALPHA - alphaIndex; // alpha index is 0-3
}
/**
* chooses a random Guard thief when a newly minted token is stolen
* @param seed a random value to choose a Guard from
* @return the owner of the randomly selected Guard thief
*/
function randomGuardOwner(uint256 seed) external view returns (address) {
if (totalAlphaStaked == 0) return address(0x0);
uint256 bucket = (seed & 0xFFFFFFFF) % totalAlphaStaked; // choose a value from 0 to total alpha staked
uint256 cumulative;
seed >>= 32;
// loop through each bucket of Wolves with the same alpha score
for (uint i = MAX_ALPHA - 3; i <= MAX_ALPHA; i++) {
cumulative += pack[i].length * i;
// if the value is not inside of that bucket, keep going
if (bucket >= cumulative) continue;
// get the address of a random Guard with that alpha score
return pack[i][seed % pack[i].length].owner;
}
return address(0x0);
}
/**
* generates a pseudorandom number
* @param seed a value ensure different outcomes for different sources in the same block
* @return a pseudorandom value
*/
function random(uint256 seed) internal view returns (uint256) {
return uint256(keccak256(abi.encodePacked(
tx.origin,
blockhash(block.number - 1),
block.timestamp,
seed
)));
}
function onERC721Received(
address,
address from,
uint256,
bytes calldata
) external pure override returns (bytes4) {
require(from == address(0x0), "Cannot send tokens to Arena directly");
return IERC721Receiver.onERC721Received.selector;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "./ERC20.sol";
import "./Ownable.sol";
contract SQUID is ERC20, Ownable {
// a mapping from an address to whether or not it can mint / burn
mapping(address => bool) controllers;
constructor() ERC20("SQUID", "SQUID") { }
/**
* mints $SQUID to a recipient
* @param to the recipient of the $SQUID
* @param amount the amount of $SQUID to mint
*/
function mint(address to, uint256 amount) external {
require(controllers[msg.sender], "Only controllers can mint");
_mint(to, amount);
}
/**
* burns $SQUID from a holder
* @param from the holder of the $SQUID
* @param amount the amount of $SQUID to burn
*/
function burn(address from, uint256 amount) external {
require(controllers[msg.sender], "Only controllers can burn");
_burn(from, amount);
}
/**
* enables an address to mint / burn
* @param controller the address to enable
*/
function addController(address controller) external onlyOwner {
controllers[controller] = true;
}
/**
* disables an address from minting / burning
* @param controller the address to disbale
*/
function removeController(address controller) external onlyOwner {
controllers[controller] = false;
}
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
import "./Ownable.sol";
import "./Pausable.sol";
import "./ERC721Enumerable.sol";
import "./ISquuid.sol";
import "./IArena.sol";
import "./ITraits.sol";
import "./SQUID.sol";
import "./ReentrancyGuard.sol";
contract Squuid is ISquuid, ERC721Enumerable, Ownable, Pausable {
// mint price
uint256 public constant WL_MINT_PRICE = .0456 ether;
uint256 public constant MINT_PRICE = .06942 ether;
// max number of tokens that can be minted - 50000 in production
uint256 public immutable MAX_TOKENS;
// number of tokens that can be claimed for free - 20% of MAX_TOKENS
uint256 public PAID_TOKENS;
// number of tokens have been minted so far
uint16 public minted;
//For Whitelist
mapping(address => uint256) public whiteList;
//Keep track of data
mapping(uint256 => PlayerGuard) public _idData;
// mapping from tokenId to a struct containing the token's traits
mapping(uint256 => PlayerGuard) public tokenTraits;
// mapping from hashed(tokenTrait) to the tokenId it's associated with
// used to ensure there are no duplicates
mapping(uint256 => uint256) public existingCombinations;
// list of probabilities for each trait type
// 0 - 9 are associated with Player, 10 - 18 are associated with Wolves
uint8[][18] public rarities;
// list of aliases for Walker's Alias algorithm
// 0 - 9 are associated with Player, 10 - 18 are associated with Wolves
uint8[][18] public aliases;
// reference to the Arena for choosing random Guard thieves
IArena public arena;
// reference to $SQUID for burning on mint
SQUID public squid;
// reference to Traits
ITraits public traits;
/**
* instantiates contract and rarity tables
*/
constructor(address _squid, address _traits, uint256 _maxTokens) ERC721("Squid Game", 'SGAME') {
squid = SQUID(_squid);
traits = ITraits(_traits);
MAX_TOKENS = _maxTokens;
PAID_TOKENS = _maxTokens / 5;
// I know this looks weird but it saves users gas by making lookup O(1)
// A.J. Walker's Alias Algorithm
// player
// colors
rarities[0] = [15, 50, 200, 250, 255];
aliases[0] = [4, 4, 4, 4, 4];
// head
rarities[1] = [190, 215, 240, 100, 110, 135, 160, 185, 80, 210, 235, 240, 80, 80, 100, 100, 100, 245, 250, 255];
aliases[1] = [1, 2, 4, 0, 5, 6, 7, 9, 0, 10, 11, 17, 0, 0, 0, 0, 4, 18, 19, 19];
// numbers
rarities[2] = [255, 30, 60, 60, 150, 156];
aliases[2] = [0, 0, 0, 0, 0, 0];
// shapes
rarities[3] = [221, 100, 181, 140, 224, 147, 84, 228, 140, 224, 250, 160, 241, 207, 173, 84, 254, 220, 196, 140, 168, 252, 140, 183, 236, 252, 224, 255];
aliases[3] = [1, 2, 5, 0, 1, 7, 1, 10, 5, 10, 11, 12, 13, 14, 16, 11, 17, 23, 13, 14, 17, 23, 23, 24, 27, 27, 27, 27];
// nose
rarities[4] = [175, 100, 40, 250, 115, 100, 185, 175, 180, 255];
aliases[4] = [3, 0, 4, 6, 6, 7, 8, 8, 9, 9];
// accessories
rarities[5] = [80, 225, 227, 228, 112, 240, 64, 160, 167, 217, 171, 64, 240, 126, 80, 255];
aliases[5] = [1, 2, 3, 8, 2, 8, 8, 9, 9, 10, 13, 10, 13, 15, 13, 15];
// guns
rarities[6] = [255];
aliases[6] = [0];
// feet
rarities[7] = [243, 189, 133, 133, 57, 95, 152, 135, 133, 57, 222, 168, 57, 57, 38, 114, 114, 114, 255];
aliases[7] = [1, 7, 0, 0, 0, 0, 0, 10, 0, 0, 11, 18, 0, 0, 0, 1, 7, 11, 18];
// alphaIndex
rarities[8] = [255];
aliases[8] = [0];
// wolves
// colors
rarities[9] = [210, 90, 9, 9, 9, 150, 9, 255, 9];
aliases[9] = [5, 0, 0, 5, 5, 7, 5, 7, 5];
// head
rarities[10] = [255];
aliases[10] = [0];
// numbers
rarities[11] = [255];
aliases[11] = [0];
// shapes
rarities[12] = [135, 177, 219, 141, 183, 225, 147, 189, 231, 135, 135, 135, 135, 246, 150, 150, 156, 165, 171, 180, 186, 195, 201, 210, 243, 252, 255];
aliases[12] = [1, 2, 3, 4, 5, 6, 7, 8, 13, 3, 6, 14, 15, 16, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 26, 26];
// nose
rarities[13] = [255];
aliases[13] = [0];
// accessories
rarities[14] = [239, 244, 249, 234, 234, 234, 234, 234, 234, 234, 130, 255, 247];
aliases[14] = [1, 2, 11, 0, 11, 11, 11, 11, 11, 11, 11, 11, 11];
// guns
rarities[15] = [75, 180, 165, 120, 60, 150, 105, 195, 45, 225, 75, 45, 195, 120, 255];
aliases[15] = [1, 9, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 14, 12, 14];
// feet
rarities[16] = [255];
aliases[16] = [0];
// alphaIndex
rarities[17] = [8, 160, 73, 255];
aliases[17] = [2, 3, 3, 3];
}
/** EXTERNAL */
/**
* mint a token - 90% Player, 10% Wolves
* The first 20% are free to claim, the remaining cost $SQUID
*/
function mint(uint256 amount, bool stake) external payable whenNotPaused {
require(tx.origin == _msgSender(), "Only EOA");
require(minted + amount <= MAX_TOKENS, "All tokens minted");
require(amount > 0 && amount <= 10, "Invalid mint amount");
if (minted < PAID_TOKENS) {
require(minted + amount <= PAID_TOKENS, "All tokens on-sale already sold");
require(amount * MINT_PRICE == msg.value, "Invalid payment amount");
} else {
require(msg.value == 0);
}
uint256 totalSquidCost = 0;
uint16[] memory tokenIds = stake ? new uint16[](amount) : new uint16[](0);
uint256 seed;
for (uint i = 0; i < amount; i++) {
minted++;
seed = random(minted);
generate(minted, seed);
address recipient = selectRecipient(seed);
if (!stake || recipient != _msgSender()) {
_safeMint(recipient, minted);
} else {
_safeMint(address(arena), minted);
tokenIds[i] = minted;
}
totalSquidCost += mintCost(minted);
}
if (totalSquidCost > 0) squid.burn(_msgSender(), totalSquidCost);
if (stake) arena.addManyToArenaAndPack(_msgSender(), tokenIds);
}
function mintWhitelist(uint256 amount, address _wallet, bool stake) external payable whenNotPaused {
require(tx.origin == _msgSender(), "Only EOA");
require(minted + amount <= MAX_TOKENS, "All tokens minted");
require(amount > 0 && amount <= 5, "Invalid mint amount");
require(whiteList[_msgSender()] >= amount, "Invalid Whitelist Amount");
require(amount * WL_MINT_PRICE == msg.value, "Invalid payment amount");
whiteList[_msgSender()] = whiteList[_msgSender()] - amount;
uint16[] memory tokenIds = stake ? new uint16[](amount) : new uint16[](0);
uint256 seed;
for (uint i = 0; i < amount; i++) {
minted++;
seed = random(minted);
_idData[minted] = generate(minted, seed);
if (!stake) {
_mint(_wallet, minted);
} else {
_mint(address(arena), minted);
tokenIds[i] = minted;
}
}
if (stake) arena.addManyToArenaAndPack(_msgSender(), tokenIds);
}
/**
* the first 20% are paid in ETH
* the next 20% are 20000 $SQUID
* the next 40% are 40000 $SQUID
* the final 20% are 80000 $SQUID
* @param tokenId the ID to check the cost of to mint
* @return the cost of the given token ID
*/
function mintCost(uint256 tokenId) public view returns (uint256) {
if (tokenId <= PAID_TOKENS) return 0;
if (tokenId <= MAX_TOKENS * 2 / 5) return 25000 ether; // XXX
if (tokenId <= MAX_TOKENS * 3 / 5) return 75000 ether; // XXX
if (tokenId <= MAX_TOKENS * 4 / 5) return 125000 ether; // XXX
if (tokenId <= MAX_TOKENS * 9 / 10) return 250000 ether; // XXX
return 500000 ether; // XXX
}
function totalMint() public view returns (uint16) {
return minted;
} // XXX
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
// Hardcode the Arena's approval so that users don't have to waste gas approving
if (_msgSender() != address(arena))
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/** INTERNAL */
/**
* generates traits for a specific token, checking to make sure it's unique
* @param tokenId the id of the token to generate traits for
* @param seed a pseudorandom 256 bit number to derive traits from
* @return t - a struct of traits for the given token ID
*/
function generate(uint256 tokenId, uint256 seed) internal returns (PlayerGuard memory t) {
t = selectTraits(seed);
if (existingCombinations[structToHash(t)] == 0) {
tokenTraits[tokenId] = t;
existingCombinations[structToHash(t)] = tokenId;
return t;
}
return generate(tokenId, random(seed));
}
/**
* uses A.J. Walker's Alias algorithm for O(1) rarity table lookup
* ensuring O(1) instead of O(n) reduces mint cost by more than 50%
* probability & alias tables are generated off-chain beforehand
* @param seed portion of the 256 bit seed to remove trait correlation
* @param traitType the trait type to select a trait for
* @return the ID of the randomly selected trait
*/
function selectTrait(uint16 seed, uint8 traitType) internal view returns (uint8) {
uint8 trait = uint8(seed) % uint8(rarities[traitType].length);
if (seed >> 8 < rarities[traitType][trait]) return trait;
return aliases[traitType][trait];
}
/**
* the first 20% (ETH purchases) go to the minter
* the remaining 80% have a 10% chance to be given to a random staked guard
* @param seed a random value to select a recipient from
* @return the address of the recipient (either the minter or the Guard thief's owner)
*/
function selectRecipient(uint256 seed) internal view returns (address) {
if (minted <= PAID_TOKENS || ((seed >> 245) % 10) != 0) return _msgSender(); // top 10 bits haven't been used
address thief = arena.randomGuardOwner(seed >> 144); // 144 bits reserved for trait selection
if (thief == address(0x0)) return _msgSender();
return thief;
}
/**
* selects the species and all of its traits based on the seed value
* @param seed a pseudorandom 256 bit number to derive traits from
* @return t - a struct of randomly selected traits
*/
function selectTraits(uint256 seed) internal view returns (PlayerGuard memory t) {
t.isPlayer = (seed & 0xFFFF) % 10 != 0;
uint8 shift = t.isPlayer ? 0 : 9;
seed >>= 16;
t.colors = selectTrait(uint16(seed & 0xFFFF), 0 + shift);
seed >>= 16;
t.head = selectTrait(uint16(seed & 0xFFFF), 1 + shift);
seed >>= 16;
t.numbers = selectTrait(uint16(seed & 0xFFFF), 2 + shift);
seed >>= 16;
t.shapes = selectTrait(uint16(seed & 0xFFFF), 3 + shift);
seed >>= 16;
t.nose = selectTrait(uint16(seed & 0xFFFF), 4 + shift);
seed >>= 16;
t.accessories = selectTrait(uint16(seed & 0xFFFF), 5 + shift);
seed >>= 16;
t.guns = selectTrait(uint16(seed & 0xFFFF), 6 + shift);
seed >>= 16;
t.feet = selectTrait(uint16(seed & 0xFFFF), 7 + shift);
seed >>= 16;
t.alphaIndex = selectTrait(uint16(seed & 0xFFFF), 8 + shift);
}
/**
* converts a struct to a 256 bit hash to check for uniqueness
* @param s the struct to pack into a hash
* @return the 256 bit hash of the struct
*/
function structToHash(PlayerGuard memory s) internal pure returns (uint256) {
return uint256(bytes32(
abi.encodePacked(
s.isPlayer,
s.colors,
s.head,
s.shapes,
s.accessories,
s.guns,
s.numbers,
s.feet,
s.alphaIndex
)
));
}
/**
* generates a pseudorandom number
* @param seed a value ensure different outcomes for different sources in the same block
* @return a pseudorandom value
*/
function random(uint256 seed) internal view returns (uint256) {
return uint256(keccak256(abi.encodePacked(
tx.origin,
blockhash(block.number - 1),
block.timestamp,
seed
)));
}
/** READ */
function getTokenTraits(uint256 tokenId) external view override returns (PlayerGuard memory) {
return tokenTraits[tokenId];
}
function getPaidTokens() external view override returns (uint256) {
return PAID_TOKENS;
}
/** ADMIN */
function addToWhitelist(address[] memory toWhitelist) external onlyOwner {
for(uint256 i = 0; i < toWhitelist.length; i++){
address idToWhitelist = toWhitelist[i];
whiteList[idToWhitelist] = 3;
}
}
/**
* called after deployment so that the contract can get random guard thieves
* @param _arena the address of the Arena
*/
function setArena(address _arena) external onlyOwner {
arena = IArena(_arena);
}
/**
* allows owner to withdraw funds from minting
*/
function withdraw() external onlyOwner {
payable(owner()).transfer(address(this).balance);
}
/**
* updates the number of tokens for sale
*/
function setPaidTokens(uint256 _paidTokens) external onlyOwner {
PAID_TOKENS = _paidTokens;
}
/**
* enables owner to pause / unpause minting
*/
function setPaused(bool _paused) external onlyOwner {
if (_paused) _pause();
else _unpause();
}
/** RENDER */
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return traits.tokenURI(tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.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 LICENSE
pragma solidity ^0.8.0;
interface ITraits {
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface IArena {
function addManyToArenaAndPack(address account, uint16[] calldata tokenIds) external;
function randomGuardOwner(uint256 seed) external view returns (address);
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.0;
interface ISquuid {
// struct to store each token's traits
struct PlayerGuard {
bool isPlayer;
uint8 colors;
uint8 head;
uint8 numbers;
uint8 shapes;
uint8 nose;
uint8 accessories;
uint8 guns;
uint8 feet;
uint8 alphaIndex;
}
function getPaidTokens() external view returns (uint256);
function getTokenTraits(uint256 tokenId) external view returns (PlayerGuard memory);
}
// 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 "./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 "./IERC20.sol";
import "./IERC20Metadata.sol";
import "./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 Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `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 {}
}
// 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 "./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 "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./IERC721Metadata.sol";
import "./Address.sol";
import "./Context.sol";
import "./Strings.sol";
import "./ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./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;
/**
* @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 "./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;
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 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;
/**
* @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
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 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);
} | adds a single Guard to the Pack account the address of the staker tokenId the ID of the Guard to add to the Pack/ | function _addGuardToPack(address account, uint256 tokenId) internal {
uint256 alpha = _alphaForGuard(tokenId);
pack[alpha].push(Stake({
owner: account,
tokenId: uint16(tokenId),
value: uint80(squidPerAlpha)
emit TokenStaked(account, tokenId, squidPerAlpha);
}
function claimManyFromArenaAndPack(uint16[] calldata tokenIds, bool unstake) external whenNotPaused _updateEarnings {
uint256 owed = 0;
for (uint i = 0; i < tokenIds.length; i++) {
if (isPlayer(tokenIds[i]))
owed += _claimPlayerFromArena(tokenIds[i], unstake);
else
owed += _claimGuardFromPack(tokenIds[i], unstake);
}
if (owed == 0) return;
squid.mint(_msgSender(), owed);
}
function claimManyFromArenaAndPack(uint16[] calldata tokenIds, bool unstake) external whenNotPaused _updateEarnings {
uint256 owed = 0;
for (uint i = 0; i < tokenIds.length; i++) {
if (isPlayer(tokenIds[i]))
owed += _claimPlayerFromArena(tokenIds[i], unstake);
else
owed += _claimGuardFromPack(tokenIds[i], unstake);
}
if (owed == 0) return;
squid.mint(_msgSender(), owed);
}
function _claimPlayerFromArena(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
Stake memory stake = arena[tokenId];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
require(!(unstake && block.timestamp - stake.value < MINIMUM_TO_EXIT), "GONNA BE COLD WITHOUT TWO DAY'S SQUID");
if (totalSquidEarned < MAXIMUM_GLOBAL_SQUID) {
owed = (block.timestamp - stake.value) * DAILY_SQUID_RATE / 1 days;
}
if (unstake) {
_payGuardTax(owed);
owed = 0;
}
delete arena[tokenId];
totalPlayerStaked -= 1;
arena[tokenId] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(block.timestamp)
}
emit PlayerClaimed(tokenId, owed, unstake);
}
function _claimPlayerFromArena(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
Stake memory stake = arena[tokenId];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
require(!(unstake && block.timestamp - stake.value < MINIMUM_TO_EXIT), "GONNA BE COLD WITHOUT TWO DAY'S SQUID");
if (totalSquidEarned < MAXIMUM_GLOBAL_SQUID) {
owed = (block.timestamp - stake.value) * DAILY_SQUID_RATE / 1 days;
}
if (unstake) {
_payGuardTax(owed);
owed = 0;
}
delete arena[tokenId];
totalPlayerStaked -= 1;
arena[tokenId] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(block.timestamp)
}
emit PlayerClaimed(tokenId, owed, unstake);
}
} else if (stake.value > lastClaimTimestamp) {
} else {
function _claimPlayerFromArena(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
Stake memory stake = arena[tokenId];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
require(!(unstake && block.timestamp - stake.value < MINIMUM_TO_EXIT), "GONNA BE COLD WITHOUT TWO DAY'S SQUID");
if (totalSquidEarned < MAXIMUM_GLOBAL_SQUID) {
owed = (block.timestamp - stake.value) * DAILY_SQUID_RATE / 1 days;
}
if (unstake) {
_payGuardTax(owed);
owed = 0;
}
delete arena[tokenId];
totalPlayerStaked -= 1;
arena[tokenId] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(block.timestamp)
}
emit PlayerClaimed(tokenId, owed, unstake);
}
} else {
function _claimPlayerFromArena(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
Stake memory stake = arena[tokenId];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
require(!(unstake && block.timestamp - stake.value < MINIMUM_TO_EXIT), "GONNA BE COLD WITHOUT TWO DAY'S SQUID");
if (totalSquidEarned < MAXIMUM_GLOBAL_SQUID) {
owed = (block.timestamp - stake.value) * DAILY_SQUID_RATE / 1 days;
}
if (unstake) {
_payGuardTax(owed);
owed = 0;
}
delete arena[tokenId];
totalPlayerStaked -= 1;
arena[tokenId] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(block.timestamp)
}
emit PlayerClaimed(tokenId, owed, unstake);
}
function _claimGuardFromPack(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
require(squuid.ownerOf(tokenId) == address(this), "AINT A PART OF THE PACK");
uint256 alpha = _alphaForGuard(tokenId);
Stake memory stake = pack[alpha][packIndices[tokenId]];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
if (unstake) {
Stake memory lastStake = pack[alpha][pack[alpha].length - 1];
packIndices[lastStake.tokenId] = packIndices[tokenId];
pack[alpha][packIndices[tokenId]] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(squidPerAlpha)
}
emit GuardClaimed(tokenId, owed, unstake);
}
function rescue(uint256[] calldata tokenIds) external {
require(rescueEnabled, "RESCUE DISABLED");
uint256 tokenId;
Stake memory stake;
Stake memory lastStake;
uint256 alpha;
for (uint i = 0; i < tokenIds.length; i++) {
tokenId = tokenIds[i];
if (isPlayer(tokenId)) {
stake = arena[tokenId];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
delete arena[tokenId];
totalPlayerStaked -= 1;
emit PlayerClaimed(tokenId, 0, true);
alpha = _alphaForGuard(tokenId);
stake = pack[alpha][packIndices[tokenId]];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
lastStake = pack[alpha][pack[alpha].length - 1];
packIndices[lastStake.tokenId] = packIndices[tokenId];
emit GuardClaimed(tokenId, 0, true);
}
}
}
function _payGuardTax(uint256 amount) internal {
return;
}
unaccountedRewards = 0;
}
function _claimGuardFromPack(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
require(squuid.ownerOf(tokenId) == address(this), "AINT A PART OF THE PACK");
uint256 alpha = _alphaForGuard(tokenId);
Stake memory stake = pack[alpha][packIndices[tokenId]];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
if (unstake) {
Stake memory lastStake = pack[alpha][pack[alpha].length - 1];
packIndices[lastStake.tokenId] = packIndices[tokenId];
pack[alpha][packIndices[tokenId]] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(squidPerAlpha)
}
emit GuardClaimed(tokenId, owed, unstake);
}
function rescue(uint256[] calldata tokenIds) external {
require(rescueEnabled, "RESCUE DISABLED");
uint256 tokenId;
Stake memory stake;
Stake memory lastStake;
uint256 alpha;
for (uint i = 0; i < tokenIds.length; i++) {
tokenId = tokenIds[i];
if (isPlayer(tokenId)) {
stake = arena[tokenId];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
delete arena[tokenId];
totalPlayerStaked -= 1;
emit PlayerClaimed(tokenId, 0, true);
alpha = _alphaForGuard(tokenId);
stake = pack[alpha][packIndices[tokenId]];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
lastStake = pack[alpha][pack[alpha].length - 1];
packIndices[lastStake.tokenId] = packIndices[tokenId];
emit GuardClaimed(tokenId, 0, true);
}
}
}
function _payGuardTax(uint256 amount) internal {
return;
}
unaccountedRewards = 0;
}
} else {
function _claimGuardFromPack(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
require(squuid.ownerOf(tokenId) == address(this), "AINT A PART OF THE PACK");
uint256 alpha = _alphaForGuard(tokenId);
Stake memory stake = pack[alpha][packIndices[tokenId]];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
if (unstake) {
Stake memory lastStake = pack[alpha][pack[alpha].length - 1];
packIndices[lastStake.tokenId] = packIndices[tokenId];
pack[alpha][packIndices[tokenId]] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(squidPerAlpha)
}
emit GuardClaimed(tokenId, owed, unstake);
}
function rescue(uint256[] calldata tokenIds) external {
require(rescueEnabled, "RESCUE DISABLED");
uint256 tokenId;
Stake memory stake;
Stake memory lastStake;
uint256 alpha;
for (uint i = 0; i < tokenIds.length; i++) {
tokenId = tokenIds[i];
if (isPlayer(tokenId)) {
stake = arena[tokenId];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
delete arena[tokenId];
totalPlayerStaked -= 1;
emit PlayerClaimed(tokenId, 0, true);
alpha = _alphaForGuard(tokenId);
stake = pack[alpha][packIndices[tokenId]];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
lastStake = pack[alpha][pack[alpha].length - 1];
packIndices[lastStake.tokenId] = packIndices[tokenId];
emit GuardClaimed(tokenId, 0, true);
}
}
}
function _payGuardTax(uint256 amount) internal {
return;
}
unaccountedRewards = 0;
}
function _claimGuardFromPack(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
require(squuid.ownerOf(tokenId) == address(this), "AINT A PART OF THE PACK");
uint256 alpha = _alphaForGuard(tokenId);
Stake memory stake = pack[alpha][packIndices[tokenId]];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
if (unstake) {
Stake memory lastStake = pack[alpha][pack[alpha].length - 1];
packIndices[lastStake.tokenId] = packIndices[tokenId];
pack[alpha][packIndices[tokenId]] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(squidPerAlpha)
}
emit GuardClaimed(tokenId, owed, unstake);
}
function rescue(uint256[] calldata tokenIds) external {
require(rescueEnabled, "RESCUE DISABLED");
uint256 tokenId;
Stake memory stake;
Stake memory lastStake;
uint256 alpha;
for (uint i = 0; i < tokenIds.length; i++) {
tokenId = tokenIds[i];
if (isPlayer(tokenId)) {
stake = arena[tokenId];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
delete arena[tokenId];
totalPlayerStaked -= 1;
emit PlayerClaimed(tokenId, 0, true);
alpha = _alphaForGuard(tokenId);
stake = pack[alpha][packIndices[tokenId]];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
lastStake = pack[alpha][pack[alpha].length - 1];
packIndices[lastStake.tokenId] = packIndices[tokenId];
emit GuardClaimed(tokenId, 0, true);
}
}
}
function _payGuardTax(uint256 amount) internal {
return;
}
unaccountedRewards = 0;
}
function _claimGuardFromPack(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
require(squuid.ownerOf(tokenId) == address(this), "AINT A PART OF THE PACK");
uint256 alpha = _alphaForGuard(tokenId);
Stake memory stake = pack[alpha][packIndices[tokenId]];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
if (unstake) {
Stake memory lastStake = pack[alpha][pack[alpha].length - 1];
packIndices[lastStake.tokenId] = packIndices[tokenId];
pack[alpha][packIndices[tokenId]] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(squidPerAlpha)
}
emit GuardClaimed(tokenId, owed, unstake);
}
function rescue(uint256[] calldata tokenIds) external {
require(rescueEnabled, "RESCUE DISABLED");
uint256 tokenId;
Stake memory stake;
Stake memory lastStake;
uint256 alpha;
for (uint i = 0; i < tokenIds.length; i++) {
tokenId = tokenIds[i];
if (isPlayer(tokenId)) {
stake = arena[tokenId];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
delete arena[tokenId];
totalPlayerStaked -= 1;
emit PlayerClaimed(tokenId, 0, true);
alpha = _alphaForGuard(tokenId);
stake = pack[alpha][packIndices[tokenId]];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
lastStake = pack[alpha][pack[alpha].length - 1];
packIndices[lastStake.tokenId] = packIndices[tokenId];
emit GuardClaimed(tokenId, 0, true);
}
}
}
function _payGuardTax(uint256 amount) internal {
return;
}
unaccountedRewards = 0;
}
function _claimGuardFromPack(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
require(squuid.ownerOf(tokenId) == address(this), "AINT A PART OF THE PACK");
uint256 alpha = _alphaForGuard(tokenId);
Stake memory stake = pack[alpha][packIndices[tokenId]];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
if (unstake) {
Stake memory lastStake = pack[alpha][pack[alpha].length - 1];
packIndices[lastStake.tokenId] = packIndices[tokenId];
pack[alpha][packIndices[tokenId]] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(squidPerAlpha)
}
emit GuardClaimed(tokenId, owed, unstake);
}
function rescue(uint256[] calldata tokenIds) external {
require(rescueEnabled, "RESCUE DISABLED");
uint256 tokenId;
Stake memory stake;
Stake memory lastStake;
uint256 alpha;
for (uint i = 0; i < tokenIds.length; i++) {
tokenId = tokenIds[i];
if (isPlayer(tokenId)) {
stake = arena[tokenId];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
delete arena[tokenId];
totalPlayerStaked -= 1;
emit PlayerClaimed(tokenId, 0, true);
alpha = _alphaForGuard(tokenId);
stake = pack[alpha][packIndices[tokenId]];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
lastStake = pack[alpha][pack[alpha].length - 1];
packIndices[lastStake.tokenId] = packIndices[tokenId];
emit GuardClaimed(tokenId, 0, true);
}
}
}
function _payGuardTax(uint256 amount) internal {
return;
}
unaccountedRewards = 0;
}
} else {
function _claimGuardFromPack(uint256 tokenId, bool unstake) internal returns (uint256 owed) {
require(squuid.ownerOf(tokenId) == address(this), "AINT A PART OF THE PACK");
uint256 alpha = _alphaForGuard(tokenId);
Stake memory stake = pack[alpha][packIndices[tokenId]];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
if (unstake) {
Stake memory lastStake = pack[alpha][pack[alpha].length - 1];
packIndices[lastStake.tokenId] = packIndices[tokenId];
pack[alpha][packIndices[tokenId]] = Stake({
owner: _msgSender(),
tokenId: uint16(tokenId),
value: uint80(squidPerAlpha)
}
emit GuardClaimed(tokenId, owed, unstake);
}
function rescue(uint256[] calldata tokenIds) external {
require(rescueEnabled, "RESCUE DISABLED");
uint256 tokenId;
Stake memory stake;
Stake memory lastStake;
uint256 alpha;
for (uint i = 0; i < tokenIds.length; i++) {
tokenId = tokenIds[i];
if (isPlayer(tokenId)) {
stake = arena[tokenId];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
delete arena[tokenId];
totalPlayerStaked -= 1;
emit PlayerClaimed(tokenId, 0, true);
alpha = _alphaForGuard(tokenId);
stake = pack[alpha][packIndices[tokenId]];
require(stake.owner == _msgSender(), "SWIPER, NO SWIPING");
lastStake = pack[alpha][pack[alpha].length - 1];
packIndices[lastStake.tokenId] = packIndices[tokenId];
emit GuardClaimed(tokenId, 0, true);
}
}
}
function _payGuardTax(uint256 amount) internal {
return;
}
unaccountedRewards = 0;
}
squidPerAlpha += (amount + unaccountedRewards) / totalAlphaStaked;
modifier _updateEarnings() {
if (totalSquidEarned < MAXIMUM_GLOBAL_SQUID) {
totalSquidEarned +=
(block.timestamp - lastClaimTimestamp)
* totalPlayerStaked
* DAILY_SQUID_RATE / 1 days;
lastClaimTimestamp = block.timestamp;
}
_;
}
modifier _updateEarnings() {
if (totalSquidEarned < MAXIMUM_GLOBAL_SQUID) {
totalSquidEarned +=
(block.timestamp - lastClaimTimestamp)
* totalPlayerStaked
* DAILY_SQUID_RATE / 1 days;
lastClaimTimestamp = block.timestamp;
}
_;
}
function setRescueEnabled(bool _enabled) external onlyOwner {
rescueEnabled = _enabled;
}
function setPaused(bool _paused) external onlyOwner {
if (_paused) _pause();
else _unpause();
}
function isPlayer(uint256 tokenId) public view returns (bool player) {
(player, , , , , , , , , ) = squuid.tokenTraits(tokenId);
}
function _alphaForGuard(uint256 tokenId) internal view returns (uint8) {
( , , , , , , , , , uint8 alphaIndex) = squuid.tokenTraits(tokenId);
}
function randomGuardOwner(uint256 seed) external view returns (address) {
if (totalAlphaStaked == 0) return address(0x0);
uint256 cumulative;
seed >>= 32;
for (uint i = MAX_ALPHA - 3; i <= MAX_ALPHA; i++) {
cumulative += pack[i].length * i;
if (bucket >= cumulative) continue;
return pack[i][seed % pack[i].length].owner;
}
return address(0x0);
}
function randomGuardOwner(uint256 seed) external view returns (address) {
if (totalAlphaStaked == 0) return address(0x0);
uint256 cumulative;
seed >>= 32;
for (uint i = MAX_ALPHA - 3; i <= MAX_ALPHA; i++) {
cumulative += pack[i].length * i;
if (bucket >= cumulative) continue;
return pack[i][seed % pack[i].length].owner;
}
return address(0x0);
}
function random(uint256 seed) internal view returns (uint256) {
return uint256(keccak256(abi.encodePacked(
tx.origin,
blockhash(block.number - 1),
block.timestamp,
seed
)));
}
function onERC721Received(
address,
address from,
uint256,
bytes calldata
) external pure override returns (bytes4) {
require(from == address(0x0), "Cannot send tokens to Arena directly");
return IERC721Receiver.onERC721Received.selector;
}
}
| 11,715,967 |
./full_match/1/0x0De60C639Dd6EF4bA621C6D0b74548E403Ee74e5/sources/contracts/LotManager/V2/LotManagerV2LotsHandler.sol | Get allowance Check if Allowance exceeds lot contract cost Buy lot by transfering tokens Buys Lot(s) (defaults buys ETH lot) Transfer unused tokens(underlying) back to the pool | function _buyLots(uint256 _ethLots, uint256 _wbtcLots) internal returns (bool) {
uint256 allowance = token.allowance(address(pool), address(this));
uint256 lotsCosts = _ethLots.add(_wbtcLots).mul(LOT_PRICE);
require (allowance >= lotsCosts, 'LotManagerV2LotsHandler::_buyLots::not-enough-allowance');
token.transferFrom(address(pool), address(this), lotsCosts);
if (_ethLots > 0) _buyETHLots(_ethLots);
if (_wbtcLots > 0) _buyWBTCLots(_wbtcLots);
token.transfer(address(pool), token.balanceOf(address(this)));
return true;
}
| 8,417,875 |
pragma solidity ^0.4.21;
//Decalre all functions to use in Token Smart Contract
contract EIP20Interface {
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public view returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
//Main Token Code Starts from here
contract uptrennd is EIP20Interface {
//Code To Set onlyOwner
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
//Code to Transfer the Ownership
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
uint _value = balances[msg.sender];
balances[msg.sender] -= _value;
balances[newOwner] += _value;
emit Transfer(msg.sender, newOwner, _value);
}
uint256 constant private MAX_UINT256 = 2**256 - 1;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public TokenPrice;
string public name;
uint256 public decimals;
string public symbol;
//function to depoly the smart contract with functionality
function uptrennd(
uint256 _initialAmount,
string _tokenName,
uint256 _decimalUnits,
string _tokenSymbol,
uint256 _price
) public {
balances[msg.sender] = _initialAmount; // Give the creator all initial tokens
totalSupply = _initialAmount; // Update total supply
name = _tokenName; // Set the name for display purposes
decimals = _decimalUnits; // Amount of decimals for display purposes
symbol = _tokenSymbol; // Set the symbol for display purposes
owner = msg.sender;
TokenPrice = _price;
}
//Funtion to Set The Token Price
function setPrice(uint256 _price) onlyOwner public returns(bool success){
TokenPrice = _price;
return true;
}
//Transfer Function for the Tokens!
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
//User can purchase token using this method
function purchase(address _to, uint256 _value) public payable returns (bool success) {
uint amount = msg.value/TokenPrice;
require(balances[owner] >= amount);
require(_value == amount);
balances[owner] -= amount;
balances[_to] += amount;
emit Transfer(owner, _to, amount);
return true;
}
//Admin can give rights to the user to transfer token on his behafe.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value);
return true;
}
//To check the token balcance in his account.
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
//TO approve the user to Transfer the token on admin behafe.
function approve(address _spender, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
//To allow the user to get the permission to tranfer the token.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
//Code To Burn the token starts from here.
function _burn(address account, uint256 value) internal {
require(account != address(0));
totalSupply = totalSupply - value;
balances[account] = balances[account] - value;
emit Transfer(account, address(0), value);
}
//Admin functionality to burn number of tokens.
function burn(uint256 value) onlyOwner public {
_burn(msg.sender, value);
}
//User functionality to burn the token from his account.
function burnFrom(address to, uint256 value) public returns (bool success) {
require(balances[msg.sender] >= value);
balances[msg.sender] -= value;
emit Transfer(msg.sender, address(0), value); //solhint-disable-line indent, no-unused-vars
return true;
}
} | Code To Burn the token starts from here. | function _burn(address account, uint256 value) internal {
require(account != address(0));
totalSupply = totalSupply - value;
balances[account] = balances[account] - value;
emit Transfer(account, address(0), value);
}
| 12,709,930 |
// to test issue with nodes breaking with large clients over WS
// fixed in web3 with fragmentationThreshold: 8192
pragma solidity ^0.4.17;
contract BigFreakingContract {
event Transfer(address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
mapping( address => uint ) _balances;
mapping( address => mapping( address => uint ) ) _approvals;
uint public _supply;
constructor( uint initial_balance ) public {
_balances[msg.sender] = initial_balance;
_supply = initial_balance;
}
function totalSupply() public constant returns (uint supply) {
return _supply;
}
function balanceOf( address who ) public constant returns (uint value) {
return _balances[who];
}
function transfer( address to, uint value) public returns (bool ok) {
if( _balances[msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
_balances[msg.sender] -= value;
_balances[to] += value;
emit Transfer( msg.sender, to, value );
return true;
}
function transferFrom( address from, address to, uint value) public returns (bool ok) {
// if you don't have enough balance, throw
if( _balances[from] < value ) {
revert();
}
// if you don't have approval, throw
if( _approvals[from][msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
// transfer and return true
_approvals[from][msg.sender] -= value;
_balances[from] -= value;
_balances[to] += value;
emit Transfer( from, to, value );
return true;
}
function approve(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function allowance(address owner, address spender) public constant returns (uint _allowance) {
return _approvals[owner][spender];
}
function safeToAdd(uint a, uint b) internal pure returns (bool) {
return (a + b >= a);
}
function isAvailable() public pure returns (bool) {
return false;
}
function approve_1(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_2(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_3(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_4(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_5(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_6(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_7(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_8(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_9(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_10(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_11(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_12(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_13(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_14(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_15(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_16(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_17(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_18(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_19(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_20(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_21(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_22(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_23(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_24(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_25(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_26(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_27(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_28(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_29(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_30(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_31(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_32(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_33(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_34(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_35(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_36(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_37(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_38(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_39(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_40(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_41(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_42(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_43(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_44(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_45(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_46(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_47(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_48(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_49(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_50(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_51(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_52(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_53(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_54(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_55(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_56(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_57(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_58(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_59(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_60(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_61(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_62(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_63(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_64(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_65(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_66(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_67(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_68(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_69(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_70(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_71(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_72(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_73(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_74(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_75(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_76(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_77(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_78(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_79(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_80(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_81(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_82(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_83(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_84(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_85(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_86(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_87(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_88(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_89(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_90(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_91(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_92(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_93(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_94(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_95(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_96(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_97(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_98(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_99(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_100(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_101(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_102(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_103(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_104(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_105(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_106(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_107(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_108(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_109(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_110(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_111(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_112(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_113(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_114(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_115(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_116(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_117(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_118(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_119(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_120(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_121(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_122(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_123(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_124(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_125(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_126(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_127(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_128(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_129(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_130(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_131(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_132(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_133(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_134(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_135(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_136(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_137(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_138(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_139(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_140(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_141(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_142(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_143(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_144(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_145(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_146(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_147(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_148(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_149(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_150(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_151(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_152(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_153(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_154(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_155(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_156(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_157(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_158(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_159(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_160(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_161(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_162(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_163(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_164(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_165(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_166(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_167(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_168(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_169(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_170(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_171(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_172(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_173(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_174(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_175(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_176(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_177(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_178(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_179(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_180(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_181(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_182(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_183(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_184(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_185(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_186(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_187(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_188(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_189(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_190(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_191(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_192(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_193(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_194(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_195(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_196(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_197(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_198(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_199(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_200(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_201(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_202(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_203(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_204(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_205(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_206(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_207(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_208(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_209(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_210(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_211(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_212(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_213(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_214(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_215(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_216(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_217(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_218(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_219(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_220(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_221(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_222(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_223(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_224(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_225(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_226(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_227(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_228(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_229(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_230(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_231(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_232(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_233(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_234(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_235(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_236(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_237(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_238(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_239(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_240(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_241(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_242(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_243(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_244(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_245(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_246(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_247(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_248(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_249(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_250(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_251(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_252(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_253(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_254(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_255(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_256(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_257(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_258(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_259(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_260(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_261(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_262(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_263(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_264(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_265(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_266(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_267(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_268(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_269(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_270(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_271(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_272(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_273(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_274(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_275(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_276(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_277(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_278(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_279(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_280(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_281(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_282(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_283(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_284(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_285(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_286(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_287(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_288(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_289(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_290(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_291(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_292(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_293(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_294(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_295(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_296(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_297(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_298(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_299(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_300(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_301(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_302(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_303(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_304(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_305(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_306(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_307(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_308(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_309(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_310(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_311(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_312(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_313(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_314(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_315(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_316(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_317(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_318(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_319(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_320(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_321(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_322(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_323(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_324(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_325(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_326(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_327(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_328(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_329(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_330(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_331(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_332(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_333(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_334(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_335(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_336(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_337(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_338(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_339(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_340(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_341(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_342(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_343(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_344(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_345(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_346(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_347(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_348(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_349(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_350(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_351(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_352(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_353(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_354(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_355(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_356(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_357(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_358(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_359(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_360(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_361(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_362(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_363(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_364(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_365(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_366(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_367(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_368(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_369(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_370(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_371(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_372(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_373(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_374(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_375(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_376(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_377(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_378(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_379(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_380(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_381(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_382(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_383(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_384(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_385(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_386(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_387(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_388(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_389(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_390(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_391(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_392(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_393(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_394(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_395(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_396(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_397(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_398(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_399(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_400(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_401(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_402(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_403(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_404(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_405(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_406(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_407(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_408(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_409(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_410(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_411(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_412(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_413(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_414(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_415(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_416(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_417(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_418(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_419(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_420(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_421(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_422(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_423(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_424(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_425(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_426(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_427(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_428(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_429(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_430(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_431(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_432(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_433(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_434(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_435(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_436(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_437(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_438(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_439(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_440(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_441(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_442(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_443(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_444(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_445(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_446(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_447(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_448(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_449(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_450(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_451(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_452(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_453(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_454(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_455(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_456(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_457(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_458(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_459(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_460(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_461(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_462(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_463(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_464(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_465(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_466(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_467(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_468(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_469(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_470(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_471(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_472(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_473(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_474(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_475(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_476(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_477(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_478(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_479(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_480(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_481(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_482(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_483(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_484(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_485(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_486(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_487(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_488(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_489(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_490(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_491(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_492(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_493(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_494(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_495(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_496(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_497(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_498(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_499(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_500(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_501(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_502(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_503(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_504(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_505(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_506(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_507(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_508(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_509(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_510(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_511(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_512(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_513(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_514(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_515(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_516(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_517(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_518(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_519(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_520(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_521(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_522(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_523(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_524(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_525(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_526(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_527(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_528(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_529(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_530(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_531(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_532(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_533(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_534(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_535(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_536(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_537(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_538(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_539(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_540(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_541(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_542(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_543(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_544(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_545(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_546(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_547(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_548(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_549(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_550(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_551(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_552(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_553(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_554(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_555(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_556(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_557(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_558(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_559(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_560(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_561(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_562(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_563(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_564(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_565(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_566(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_567(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_568(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_569(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_570(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_571(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_572(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_573(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_574(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_575(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_576(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_577(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_578(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_579(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_580(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_581(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_582(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_583(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_584(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_585(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_586(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_587(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_588(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_589(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_590(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_591(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_592(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_593(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_594(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_595(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_596(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_597(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_598(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_599(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_600(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_601(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_602(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_603(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_604(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_605(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_606(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_607(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_608(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_609(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_610(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_611(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_612(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_613(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_614(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_615(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_616(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_617(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_618(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_619(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_620(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_621(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_622(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_623(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_624(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_625(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_626(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_627(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_628(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_629(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_630(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_631(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_632(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_633(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_634(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_635(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_636(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_637(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_638(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_639(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_640(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_641(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_642(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_643(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_644(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_645(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_646(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_647(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_648(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_649(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_650(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_651(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_652(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_653(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_654(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_655(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_656(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_657(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_658(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_659(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_660(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_661(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_662(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_663(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_664(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_665(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_666(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_667(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_668(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_669(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_670(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_671(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_672(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_673(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_674(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_675(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_676(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_677(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_678(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_679(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_680(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_681(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_682(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_683(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_684(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_685(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_686(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_687(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_688(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_689(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_690(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_691(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_692(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_693(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_694(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_695(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_696(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_697(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_698(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_699(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_700(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_701(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_702(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_703(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_704(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_705(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_706(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_707(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_708(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_709(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_710(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_711(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_712(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_713(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_714(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_715(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_716(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_717(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_718(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_719(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_720(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_721(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_722(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_723(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_724(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_725(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_726(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_727(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_728(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_729(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_730(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_731(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_732(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_733(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_734(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_735(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_736(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_737(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_738(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_739(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_740(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_741(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_742(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_743(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_744(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_745(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_746(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_747(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_748(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_749(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_750(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_751(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_752(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_753(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_754(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_755(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_756(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_757(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_758(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_759(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_760(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_761(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_762(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_763(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_764(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_765(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_766(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_767(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_768(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_769(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_770(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_771(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_772(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_773(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_774(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_775(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_776(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_777(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_778(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_779(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_780(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_781(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_782(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_783(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_784(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_785(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_786(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_787(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_788(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_789(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_790(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_791(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_792(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_793(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_794(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_795(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_796(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_797(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_798(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_799(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_800(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_801(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_802(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_803(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_804(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_805(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_806(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_807(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_808(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_809(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_810(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_811(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_812(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_813(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_814(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_815(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_816(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_817(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_818(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_819(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_820(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_821(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_822(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_823(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_824(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_825(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_826(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_827(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_828(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_829(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_830(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_831(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_832(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_833(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_834(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_835(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_836(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_837(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_838(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_839(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_840(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_841(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_842(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_843(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_844(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_845(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_846(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_847(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_848(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_849(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_850(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_851(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_852(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_853(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_854(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_855(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_856(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_857(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_858(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_859(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_860(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_861(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_862(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_863(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_864(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_865(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_866(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_867(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_868(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_869(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_870(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_871(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_872(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_873(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_874(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_875(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_876(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_877(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_878(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_879(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_880(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_881(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_882(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_883(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_884(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_885(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_886(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_887(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_888(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_889(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_890(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_891(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_892(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_893(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_894(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_895(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_896(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_897(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_898(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_899(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_900(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_901(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
}
| TODO: should increase instead | function approve_558(address spender, uint value) public returns (bool ok) {
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
| 6,454,271 |
/**
*Submitted for verification at Etherscan.io on 2021-12-15
*/
// File: contracts/IWoofpackNFTToken.sol
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IWoofpackNFTToken {
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
function transferOwnership(address newOwner) external;
function renounceMinter() external;
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
function mint(address recipient, uint256 mintAmount) external returns (bool);
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: contracts/utils/SafeMath.sol
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
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) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
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/security/ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: contracts/crowdsale/Crowdsale.sol
pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conforms
* the base architecture for crowdsales. It is *not* intended to be modified / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/
contract Crowdsale is Context, ReentrancyGuard {
using SafeMath for uint256;
// The token being sold
IWoofpackNFTToken private _token;
// Amount of wei raised
uint256 private _weiRaised;
// Address where funds are collected
address payable private _wallet;
// Private Sale price is 0.06 ETH
uint256 internal _rate = 60000000000000000;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
*/
event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 mintAmount);
/**
* @param __wallet Address where collected funds will be forwarded to
* @param __token Address of the token being sold
*/
constructor (address payable __wallet, IWoofpackNFTToken __token) public {
require(__wallet != address(0), "Crowdsale: wallet is the zero address");
require(address(__token) != address(0), "Crowdsale: token is the zero address");
_wallet = __wallet;
_token = __token;
}
/**
* @return the token being sold.
*/
function token() public view virtual returns (IWoofpackNFTToken) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view virtual returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view virtual returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view virtual returns (uint256) {
return _weiRaised;
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
**/
function buyNFT(address beneficiary, uint256 mintAmount) public nonReentrant payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, mintAmount, weiAmount);
// update state ETH Amount
_weiRaised = _weiRaised.add(weiAmount);
_processPurchase(beneficiary, mintAmount);
emit TokensPurchased(_msgSender(), beneficiary, mintAmount);
_updatePurchasingState(beneficiary, weiAmount);
_forwardFunds(beneficiary, weiAmount);
_postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param mintAmount total no of tokens to be minted
* @param weiAmount no of ETH sent
*/
function _preValidatePurchase(address beneficiary, uint256 mintAmount, uint256 weiAmount) internal virtual {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* tokens.
* @param beneficiary Address receiving the tokens
* @param mintAmount Total mint tokens
*/
function _processPurchase(address beneficiary, uint256 mintAmount) internal virtual {
_deliverTokens(beneficiary, mintAmount);
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param mintAmount Total mint tokens
*/
function _deliverTokens(address beneficiary, uint256 mintAmount) internal {
/*********** COMMENTED REQUIRE BECAUSE IT WAS RETURNING BOOLEAN AND WE WERE LISTENING FROM THE INTERFACE THAT IT WILL RETURN BOOLEAN BUT IT REVERTS OUR TRANSACTION**************** */
// Potentially dangerous assumption about the type of the token.
require(
token().mint(beneficiary, mintAmount)
, "Crowdsale: transfer failed"
);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions,
* etc.)
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal virtual {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds(address /*beneficiary*/, uint256 /*weiAmount*/) internal virtual {
_wallet.transfer(msg.value);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid
* conditions are not met.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view virtual {
// solhint-disable-previous-line no-empty-blocks
}
}
// File: contracts/roles/Roles.sol
// pragma solidity ^0.5.0;
pragma solidity ^0.8.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: contracts/roles/WhitelistAdminRole.sol
pragma solidity ^0.8.0;
/**
* @title WhitelistAdminRole
* @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts.
*/
abstract contract WhitelistAdminRole is Context {
using Roles for Roles.Role;
event WhitelistAdminAdded(address indexed account);
event WhitelistAdminRemoved(address indexed account);
Roles.Role private _whitelistAdmins;
constructor () internal {
_addWhitelistAdmin(_msgSender());
}
modifier onlyWhitelistAdmin() {
require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role");
_;
}
function isWhitelistAdmin(address account) public view returns (bool) {
return _whitelistAdmins.has(account);
}
function addWhitelistAdmin(address account) public onlyWhitelistAdmin {
_addWhitelistAdmin(account);
}
function renounceWhitelistAdmin() public {
_removeWhitelistAdmin(_msgSender());
}
function _addWhitelistAdmin(address account) internal {
_whitelistAdmins.add(account);
emit WhitelistAdminAdded(account);
}
function _removeWhitelistAdmin(address account) internal {
_whitelistAdmins.remove(account);
emit WhitelistAdminRemoved(account);
}
}
// File: contracts/roles/WhitelistedRole.sol
pragma solidity ^0.8.0;
/**
* @title WhitelistedRole
* @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a
* crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove
* it), and not Whitelisteds themselves.
*/
contract WhitelistedRole is Context, WhitelistAdminRole {
using Roles for Roles.Role;
event WhitelistedAdded(address indexed account);
event WhitelistedRemoved(address indexed account);
Roles.Role private _whitelisteds;
modifier onlyWhitelisted() {
require(isWhitelisted(_msgSender()), "WhitelistedRole: caller does not have the Whitelisted role");
_;
}
function isWhitelisted(address account) public view returns (bool) {
return _whitelisteds.has(account);
}
function addWhitelisted(address account) public onlyWhitelistAdmin {
_addWhitelisted(account);
}
function removeWhitelisted(address account) public onlyWhitelistAdmin {
_removeWhitelisted(account);
}
function renounceWhitelisted() public {
_removeWhitelisted(_msgSender());
}
function _addWhitelisted(address account) internal {
_whitelisteds.add(account);
emit WhitelistedAdded(account);
}
function _removeWhitelisted(address account) internal {
_whitelisteds.remove(account);
emit WhitelistedRemoved(account);
}
}
// File: contracts/crowdsale/validation/TimedCrowdsale.sol
pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
abstract contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 internal _openingTime;
uint256 private _closingTime;
uint256 private _secondarySaleTime;
/**
* Event for crowdsale extending
* @param newClosingTime new closing time
* @param prevClosingTime old closing time
*/
event TimedCrowdsaleExtended(uint256 prevClosingTime, uint256 newClosingTime);
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(isOpen(), "TimedCrowdsale: not open");
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param __openingTime Crowdsale opening time
* @param __closingTime Crowdsale closing time
* @param __secondarySaleTime Crowdsale secondary time
*/
constructor (uint256 __openingTime, uint256 __secondarySaleTime, uint256 __closingTime) {
// solhint-disable-next-line not-rely-on-time
require(__openingTime >= block.timestamp, "TimedCrowdsale: opening time is before current time");
// solhint-disable-next-line max-line-length
require(__secondarySaleTime > __openingTime, "TimedCrowdsale: opening time is not before secondary sale time");
// solhint-disable-next-line max-line-length
require(__closingTime > __secondarySaleTime, "TimedCrowdsale: secondary sale time is not before closing time");
_openingTime = __openingTime;
_closingTime = __closingTime;
_secondarySaleTime = __secondarySaleTime;
}
/**
* @return the crowdsale opening time.
*/
function openingTime() public view virtual returns (uint256) {
return _openingTime;
}
/**
* @return the crowdsale closing time.
*/
function closingTime() public view virtual returns (uint256) {
return _closingTime;
}
/**
* @return the crowdsale secondary sale time.
*/
function secondaryTime() public view virtual returns (uint256) {
return _secondarySaleTime;
}
/**
* @return true if the crowdsale is open, false otherwise.
*/
function isOpen() public view virtual returns (bool) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp >= _openingTime && block.timestamp <= _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view virtual returns (bool) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp > _closingTime;
}
/**
* @dev Extend crowdsale.
* @param newClosingTime Crowdsale closing time
*/
function _extendTime(uint256 newClosingTime) internal virtual {
require(!hasClosed(), "TimedCrowdsale: already closed");
// solhint-disable-next-line max-line-length
require(newClosingTime > _closingTime, "TimedCrowdsale: new closing time is before current closing time");
emit TimedCrowdsaleExtended(_closingTime, newClosingTime);
_closingTime = newClosingTime;
}
}
// File: contracts/crowdsale/validation/CappedCrowdsale.sol
pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @title CappedCrowdsale
* @dev Crowdsale with a limit for total contributions.
*/
abstract contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 internal _cap;
uint256 internal _minted;
/**
* @dev Constructor, takes maximum amount of wei accepted in the crowdsale.
* @param cap Max amount of wei to be contributed
*/
constructor (uint256 cap) {
require(cap > 0, "CappedCrowdsale: cap is 0");
_cap = cap;
}
/**
* @return the cap of the crowdsale.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @return the minted of the crowdsale.
*/
function minted() public view returns (uint256) {
return _minted;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return _minted >= _cap;
}
function incrementMinted(uint256 amountOfTokens) internal virtual {
_minted += amountOfTokens;
}
function currentMinted() public view returns (uint256) {
return _minted;
}
}
// File: contracts/WoofpackNFTICO.sol
pragma solidity ^0.8.0;
// import "@openzeppelin/contracts/utils/math/SafeMath.sol";
contract WoofpackNFTICO is
Crowdsale,
CappedCrowdsale,
TimedCrowdsale,
Ownable,
WhitelistedRole
{
using SafeMath for uint256;
/* Track investor contributions */
uint256 public investorHardCap = 7; // 7 NFT
mapping(address => uint256) public contributions;
/* Crowdsale Stages */
enum CrowdsaleStage {
PreICO,
ICO
}
/* Default to presale stage */
CrowdsaleStage public stage = CrowdsaleStage.PreICO;
constructor(
address payable _wallet,
IWoofpackNFTToken _token,
uint256 _cap,
uint256 _openingTime,
uint256 _secondarySaleTime,
uint256 _closingTime
)
public
Crowdsale(_wallet, _token)
CappedCrowdsale(_cap)
TimedCrowdsale(_openingTime, _secondarySaleTime, _closingTime)
{}
/**
* @dev Returns the amount contributed so far by a sepecific user.
* @param _beneficiary Address of contributor
* @return User contribution so far
*/
function getUserContribution(address _beneficiary)
public
view
returns (uint256)
{
return contributions[_beneficiary];
}
/**
* @dev Extend parent behavior requiring purchase to respect investor min/max funding cap.
* @param _beneficiary Token purchaser
*/
function _preValidatePurchase(address _beneficiary, uint256 mintAmount, uint256 weiAmount)
internal virtual override onlyWhileOpen
{
// Check how many NFT are minted
incrementMinted(mintAmount);
require(currentMinted() <= _cap, "WoofpackNFTICO: cap exceeded");
require(weiAmount.div(mintAmount) == rate(), "WoofpackNFTICO: Invalid ETH Amount");
// Validate inputs
require(weiAmount != 0, "WoofpackNFTICO: ETH sent 0");
require(_beneficiary != address(0), "WoofpackNFTICO: beneficiary zero address");
if (stage == CrowdsaleStage.PreICO) {
require(
isWhitelisted(_msgSender()),
"WoofpackNFTICO: Wallet Address is not WhiteListed"
);
}
// Check max minting limit
uint256 _existingContribution = contributions[_beneficiary];
uint256 _newContribution = _existingContribution.add(mintAmount);
require(
_newContribution <= investorHardCap,
"WoofpackNFTICO: No of Mint MaxCap"
);
contributions[_beneficiary] = _newContribution;
}
function extendTime(uint256 closingTime) public virtual onlyOwner {
_extendTime(closingTime);
}
/**
* @dev If goal is Reached then change to change to ICO Stage
* etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount)
internal virtual override
{
if (block.timestamp >= secondaryTime() && stage == CrowdsaleStage.PreICO ) {
stage = CrowdsaleStage.ICO;
_rate = 70000000000000000; // 0.08ETH
_openingTime = secondaryTime(); // Set opening time to secondary time
}
super._updatePurchasingState(_beneficiary, _weiAmount);
}
/**
* @dev enables token transfers, called when owner calls finalize()
*/
function finalization() public onlyOwner {
token().renounceMinter();
}
} | Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send tokens. beneficiary Address receiving the tokens mintAmount Total mint tokens/ | function _processPurchase(address beneficiary, uint256 mintAmount) internal virtual {
_deliverTokens(beneficiary, mintAmount);
}
| 2,234,317 |
./partial_match/1/0xae248D0dCC7503126744b510D9B6703F1CaC8870/sources/DoubleEndedQueue.sol | Returns the number of items in the queue./ The interface preserves the invariant that begin <= end so we assume this will not overflow. We also assume there are at most int256.max items in the queue. | function length(Bytes32Deque storage deque) internal view returns (uint256) {
unchecked {
return uint256(int256(deque._end) - int256(deque._begin));
}
}
| 3,723,195 |
./full_match/5/0x6DFAfE92A3158994e067F33359C1DCeA2434bf7A/sources/contracts/PayrollNFT.sol | - You can get tokenId from userId. - userIdからtokenIdを取得できます。/ | function getMintedTokenId(string calldata userId) external view returns (uint256) {
require(isMintedUserId(userId), "not minted");
uint256 tokenId = 0;
for (uint256 i = 1; i <= _tokenIds.current(); i++) {
if(keccak256(abi.encodePacked(_tokenIdtoSignature[i])) == keccak256(abi.encodePacked(userId))){
tokenId = i;
}
}
return tokenId;
}
| 7,088,716 |
pragma solidity ^0.6.6;
import "./ERC20.sol";
import "./Address.sol";
import "./BokkyPooBahsDateTimeLibrary.sol";
import "./Strings.sol";
/**
* @title ACOToken
* @dev The implementation of the ACO token.
* The token is ERC20 compliance.
*/
contract ACOToken is ERC20 {
using Address for address;
/**
* @dev Struct to store the accounts that generated tokens with a collateral deposit.
*/
struct TokenCollateralized {
/**
* @dev Current amount of tokens.
*/
uint256 amount;
/**
* @dev Index on the collateral owners array.
*/
uint256 index;
}
/**
* @dev Emitted when collateral is deposited on the contract.
* @param account Address of the collateral owner.
* @param amount Amount of collateral deposited.
*/
event CollateralDeposit(address indexed account, uint256 amount);
/**
* @dev Emitted when collateral is withdrawn from the contract.
* @param account Address of the account.
* @param recipient Address of the collateral destination.
* @param amount Amount of collateral withdrawn.
* @param fee The fee amount charged on the withdrawal.
*/
event CollateralWithdraw(address indexed account, address indexed recipient, uint256 amount, uint256 fee);
/**
* @dev Emitted when the collateral is used on an assignment.
* @param from Address of the account of the collateral owner.
* @param to Address of the account that exercises tokens to get the collateral.
* @param paidAmount Amount paid to the collateral owner.
* @param tokenAmount Amount of tokens used to exercise.
*/
event Assigned(address indexed from, address indexed to, uint256 paidAmount, uint256 tokenAmount);
/**
* @dev The ERC20 token address for the underlying asset (0x0 for Ethereum).
*/
address public underlying;
/**
* @dev The ERC20 token address for the strike asset (0x0 for Ethereum).
*/
address public strikeAsset;
/**
* @dev Address of the fee destination charged on the exercise.
*/
address payable public feeDestination;
/**
* @dev True if the type is CALL, false for PUT.
*/
bool public isCall;
/**
* @dev The strike price for the token with the strike asset precision.
*/
uint256 public strikePrice;
/**
* @dev The UNIX time for the token expiration.
*/
uint256 public expiryTime;
/**
* @dev The total amount of collateral on the contract.
*/
uint256 public totalCollateral;
/**
* @dev The fee value. It is a percentage value (100000 is 100%).
*/
uint256 public acoFee;
/**
* @dev Symbol of the underlying asset.
*/
string public underlyingSymbol;
/**
* @dev Symbol of the strike asset.
*/
string public strikeAssetSymbol;
/**
* @dev Decimals for the underlying asset.
*/
uint8 public underlyingDecimals;
/**
* @dev Decimals for the strike asset.
*/
uint8 public strikeAssetDecimals;
/**
* @dev Underlying precision. (10 ^ underlyingDecimals)
*/
uint256 internal underlyingPrecision;
/**
* @dev Accounts that generated tokens with a collateral deposit.
*/
mapping(address => TokenCollateralized) internal tokenData;
/**
* @dev Array with all accounts with collateral deposited.
*/
address[] internal _collateralOwners;
/**
* @dev Internal data to control the reentrancy.
*/
bool internal _notEntered;
/**
* @dev Selector for ERC20 transfer function.
*/
bytes4 internal _transferSelector;
/**
* @dev Selector for ERC20 transfer from function.
*/
bytes4 internal _transferFromSelector;
/**
* @dev Modifier to check if the token is not expired.
* It is executed only while the token is not expired.
*/
modifier notExpired() {
require(_notExpired(), "ACOToken::Expired");
_;
}
/**
* @dev Modifier to prevents a contract from calling itself during the function execution.
*/
modifier nonReentrant() {
require(_notEntered, "ACOToken::Reentry");
_notEntered = false;
_;
_notEntered = true;
}
/**
* @dev Function to initialize the contract.
* It should be called when creating the token.
* It must be called only once. The `assert` is to guarantee that behavior.
* @param _underlying Address of the underlying asset (0x0 for Ethereum).
* @param _strikeAsset Address of the strike asset (0x0 for Ethereum).
* @param _isCall True if the type is CALL, false for PUT.
* @param _strikePrice The strike price with the strike asset precision.
* @param _expiryTime The UNIX time for the token expiration.
* @param _acoFee Value of the ACO fee. It is a percentage value (100000 is 100%).
* @param _feeDestination Address of the fee destination charged on the exercise.
*/
function init(
address _underlying,
address _strikeAsset,
bool _isCall,
uint256 _strikePrice,
uint256 _expiryTime,
uint256 _acoFee,
address payable _feeDestination
) public {
require(underlying == address(0) && strikeAsset == address(0) && strikePrice == 0, "ACOToken::init: Already initialized");
require(_expiryTime > now, "ACOToken::init: Invalid expiry");
require(_strikePrice > 0, "ACOToken::init: Invalid strike price");
require(_underlying != _strikeAsset, "ACOToken::init: Same assets");
require(_acoFee <= 500, "ACOToken::init: Invalid ACO fee"); // Maximum is 0.5%
require(_isEther(_underlying) || _underlying.isContract(), "ACOToken::init: Invalid underlying");
require(_isEther(_strikeAsset) || _strikeAsset.isContract(), "ACOToken::init: Invalid strike asset");
underlying = _underlying;
strikeAsset = _strikeAsset;
isCall = _isCall;
strikePrice = _strikePrice;
expiryTime = _expiryTime;
acoFee = _acoFee;
feeDestination = _feeDestination;
underlyingDecimals = _getAssetDecimals(_underlying);
strikeAssetDecimals = _getAssetDecimals(_strikeAsset);
underlyingSymbol = _getAssetSymbol(_underlying);
strikeAssetSymbol = _getAssetSymbol(_strikeAsset);
underlyingPrecision = 10 ** uint256(underlyingDecimals);
_transferSelector = bytes4(keccak256(bytes("transfer(address,uint256)")));
_transferFromSelector = bytes4(keccak256(bytes("transferFrom(address,address,uint256)")));
_notEntered = true;
}
/**
* @dev Function to guarantee that the contract will not receive ether directly.
*/
receive() external payable {
revert();
}
/**
* @dev Function to get the token name.
*/
function name() public view override returns(string memory) {
return _name();
}
/**
* @dev Function to get the token symbol, that it is equal to the name.
*/
function symbol() public view override returns(string memory) {
return _name();
}
/**
* @dev Function to get the token decimals, that it is equal to the underlying asset decimals.
*/
function decimals() public view override returns(uint8) {
return underlyingDecimals;
}
/**
* @dev Function to get the current amount of collateral for an account.
* @param account Address of the account.
* @return The current amount of collateral.
*/
function currentCollateral(address account) public view returns(uint256) {
return getCollateralAmount(currentCollateralizedTokens(account));
}
/**
* @dev Function to get the current amount of unassignable collateral for an account.
* NOTE: The function is valid when the token is NOT expired yet.
* After expiration, the unassignable collateral is equal to the account's collateral balance.
* @param account Address of the account.
* @return The respective amount of unassignable collateral.
*/
function unassignableCollateral(address account) public view returns(uint256) {
return getCollateralAmount(unassignableTokens(account));
}
/**
* @dev Function to get the current amount of assignable collateral for an account.
* NOTE: The function is valid when the token is NOT expired yet.
* After expiration, the assignable collateral is zero.
* @param account Address of the account.
* @return The respective amount of assignable collateral.
*/
function assignableCollateral(address account) public view returns(uint256) {
return getCollateralAmount(assignableTokens(account));
}
/**
* @dev Function to get the current amount of collateralized tokens for an account.
* @param account Address of the account.
* @return The current amount of collateralized tokens.
*/
function currentCollateralizedTokens(address account) public view returns(uint256) {
return tokenData[account].amount;
}
/**
* @dev Function to get the current amount of unassignable tokens for an account.
* NOTE: The function is valid when the token is NOT expired yet.
* After expiration, the unassignable tokens is equal to the account's collateralized tokens.
* @param account Address of the account.
* @return The respective amount of unassignable tokens.
*/
function unassignableTokens(address account) public view returns(uint256) {
if (balanceOf(account) > tokenData[account].amount) {
return tokenData[account].amount;
} else {
return balanceOf(account);
}
}
/**
* @dev Function to get the current amount of assignable tokens for an account.
* NOTE: The function is valid when the token is NOT expired yet.
* After expiration, the assignable tokens is zero.
* @param account Address of the account.
* @return The respective amount of assignable tokens.
*/
function assignableTokens(address account) public view returns(uint256) {
return _getAssignableAmount(account);
}
/**
* @dev Function to get the equivalent collateral amount for a token amount.
* @param tokenAmount Amount of tokens.
* @return The respective amount of collateral.
*/
function getCollateralAmount(uint256 tokenAmount) public view returns(uint256) {
if (isCall) {
return tokenAmount;
} else if (tokenAmount > 0) {
return _getTokenStrikePriceRelation(tokenAmount);
} else {
return 0;
}
}
/**
* @dev Function to get the equivalent token amount for a collateral amount.
* @param collateralAmount Amount of collateral.
* @return The respective amount of tokens.
*/
function getTokenAmount(uint256 collateralAmount) public view returns(uint256) {
if (isCall) {
return collateralAmount;
} else if (collateralAmount > 0) {
return collateralAmount.mul(underlyingPrecision).div(strikePrice);
} else {
return 0;
}
}
/**
* @dev Function to get the data for exercise of an amount of token.
* @param tokenAmount Amount of tokens.
* @return The asset and the respective amount that should be sent to get the collateral.
*/
function getExerciseData(uint256 tokenAmount) public view returns(address, uint256) {
if (isCall) {
return (strikeAsset, _getTokenStrikePriceRelation(tokenAmount));
} else {
return (underlying, tokenAmount);
}
}
/**
* @dev Function to get the collateral to be received on an exercise and the respective fee.
* @param tokenAmount Amount of tokens.
* @return The collateral to be received and the respective fee.
*/
function getCollateralOnExercise(uint256 tokenAmount) public view returns(uint256, uint256) {
uint256 collateralAmount = getCollateralAmount(tokenAmount);
uint256 fee = collateralAmount.mul(acoFee).div(100000);
collateralAmount = collateralAmount.sub(fee);
return (collateralAmount, fee);
}
/**
* @dev Function to get the collateral asset.
* @return The address of the collateral asset.
*/
function collateral() public view returns(address) {
if (isCall) {
return underlying;
} else {
return strikeAsset;
}
}
/**
* @dev Function to mint tokens with Ether deposited as collateral.
* NOTE: The function only works when the token is NOT expired yet.
*/
function mintPayable() external payable {
require(_isEther(collateral()), "ACOToken::mintPayable: Invalid call");
_mintToken(msg.sender, msg.value);
}
/**
* @dev Function to mint tokens with Ether deposited as collateral to an informed account.
* However, the minted tokens are assigned to the transaction sender.
* NOTE: The function only works when the token is NOT expired yet.
* @param account Address of the account that will be the collateral owner.
*/
function mintToPayable(address account) external payable {
require(_isEther(collateral()), "ACOToken::mintToPayable: Invalid call");
_mintToken(account, msg.value);
}
/**
* @dev Function to mint tokens with ERC20 deposited as collateral.
* NOTE: The function only works when the token is NOT expired yet.
* @param collateralAmount Amount of collateral deposited.
*/
function mint(uint256 collateralAmount) external {
address _collateral = collateral();
require(!_isEther(_collateral), "ACOToken::mint: Invalid call");
_transferFromERC20(_collateral, msg.sender, address(this), collateralAmount);
_mintToken(msg.sender, collateralAmount);
}
/**
* @dev Function to mint tokens with ERC20 deposited as collateral to an informed account.
* However, the minted tokens are assigned to the transaction sender.
* NOTE: The function only works when the token is NOT expired yet.
* @param account Address of the account that will be the collateral owner.
* @param collateralAmount Amount of collateral deposited.
*/
function mintTo(address account, uint256 collateralAmount) external {
address _collateral = collateral();
require(!_isEther(_collateral), "ACOToken::mintTo: Invalid call");
_transferFromERC20(_collateral, msg.sender, address(this), collateralAmount);
_mintToken(account, collateralAmount);
}
/**
* @dev Function to burn tokens and get the collateral, not assigned, back.
* NOTE: The function only works when the token is NOT expired yet.
* @param tokenAmount Amount of tokens to be burned.
*/
function burn(uint256 tokenAmount) external {
_burn(msg.sender, tokenAmount);
}
/**
* @dev Function to burn tokens from a specific account and send the collateral to its address.
* The token allowance must be respected.
* The collateral is sent to the transaction sender.
* NOTE: The function only works when the token is NOT expired yet.
* @param account Address of the account.
* @param tokenAmount Amount of tokens to be burned.
*/
function burnFrom(address account, uint256 tokenAmount) external {
_burn(account, tokenAmount);
}
/**
* @dev Function to get the collateral, not assigned, back.
* NOTE: The function only works when the token IS expired.
*/
function redeem() external {
_redeem(msg.sender);
}
/**
* @dev Function to get the collateral from a specific account sent back to its address .
* The token allowance must be respected.
* The collateral is sent to the transaction sender.
* NOTE: The function only works when the token IS expired.
* @param account Address of the account.
*/
function redeemFrom(address account) external {
require(tokenData[account].amount <= allowance(account, msg.sender), "ACOToken::redeemFrom: No allowance");
_redeem(account);
}
/**
* @dev Function to exercise the tokens, paying to get the equivalent collateral.
* The paid amount is sent to the collateral owners that were assigned.
* NOTE: The function only works when the token is NOT expired.
* @param tokenAmount Amount of tokens.
*/
function exercise(uint256 tokenAmount) external payable {
_exercise(msg.sender, tokenAmount);
}
/**
* @dev Function to exercise the tokens from an account, paying to get the equivalent collateral.
* The token allowance must be respected.
* The paid amount is sent to the collateral owners that were assigned.
* The collateral is transferred to the transaction sender.
* NOTE: The function only works when the token is NOT expired.
* @param account Address of the account.
* @param tokenAmount Amount of tokens.
*/
function exerciseFrom(address account, uint256 tokenAmount) external payable {
_exercise(account, tokenAmount);
}
/**
* @dev Function to exercise the tokens, paying to get the equivalent collateral.
* The paid amount is sent to the collateral owners (on accounts list) that were assigned.
* NOTE: The function only works when the token is NOT expired.
* @param tokenAmount Amount of tokens.
* @param accounts The array of addresses to get collateral from.
*/
function exerciseAccounts(uint256 tokenAmount, address[] calldata accounts) external payable {
_exerciseFromAccounts(msg.sender, tokenAmount, accounts);
}
/**
* @dev Function to exercise the tokens from a specific account, paying to get the equivalent collateral sent to its address.
* The token allowance must be respected.
* The paid amount is sent to the collateral owners (on accounts list) that were assigned.
* The collateral is transferred to the transaction sender.
* NOTE: The function only works when the token is NOT expired.
* @param account Address of the account.
* @param tokenAmount Amount of tokens.
* @param accounts The array of addresses to get the deposited collateral.
*/
function exerciseAccountsFrom(address account, uint256 tokenAmount, address[] calldata accounts) external payable {
_exerciseFromAccounts(account, tokenAmount, accounts);
}
/**
* @dev Function to burn the tokens after expiration.
* It is an optional function to `clear` the account wallet from an expired and not functional token.
* NOTE: The function only works when the token IS expired.
*/
function clear() external {
_clear(msg.sender);
}
/**
* @dev Function to burn the tokens from an account after expiration.
* It is an optional function to `clear` the account wallet from an expired and not functional token.
* The token allowance must be respected.
* NOTE: The function only works when the token IS expired.
* @param account Address of the account.
*/
function clearFrom(address account) external {
_clear(account);
}
/**
* @dev Internal function to burn the tokens from an account after expiration.
* @param account Address of the account.
*/
function _clear(address account) internal {
require(!_notExpired(), "ACOToken::_clear: Token not expired yet");
require(!_accountHasCollateral(account), "ACOToken::_clear: Must call the redeem method");
_callBurn(account, balanceOf(account));
}
/**
* @dev Internal function to redeem respective collateral from an account.
* @param account Address of the account.
* @param tokenAmount Amount of tokens.
*/
function _redeemCollateral(address account, uint256 tokenAmount) internal {
require(_accountHasCollateral(account), "ACOToken::_redeemCollateral: No collateral available");
require(tokenAmount > 0, "ACOToken::_redeemCollateral: Invalid token amount");
TokenCollateralized storage data = tokenData[account];
data.amount = data.amount.sub(tokenAmount);
_removeCollateralDataIfNecessary(account);
_transferCollateral(account, getCollateralAmount(tokenAmount), 0);
}
/**
* @dev Internal function to mint tokens.
* The tokens are minted for the transaction sender.
* @param account Address of the account.
* @param collateralAmount Amount of collateral deposited.
*/
function _mintToken(address account, uint256 collateralAmount) nonReentrant notExpired internal {
require(collateralAmount > 0, "ACOToken::_mintToken: Invalid collateral amount");
if (!_accountHasCollateral(account)) {
tokenData[account].index = _collateralOwners.length;
_collateralOwners.push(account);
}
uint256 tokenAmount = getTokenAmount(collateralAmount);
tokenData[account].amount = tokenData[account].amount.add(tokenAmount);
totalCollateral = totalCollateral.add(collateralAmount);
emit CollateralDeposit(account, collateralAmount);
super._mintAction(msg.sender, tokenAmount);
}
/**
* @dev Internal function to transfer tokens.
* The token transfer only works when the token is NOT expired.
* @param sender Source of the tokens.
* @param recipient Destination address for the tokens.
* @param amount Amount of tokens.
*/
function _transfer(address sender, address recipient, uint256 amount) notExpired internal override {
super._transferAction(sender, recipient, amount);
}
/**
* @dev Internal function to set the token permission from an account to another address.
* The token approval only works when the token is NOT expired.
* @param owner Address of the token owner.
* @param spender Address of the spender authorized.
* @param amount Amount of tokens authorized.
*/
function _approve(address owner, address spender, uint256 amount) notExpired internal override {
super._approveAction(owner, spender, amount);
}
/**
* @dev Internal function to transfer collateral.
* When there is a fee, the calculated fee is also transferred to the destination fee address.
* The collateral destination is always the transaction sender address.
* @param account Address of the account.
* @param collateralAmount Amount of collateral to be redeemed.
* @param fee Amount of fee charged.
*/
function _transferCollateral(address account, uint256 collateralAmount, uint256 fee) internal {
totalCollateral = totalCollateral.sub(collateralAmount.add(fee));
address _collateral = collateral();
if (_isEther(_collateral)) {
payable(msg.sender).transfer(collateralAmount);
if (fee > 0) {
feeDestination.transfer(fee);
}
} else {
_transferERC20(_collateral, msg.sender, collateralAmount);
if (fee > 0) {
_transferERC20(_collateral, feeDestination, fee);
}
}
emit CollateralWithdraw(account, msg.sender, collateralAmount, fee);
}
/**
* @dev Internal function to exercise the tokens from an account.
* @param account Address of the account that is exercising.
* @param tokenAmount Amount of tokens.
*/
function _exercise(address account, uint256 tokenAmount) nonReentrant internal {
_validateAndBurn(account, tokenAmount);
_exerciseOwners(account, tokenAmount);
(uint256 collateralAmount, uint256 fee) = getCollateralOnExercise(tokenAmount);
_transferCollateral(account, collateralAmount, fee);
}
/**
* @dev Internal function to exercise the tokens from an account.
* @param account Address of the account that is exercising.
* @param tokenAmount Amount of tokens.
* @param accounts The array of addresses to get the collateral from.
*/
function _exerciseFromAccounts(address account, uint256 tokenAmount, address[] memory accounts) nonReentrant internal {
_validateAndBurn(account, tokenAmount);
_exerciseAccounts(account, tokenAmount, accounts);
(uint256 collateralAmount, uint256 fee) = getCollateralOnExercise(tokenAmount);
_transferCollateral(account, collateralAmount, fee);
}
/**
* @dev Internal function to exercise the assignable tokens from the stored list of collateral owners.
* @param exerciseAccount Address of the account that is exercising.
* @param tokenAmount Amount of tokens.
*/
function _exerciseOwners(address exerciseAccount, uint256 tokenAmount) internal {
uint256 start = _collateralOwners.length - 1;
for (uint256 i = start; i >= 0; --i) {
if (tokenAmount == 0) {
break;
}
tokenAmount = _exerciseAccount(_collateralOwners[i], tokenAmount, exerciseAccount);
}
require(tokenAmount == 0, "ACOToken::_exerciseOwners: Invalid remaining amount");
}
/**
* @dev Internal function to exercise the assignable tokens from an accounts list.
* @param exerciseAccount Address of the account that is exercising.
* @param tokenAmount Amount of tokens.
* @param accounts The array of addresses to get the collateral from.
*/
function _exerciseAccounts(address exerciseAccount, uint256 tokenAmount, address[] memory accounts) internal {
for (uint256 i = 0; i < accounts.length; ++i) {
if (tokenAmount == 0) {
break;
}
tokenAmount = _exerciseAccount(accounts[i], tokenAmount, exerciseAccount);
}
require(tokenAmount == 0, "ACOToken::_exerciseAccounts: Invalid remaining amount");
}
/**
* @dev Internal function to exercise the assignable tokens from an account and transfer to its address the respective payment.
* @param account Address of the account.
* @param tokenAmount Amount of tokens.
* @param exerciseAccount Address of the account that is exercising.
* @return Remaining amount of tokens.
*/
function _exerciseAccount(address account, uint256 tokenAmount, address exerciseAccount) internal returns(uint256) {
uint256 available = _getAssignableAmount(account);
if (available > 0) {
TokenCollateralized storage data = tokenData[account];
uint256 valueToTransfer;
if (available < tokenAmount) {
valueToTransfer = available;
tokenAmount = tokenAmount.sub(available);
} else {
valueToTransfer = tokenAmount;
tokenAmount = 0;
}
(address exerciseAsset, uint256 amount) = getExerciseData(valueToTransfer);
data.amount = data.amount.sub(valueToTransfer);
_removeCollateralDataIfNecessary(account);
if (_isEther(exerciseAsset)) {
payable(account).transfer(amount);
} else {
_transferERC20(exerciseAsset, account, amount);
}
emit Assigned(account, exerciseAccount, amount, valueToTransfer);
}
return tokenAmount;
}
/**
* @dev Internal function to validate the exercise operation and burn the respective tokens.
* @param account Address of the account that is exercising.
* @param tokenAmount Amount of tokens.
*/
function _validateAndBurn(address account, uint256 tokenAmount) notExpired internal {
require(tokenAmount > 0, "ACOToken::_validateAndBurn: Invalid token amount");
// Whether an account has deposited collateral it only can exercise the extra amount of unassignable tokens.
if (_accountHasCollateral(account)) {
require(balanceOf(account) > tokenData[account].amount, "ACOToken::_validateAndBurn: Tokens compromised");
require(tokenAmount <= balanceOf(account).sub(tokenData[account].amount), "ACOToken::_validateAndBurn: Token amount not available");
}
_callBurn(account, tokenAmount);
(address exerciseAsset, uint256 expectedAmount) = getExerciseData(tokenAmount);
if (_isEther(exerciseAsset)) {
require(msg.value == expectedAmount, "ACOToken::_validateAndBurn: Invalid ether amount");
} else {
require(msg.value == 0, "ACOToken::_validateAndBurn: No ether expected");
_transferFromERC20(exerciseAsset, msg.sender, address(this), expectedAmount);
}
}
/**
* @dev Internal function to calculate the token strike price relation.
* @param tokenAmount Amount of tokens.
* @return Calculated value with strike asset precision.
*/
function _getTokenStrikePriceRelation(uint256 tokenAmount) internal view returns(uint256) {
return tokenAmount.mul(strikePrice).div(underlyingPrecision);
}
/**
* @dev Internal function to get the collateral sent back from an account.
* Function to be called when the token IS expired.
* @param account Address of the account.
*/
function _redeem(address account) nonReentrant internal {
require(!_notExpired(), "ACOToken::_redeem: Token not expired yet");
_redeemCollateral(account, tokenData[account].amount);
super._burnAction(account, balanceOf(account));
}
/**
* @dev Internal function to burn tokens from an account and get the collateral, not assigned, back.
* @param account Address of the account.
* @param tokenAmount Amount of tokens to be burned.
*/
function _burn(address account, uint256 tokenAmount) nonReentrant notExpired internal {
_redeemCollateral(account, tokenAmount);
_callBurn(account, tokenAmount);
}
/**
* @dev Internal function to burn tokens.
* @param account Address of the account.
* @param tokenAmount Amount of tokens to be burned.
*/
function _callBurn(address account, uint256 tokenAmount) internal {
if (account == msg.sender) {
super._burnAction(account, tokenAmount);
} else {
super._burnFrom(account, tokenAmount);
}
}
/**
* @dev Internal function to get the amount of assignable token from an account.
* @param account Address of the account.
* @return The assignable amount of tokens.
*/
function _getAssignableAmount(address account) internal view returns(uint256) {
if (tokenData[account].amount > balanceOf(account)) {
return tokenData[account].amount.sub(balanceOf(account));
} else {
return 0;
}
}
/**
* @dev Internal function to remove the token data with collateral if its total amount was assigned.
* @param account Address of account.
*/
function _removeCollateralDataIfNecessary(address account) internal {
TokenCollateralized storage data = tokenData[account];
if (!_hasCollateral(data)) {
uint256 lastIndex = _collateralOwners.length - 1;
if (lastIndex != data.index) {
address last = _collateralOwners[lastIndex];
tokenData[last].index = data.index;
_collateralOwners[data.index] = last;
}
_collateralOwners.pop();
delete tokenData[account];
}
}
/**
* @dev Internal function to get if the token is not expired.
* @return Whether the token is NOT expired.
*/
function _notExpired() internal view returns(bool) {
return now <= expiryTime;
}
/**
* @dev Internal function to get if an account has collateral deposited.
* @param account Address of the account.
* @return Whether the account has collateral deposited.
*/
function _accountHasCollateral(address account) internal view returns(bool) {
return _hasCollateral(tokenData[account]);
}
/**
* @dev Internal function to get if an account has collateral deposited.
* @param data Token data from an account.
* @return Whether the account has collateral deposited.
*/
function _hasCollateral(TokenCollateralized storage data) internal view returns(bool) {
return data.amount > 0;
}
/**
* @dev Internal function to get if the address is for Ethereum (0x0).
* @param _address Address to be checked.
* @return Whether the address is for Ethereum.
*/
function _isEther(address _address) internal pure returns(bool) {
return _address == address(0);
}
/**
* @dev Internal function to get the token name.
* The token name is assembled with the token data:
* ACO UNDERLYING_SYMBOL-EXPIRYTIME-STRIKE_PRICE_STRIKE_ASSET_SYMBOL-TYPE
* @return The token name.
*/
function _name() internal view returns(string memory) {
return string(abi.encodePacked(
"ACO ",
underlyingSymbol,
"-",
_getFormattedStrikePrice(),
strikeAssetSymbol,
"-",
_getType(),
"-",
_getFormattedExpiryTime()
));
}
/**
* @dev Internal function to get the token type description.
* @return The token type description.
*/
function _getType() internal view returns(string memory) {
if (isCall) {
return "C";
} else {
return "P";
}
}
/**
* @dev Internal function to get the expiry time formatted.
* @return The expiry time formatted.
*/
function _getFormattedExpiryTime() internal view returns(string memory) {
(uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute,) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(expiryTime);
return string(abi.encodePacked(
_getNumberWithTwoCaracters(day),
_getMonthFormatted(month),
_getYearFormatted(year),
"-",
_getNumberWithTwoCaracters(hour),
_getNumberWithTwoCaracters(minute),
"UTC"
));
}
/**
* @dev Internal function to get the year formatted with 2 characters.
* @return The year formatted.
*/
function _getYearFormatted(uint256 year) internal pure returns(string memory) {
bytes memory yearBytes = bytes(Strings.toString(year));
bytes memory result = new bytes(2);
uint256 startIndex = yearBytes.length - 2;
for (uint256 i = startIndex; i < yearBytes.length; i++) {
result[i - startIndex] = yearBytes[i];
}
return string(result);
}
/**
* @dev Internal function to get the month abbreviation.
* @return The month abbreviation.
*/
function _getMonthFormatted(uint256 month) internal pure returns(string memory) {
if (month == 1) {
return "JAN";
} else if (month == 2) {
return "FEB";
} else if (month == 3) {
return "MAR";
} else if (month == 4) {
return "APR";
} else if (month == 5) {
return "MAY";
} else if (month == 6) {
return "JUN";
} else if (month == 7) {
return "JUL";
} else if (month == 8) {
return "AUG";
} else if (month == 9) {
return "SEP";
} else if (month == 10) {
return "OCT";
} else if (month == 11) {
return "NOV";
} else if (month == 12) {
return "DEC";
} else {
return "INVALID";
}
}
/**
* @dev Internal function to get the number with 2 characters.
* @return The 2 characters for the number.
*/
function _getNumberWithTwoCaracters(uint256 number) internal pure returns(string memory) {
string memory _string = Strings.toString(number);
if (number < 10) {
return string(abi.encodePacked("0", _string));
} else {
return _string;
}
}
/**
* @dev Internal function to get the strike price formatted.
* @return The strike price formatted.
*/
function _getFormattedStrikePrice() internal view returns(string memory) {
uint256 digits;
uint256 count;
int256 representativeAt = -1;
uint256 addPointAt = 0;
uint256 temp = strikePrice;
uint256 number = strikePrice;
while (temp != 0) {
if (representativeAt == -1 && (temp % 10 != 0 || count == uint256(strikeAssetDecimals))) {
representativeAt = int256(digits);
number = temp;
}
if (representativeAt >= 0) {
if (count == uint256(strikeAssetDecimals)) {
addPointAt = digits;
}
digits++;
}
temp /= 10;
count++;
}
if (count <= uint256(strikeAssetDecimals)) {
digits = digits + 2 + uint256(strikeAssetDecimals) - count;
addPointAt = digits - 2;
} else if (addPointAt > 0) {
digits++;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = number;
for (uint256 i = 0; i < digits; ++i) {
if (i > 0 && i == addPointAt) {
buffer[index--] = byte(".");
} else if (number == 0) {
buffer[index--] = byte("0");
} else {
if (representativeAt <= int256(i)) {
buffer[index--] = byte(uint8(48 + number % 10));
}
number /= 10;
}
}
return string(buffer);
}
/**
* @dev Internal function to the asset decimals.
* @param asset Address of the asset.
* @return The asset decimals.
*/
function _getAssetDecimals(address asset) internal view returns(uint8) {
if (_isEther(asset)) {
return uint8(18);
} else {
(bool success, bytes memory returndata) = asset.staticcall(abi.encodeWithSignature("decimals()"));
require(success, "ACOToken::_getAssetDecimals: Invalid asset decimals");
return abi.decode(returndata, (uint8));
}
}
/**
* @dev Internal function to the asset symbol.
* @param asset Address of the asset.
* @return The asset symbol.
*/
function _getAssetSymbol(address asset) internal view returns(string memory) {
if (_isEther(asset)) {
return "ETH";
} else {
(bool success, bytes memory returndata) = asset.staticcall(abi.encodeWithSignature("symbol()"));
require(success, "ACOToken::_getAssetSymbol: Invalid asset symbol");
return abi.decode(returndata, (string));
}
}
/**
* @dev Internal function to transfer ERC20 tokens.
* @param token Address of the token.
* @param recipient Address of the transfer destination.
* @param amount Amount to transfer.
*/
function _transferERC20(address token, address recipient, uint256 amount) internal {
(bool success, bytes memory returndata) = token.call(abi.encodeWithSelector(_transferSelector, recipient, amount));
require(success && (returndata.length == 0 || abi.decode(returndata, (bool))), "ACOToken::_transferERC20");
}
/**
* @dev Internal function to call transferFrom on ERC20 tokens.
* @param token Address of the token.
* @param sender Address of the sender.
* @param recipient Address of the transfer destination.
* @param amount Amount to transfer.
*/
function _transferFromERC20(address token, address sender, address recipient, uint256 amount) internal {
(bool success, bytes memory returndata) = token.call(abi.encodeWithSelector(_transferFromSelector, sender, recipient, amount));
require(success && (returndata.length == 0 || abi.decode(returndata, (bool))), "ACOToken::_transferFromERC20");
}
}
| Internal function to exercise the assignable tokens from an account and transfer to its address the respective payment. account Address of the account. tokenAmount Amount of tokens. exerciseAccount Address of the account that is exercising. return Remaining amount of tokens./ | function _exerciseAccount(address account, uint256 tokenAmount, address exerciseAccount) internal returns(uint256) {
uint256 available = _getAssignableAmount(account);
if (available > 0) {
TokenCollateralized storage data = tokenData[account];
uint256 valueToTransfer;
if (available < tokenAmount) {
valueToTransfer = available;
tokenAmount = tokenAmount.sub(available);
valueToTransfer = tokenAmount;
tokenAmount = 0;
}
(address exerciseAsset, uint256 amount) = getExerciseData(valueToTransfer);
data.amount = data.amount.sub(valueToTransfer);
_removeCollateralDataIfNecessary(account);
if (_isEther(exerciseAsset)) {
payable(account).transfer(amount);
_transferERC20(exerciseAsset, account, amount);
}
emit Assigned(account, exerciseAccount, amount, valueToTransfer);
}
return tokenAmount;
}
| 13,466,130 |
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "../../core/DaoRegistry.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
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 IVoting {
enum VotingState {
NOT_STARTED,
TIE,
PASS,
NOT_PASS,
IN_PROGRESS,
GRACE_PERIOD
}
function getAdapterName() external pure returns (string memory);
function startNewVotingForProposal(
DaoRegistry dao,
bytes32 proposalId,
bytes calldata data
) external;
function getSenderAddress(
DaoRegistry dao,
address actionId,
bytes memory data,
address sender
) external returns (address);
function voteResult(DaoRegistry dao, bytes32 proposalId)
external
returns (VotingState state);
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "../../core/DaoRegistry.sol";
import "../../extensions/bank/Bank.sol";
import "../../core/DaoConstants.sol";
import "../../helpers/GuildKickHelper.sol";
import "../../guards/MemberGuard.sol";
import "../../guards/AdapterGuard.sol";
import "../interfaces/IVoting.sol";
import "./OffchainVoting.sol";
import "../../utils/Signatures.sol";
/**
MIT License
Copyright (c) 2021 Openlaw
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.
*/
contract KickBadReporterAdapter is DaoConstants, MemberGuard {
/*
* default fallback function to prevent from sending ether to the contract
*/
receive() external payable {
revert("fallback revert");
}
function sponsorProposal(
DaoRegistry dao,
bytes32 proposalId,
bytes calldata data
) external {
OffchainVotingContract votingContract =
OffchainVotingContract(dao.getAdapterAddress(VOTING));
address sponsoredBy =
votingContract.getSenderAddress(
dao,
address(this),
data,
msg.sender
);
_sponsorProposal(dao, proposalId, data, sponsoredBy, votingContract);
}
function _sponsorProposal(
DaoRegistry dao,
bytes32 proposalId,
bytes memory data,
address sponsoredBy,
OffchainVotingContract votingContract
) internal onlyMember2(dao, sponsoredBy) {
votingContract.sponsorChallengeProposal(dao, proposalId, sponsoredBy);
votingContract.startNewVotingForProposal(dao, proposalId, data);
}
function processProposal(DaoRegistry dao, bytes32 proposalId) external {
OffchainVotingContract votingContract =
OffchainVotingContract(dao.getAdapterAddress(VOTING));
votingContract.processChallengeProposal(dao, proposalId);
IVoting.VotingState votingState =
votingContract.voteResult(dao, proposalId);
// the person has been kicked out
if (votingState == IVoting.VotingState.PASS) {
(, address challengeAddress) =
votingContract.getChallengeDetails(dao, proposalId);
GuildKickHelper.rageKick(dao, challengeAddress);
} else if (
votingState == IVoting.VotingState.NOT_PASS ||
votingState == IVoting.VotingState.TIE
) {
(uint256 units, address challengeAddress) =
votingContract.getChallengeDetails(dao, proposalId);
BankExtension bank = BankExtension(dao.getExtensionAddress(BANK));
bank.subtractFromBalance(challengeAddress, LOOT, units);
bank.addToBalance(challengeAddress, UNITS, units);
} else {
revert("vote not finished yet");
}
}
}
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT
import "../../core/DaoRegistry.sol";
import "../../extensions/bank/Bank.sol";
import "../../core/DaoConstants.sol";
import "../../guards/MemberGuard.sol";
import "../../guards/AdapterGuard.sol";
import "../../utils/Signatures.sol";
import "../interfaces/IVoting.sol";
import "./Voting.sol";
import "./KickBadReporterAdapter.sol";
import "./SnapshotProposalContract.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
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.
*/
contract OffchainVotingContract is
IVoting,
DaoConstants,
MemberGuard,
AdapterGuard,
Signatures,
Ownable
{
enum BadNodeError {
OK,
WRONG_PROPOSAL_ID,
INVALID_CHOICE,
AFTER_VOTING_PERIOD,
BAD_SIGNATURE
}
struct ProposalChallenge {
address reporter;
uint256 units;
}
uint256 public constant NB_CHOICES = 2;
SnapshotProposalContract private _snapshotContract;
KickBadReporterAdapter private _handleBadReporterAdapter;
string public constant VOTE_RESULT_NODE_TYPE =
"Message(uint64 timestamp,uint88 nbYes,uint88 nbNo,uint32 index,uint32 choice,bytes32 proposalId)";
string public constant ADAPTER_NAME = "OffchainVotingContract";
string public constant VOTE_RESULT_ROOT_TYPE = "Message(bytes32 root)";
bytes32 public constant VOTE_RESULT_NODE_TYPEHASH =
keccak256(abi.encodePacked(VOTE_RESULT_NODE_TYPE));
bytes32 public constant VOTE_RESULT_ROOT_TYPEHASH =
keccak256(abi.encodePacked(VOTE_RESULT_ROOT_TYPE));
bytes32 constant VotingPeriod = keccak256("offchainvoting.votingPeriod");
bytes32 constant GracePeriod = keccak256("offchainvoting.gracePeriod");
bytes32 constant FallbackThreshold =
keccak256("offchainvoting.fallbackThreshold");
struct VoteStepParams {
uint256 previousYes;
uint256 previousNo;
bytes32 proposalId;
}
struct Voting {
uint256 snapshot;
address reporter;
bytes32 resultRoot;
uint256 nbYes;
uint256 nbNo;
uint256 startingTime;
uint256 gracePeriodStartingTime;
bool isChallenged;
bool forceFailed;
mapping(address => bool) fallbackVotes;
uint256 fallbackVotesCount;
}
struct VoteResultNode {
uint32 choice;
uint64 index;
uint64 timestamp;
uint88 nbNo;
uint88 nbYes;
bytes sig;
bytes32 proposalId;
bytes32[] proof;
}
modifier onlyBadReporterAdapter() {
require(msg.sender == address(_handleBadReporterAdapter), "only:hbra");
_;
}
VotingContract public fallbackVoting;
mapping(address => mapping(bytes32 => ProposalChallenge)) challengeProposals;
mapping(address => mapping(bytes32 => Voting)) public votes;
constructor(
VotingContract _c,
SnapshotProposalContract _spc,
KickBadReporterAdapter _hbra,
address _owner
) {
require(address(_c) != address(0x0), "voting contract");
require(address(_spc) != address(0x0), "snapshot proposal");
require(address(_hbra) != address(0x0), "handle bad reporter");
fallbackVoting = _c;
_snapshotContract = _spc;
_handleBadReporterAdapter = _hbra;
Ownable(_owner);
}
function adminFailProposal(DaoRegistry dao, bytes32 proposalId)
external
onlyOwner
{
Voting storage vote = votes[address(dao)][proposalId];
require(vote.startingTime > 0, "proposal has not started yet");
vote.forceFailed = true;
}
function hashResultRoot(
DaoRegistry dao,
address actionId,
bytes32 resultRoot
) public view returns (bytes32) {
return
keccak256(
abi.encodePacked(
"\x19\x01",
_snapshotContract.DOMAIN_SEPARATOR(dao, actionId),
keccak256(abi.encode(VOTE_RESULT_ROOT_TYPEHASH, resultRoot))
)
);
}
function getAdapterName() external pure override returns (string memory) {
return ADAPTER_NAME;
}
function getChallengeDetails(DaoRegistry dao, bytes32 proposalId)
external
view
returns (uint256, address)
{
return (
challengeProposals[address(dao)][proposalId].units,
challengeProposals[address(dao)][proposalId].reporter
);
}
function hashVotingResultNode(VoteResultNode memory node)
public
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
VOTE_RESULT_NODE_TYPEHASH,
node.timestamp,
node.nbYes,
node.nbNo,
node.index,
node.choice,
node.proposalId
)
);
}
function nodeHash(
DaoRegistry dao,
address actionId,
VoteResultNode memory node
) public view returns (bytes32) {
return
keccak256(
abi.encodePacked(
"\x19\x01",
_snapshotContract.DOMAIN_SEPARATOR(dao, actionId),
hashVotingResultNode(node)
)
);
}
function configureDao(
DaoRegistry dao,
uint256 votingPeriod,
uint256 gracePeriod,
uint256 fallbackThreshold
) external onlyAdapter(dao) {
dao.setConfiguration(VotingPeriod, votingPeriod);
dao.setConfiguration(GracePeriod, gracePeriod);
dao.setConfiguration(FallbackThreshold, fallbackThreshold);
}
/**
What needs to be checked before submitting a vote result
- if the grace period has ended, do nothing
- if it's the first result, is this a right time to submit it?
* is the diff between nbYes and nbNo +50% of the votes ?
* is this after the voting period ?
- if we already have a result that has been challenged
* same as if there were no result yet
- if we already have a result that has not been challenged
* is the new one heavier than the previous one ?
**/
function submitVoteResult(
DaoRegistry dao,
bytes32 proposalId,
bytes32 resultRoot,
VoteResultNode memory result,
bytes memory rootSig
) external {
Voting storage vote = votes[address(dao)][proposalId];
require(vote.snapshot > 0, "vote:not started");
if (vote.resultRoot == bytes32(0) || vote.isChallenged) {
require(
_readyToSubmitResult(dao, vote, result.nbYes, result.nbNo),
"vote:notReadyToSubmitResult"
);
}
(address adapterAddress, ) = dao.proposals(proposalId);
address reporter =
ECDSA.recover(
hashResultRoot(dao, adapterAddress, resultRoot),
rootSig
);
address memberAddr = dao.getAddressIfDelegated(reporter);
require(isActiveMember(dao, memberAddr), "not active member");
BankExtension bank = BankExtension(dao.getExtensionAddress(BANK));
uint256 nbMembers =
bank.getPriorAmount(TOTAL, MEMBER_COUNT, vote.snapshot);
require(nbMembers - 1 == result.index, "index:member_count mismatch");
require(
getBadNodeError(
dao,
proposalId,
true,
resultRoot,
vote.snapshot,
vote.gracePeriodStartingTime,
result
) == BadNodeError.OK,
"bad result"
);
require(
vote.nbYes + vote.nbNo < result.nbYes + result.nbNo,
"result weight too low"
);
if (
vote.gracePeriodStartingTime == 0 ||
vote.nbNo > vote.nbYes != result.nbNo > result.nbYes // check whether the new result changes the outcome
) {
vote.gracePeriodStartingTime = block.timestamp;
}
vote.nbNo = result.nbNo;
vote.nbYes = result.nbYes;
vote.resultRoot = resultRoot;
vote.reporter = memberAddr;
vote.isChallenged = false;
}
function _readyToSubmitResult(
DaoRegistry dao,
Voting storage vote,
uint256 nbYes,
uint256 nbNo
) internal view returns (bool) {
if (vote.forceFailed) {
return false;
}
BankExtension bank = BankExtension(dao.getExtensionAddress(BANK));
uint256 totalWeight = bank.getPriorAmount(TOTAL, UNITS, vote.snapshot);
uint256 unvotedWeights = totalWeight - nbYes - nbNo;
uint256 diff;
if (nbYes > nbNo) {
diff = nbYes - nbNo;
} else {
diff = nbNo - nbYes;
}
if (diff > unvotedWeights) {
return true;
}
uint256 votingPeriod = dao.getConfiguration(VotingPeriod);
return vote.startingTime + votingPeriod <= block.timestamp;
}
function getSenderAddress(
DaoRegistry dao,
address actionId,
bytes memory data,
address
) external view override returns (address) {
SnapshotProposalContract.ProposalMessage memory proposal =
abi.decode(data, (SnapshotProposalContract.ProposalMessage));
return
ECDSA.recover(
_snapshotContract.hashMessage(dao, actionId, proposal),
proposal.sig
);
}
function startNewVotingForProposal(
DaoRegistry dao,
bytes32 proposalId,
bytes memory data
) public override onlyAdapter(dao) {
SnapshotProposalContract.ProposalMessage memory proposal =
abi.decode(data, (SnapshotProposalContract.ProposalMessage));
(bool success, uint256 blockNumber) =
_stringToUint(proposal.payload.snapshot);
require(success, "snapshot conversion error");
BankExtension bank = BankExtension(dao.getExtensionAddress(BANK));
bytes32 proposalHash =
_snapshotContract.hashMessage(dao, msg.sender, proposal);
address addr = ECDSA.recover(proposalHash, proposal.sig);
address memberAddr = dao.getAddressIfDelegated(addr);
require(bank.balanceOf(memberAddr, UNITS) > 0, "noActiveMember");
require(
blockNumber <= block.number,
"snapshot block number should not be in the future"
);
require(blockNumber > 0, "block number cannot be 0");
votes[address(dao)][proposalId].startingTime = block.timestamp;
votes[address(dao)][proposalId].snapshot = blockNumber;
}
function _fallbackVotingActivated(
DaoRegistry dao,
uint256 fallbackVotesCount
) internal view returns (bool) {
return
fallbackVotesCount >
(dao.getNbMembers() * 100) /
dao.getConfiguration(FallbackThreshold);
}
/**
possible results here:
0: has not started
1: tie
2: pass
3: not pass
4: in progress
*/
function voteResult(DaoRegistry dao, bytes32 proposalId)
external
view
override
returns (VotingState state)
{
Voting storage vote = votes[address(dao)][proposalId];
if (vote.startingTime == 0) {
return VotingState.NOT_STARTED;
}
if (vote.forceFailed) {
return VotingState.NOT_PASS;
}
if (_fallbackVotingActivated(dao, vote.fallbackVotesCount)) {
return fallbackVoting.voteResult(dao, proposalId);
}
if (vote.isChallenged) {
return VotingState.IN_PROGRESS;
}
uint256 votingPeriod = dao.getConfiguration(VotingPeriod);
//if the vote has started but the voting period has not passed yet, it's in progress
if (block.timestamp < vote.startingTime + votingPeriod) {
return VotingState.IN_PROGRESS;
}
uint256 gracePeriod = dao.getConfiguration(GracePeriod);
//if no result have been submitted but we are before grace + voting period, then the proposal is GRACE_PERIOD
if (
vote.gracePeriodStartingTime == 0 &&
block.timestamp < vote.startingTime + gracePeriod + votingPeriod
) {
return VotingState.GRACE_PERIOD;
}
//if the vote has started but the voting period has not passed yet, it's in progress
if (block.timestamp < vote.gracePeriodStartingTime + gracePeriod) {
return VotingState.GRACE_PERIOD;
}
if (vote.nbYes > vote.nbNo) {
return VotingState.PASS;
}
if (vote.nbYes < vote.nbNo) {
return VotingState.NOT_PASS;
}
return VotingState.TIE;
}
function challengeBadFirstNode(
DaoRegistry dao,
bytes32 proposalId,
VoteResultNode memory node
) external {
require(node.index == 0, "only first node");
Voting storage vote = votes[address(dao)][proposalId];
(address adapterAddress, ) = dao.proposals(proposalId);
require(vote.resultRoot != bytes32(0), "no result available yet!");
bytes32 hashCurrent = nodeHash(dao, adapterAddress, node);
//check that the step is indeed part of the result
require(
MerkleProof.verify(node.proof, vote.resultRoot, hashCurrent),
"proof:bad"
);
(address actionId, ) = dao.proposals(proposalId);
if (_checkStep(dao, actionId, node, VoteStepParams(0, 0, proposalId))) {
_challengeResult(dao, proposalId);
}
}
function challengeBadNode(
DaoRegistry dao,
bytes32 proposalId,
VoteResultNode memory node
) external {
Voting storage vote = votes[address(dao)][proposalId];
if (
getBadNodeError(
dao,
proposalId,
false,
vote.resultRoot,
vote.snapshot,
vote.gracePeriodStartingTime,
node
) != BadNodeError.OK
) {
_challengeResult(dao, proposalId);
}
}
function _isValidChoice(uint256 choice) internal pure returns (bool) {
return choice > 0 && choice < NB_CHOICES + 1;
}
function getBadNodeError(
DaoRegistry dao,
bytes32 proposalId,
bool submitNewVote,
bytes32 resultRoot,
uint256 blockNumber,
uint256 gracePeriodStartingTime,
VoteResultNode memory node
) public view returns (BadNodeError) {
(address adapterAddress, ) = dao.proposals(proposalId);
require(resultRoot != bytes32(0), "no result available yet!");
bytes32 hashCurrent = nodeHash(dao, adapterAddress, node);
//check that the step is indeed part of the result
require(
MerkleProof.verify(node.proof, resultRoot, hashCurrent),
"proof:bad"
);
address account = dao.getMemberAddress(node.index);
//return 1 if yes, 2 if no and 0 if the vote is incorrect
address voter = dao.getPriorDelegateKey(account, blockNumber);
(address actionId, ) = dao.proposals(proposalId);
//invalid choice
if (
(node.sig.length == 0 && node.choice != 0) || // no vote
(node.sig.length > 0 && !_isValidChoice(node.choice))
) {
return BadNodeError.INVALID_CHOICE;
}
//invalid proposal hash
if (node.proposalId != proposalId) {
return BadNodeError.WRONG_PROPOSAL_ID;
}
//has voted outside of the voting time
if (!submitNewVote && node.timestamp > gracePeriodStartingTime) {
return BadNodeError.AFTER_VOTING_PERIOD;
}
//bad signature
if (
node.sig.length > 0 && // a vote has happened
!_hasVoted(
dao,
actionId,
voter,
node.timestamp,
node.proposalId,
node.choice,
node.sig
)
) {
return BadNodeError.BAD_SIGNATURE;
}
return BadNodeError.OK;
}
function challengeBadStep(
DaoRegistry dao,
bytes32 proposalId,
VoteResultNode memory nodePrevious,
VoteResultNode memory nodeCurrent
) external {
Voting storage vote = votes[address(dao)][proposalId];
bytes32 resultRoot = vote.resultRoot;
(address adapterAddress, ) = dao.proposals(proposalId);
require(resultRoot != bytes32(0), "no result available yet!");
bytes32 hashCurrent = nodeHash(dao, adapterAddress, nodeCurrent);
bytes32 hashPrevious = nodeHash(dao, adapterAddress, nodePrevious);
require(
MerkleProof.verify(nodeCurrent.proof, resultRoot, hashCurrent),
"proof check for current invalid for current node"
);
require(
MerkleProof.verify(nodePrevious.proof, resultRoot, hashPrevious),
"proof check for previous invalid for previous node"
);
require(
nodeCurrent.index == nodePrevious.index + 1,
"those nodes are not consecutive"
);
(address actionId, ) = dao.proposals(proposalId);
VoteStepParams memory params =
VoteStepParams(nodePrevious.nbYes, nodePrevious.nbNo, proposalId);
if (_checkStep(dao, actionId, nodeCurrent, params)) {
_challengeResult(dao, proposalId);
}
}
function requestFallback(DaoRegistry dao, bytes32 proposalId)
external
onlyMember(dao)
{
require(
votes[address(dao)][proposalId].fallbackVotes[msg.sender] == false,
"the member has already voted for this vote to fallback"
);
votes[address(dao)][proposalId].fallbackVotes[msg.sender] = true;
votes[address(dao)][proposalId].fallbackVotesCount += 1;
if (
_fallbackVotingActivated(
dao,
votes[address(dao)][proposalId].fallbackVotesCount
)
) {
fallbackVoting.startNewVotingForProposal(dao, proposalId, "");
}
}
function _checkStep(
DaoRegistry dao,
address actionId,
VoteResultNode memory node,
VoteStepParams memory params
) internal view returns (bool) {
Voting storage vote = votes[address(dao)][params.proposalId];
address account = dao.getMemberAddress(node.index);
address voter = dao.getPriorDelegateKey(account, vote.snapshot);
BankExtension bank = BankExtension(dao.getExtensionAddress(BANK));
uint256 weight = bank.getPriorAmount(account, UNITS, vote.snapshot);
if (node.choice == 0) {
if (params.previousYes != node.nbYes) {
return true;
} else if (params.previousNo != node.nbNo) {
return true;
}
}
if (
_hasVoted(
dao,
actionId,
voter,
node.timestamp,
node.proposalId,
1,
node.sig
)
) {
if (params.previousYes + weight != node.nbYes) {
return true;
} else if (params.previousNo != node.nbNo) {
return true;
}
}
if (
_hasVoted(
dao,
actionId,
voter,
node.timestamp,
node.proposalId,
2,
node.sig
)
) {
if (params.previousYes != node.nbYes) {
return true;
} else if (params.previousNo + weight != node.nbNo) {
return true;
}
}
return false;
}
function sponsorChallengeProposal(
DaoRegistry dao,
bytes32 proposalId,
address sponsoredBy
) external onlyBadReporterAdapter {
dao.sponsorProposal(proposalId, sponsoredBy, address(this));
}
function processChallengeProposal(DaoRegistry dao, bytes32 proposalId)
external
onlyBadReporterAdapter
{
dao.processProposal(proposalId);
}
function _challengeResult(DaoRegistry dao, bytes32 proposalId) internal {
BankExtension bank = BankExtension(dao.getExtensionAddress(BANK));
votes[address(dao)][proposalId].isChallenged = true;
address challengedReporter = votes[address(dao)][proposalId].reporter;
bytes32 challengeProposalId =
keccak256(
abi.encodePacked(
proposalId,
votes[address(dao)][proposalId].resultRoot
)
);
dao.submitProposal(challengeProposalId);
uint256 units = bank.balanceOf(challengedReporter, UNITS);
challengeProposals[address(dao)][
challengeProposalId
] = ProposalChallenge(challengedReporter, units);
// Burns / subtracts from member's balance the number of units to burn.
bank.subtractFromBalance(challengedReporter, UNITS, units);
// Burns / subtracts from member's balance the number of loot to burn.
// bank.subtractFromBalance(memberToKick, LOOT, kick.lootToBurn);
bank.addToBalance(challengedReporter, LOOT, units);
}
function _hasVoted(
DaoRegistry dao,
address actionId,
address voter,
uint64 timestamp,
bytes32 proposalId,
uint32 choiceIdx,
bytes memory sig
) internal view returns (bool) {
bytes32 voteHash =
_snapshotContract.hashVote(
dao,
actionId,
SnapshotProposalContract.VoteMessage(
timestamp,
SnapshotProposalContract.VotePayload(choiceIdx, proposalId)
)
);
return ECDSA.recover(voteHash, sig) == voter;
}
function _stringToUint(string memory s)
internal
pure
returns (bool success, uint256 result)
{
bytes memory b = bytes(s);
result = 0;
success = false;
for (uint256 i = 0; i < b.length; i++) {
if (uint8(b[i]) >= 48 && uint8(b[i]) <= 57) {
result = result * 10 + (uint8(b[i]) - 48);
success = true;
} else {
result = 0;
success = false;
break;
}
}
return (success, result);
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "../../core/DaoRegistry.sol";
import "../../extensions/bank/Bank.sol";
import "../../core/DaoConstants.sol";
import "../../guards/MemberGuard.sol";
import "../../guards/AdapterGuard.sol";
import "../interfaces/IVoting.sol";
import "./Voting.sol";
/**
MIT License
Copyright (c) 2021 Openlaw
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.
*/
contract SnapshotProposalContract {
string public constant EIP712_DOMAIN =
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,address actionId)";
string public constant PROPOSAL_MESSAGE_TYPE =
"Message(uint64 timestamp,bytes32 spaceHash,MessagePayload payload)MessagePayload(bytes32 nameHash,bytes32 bodyHash,string[] choices,uint64 start,uint64 end,string snapshot)";
string public constant PROPOSAL_PAYLOAD_TYPE =
"MessagePayload(bytes32 nameHash,bytes32 bodyHash,string[] choices,uint64 start,uint64 end,string snapshot)";
string public constant VOTE_MESSAGE_TYPE =
"Message(uint64 timestamp,MessagePayload payload)MessagePayload(uint32 choice,bytes32 proposalId)";
string public constant VOTE_PAYLOAD_TYPE =
"MessagePayload(uint32 choice,bytes32 proposalId)";
bytes32 public constant EIP712_DOMAIN_TYPEHASH =
keccak256(abi.encodePacked(EIP712_DOMAIN));
bytes32 public constant PROPOSAL_MESSAGE_TYPEHASH =
keccak256(abi.encodePacked(PROPOSAL_MESSAGE_TYPE));
bytes32 public constant PROPOSAL_PAYLOAD_TYPEHASH =
keccak256(abi.encodePacked(PROPOSAL_PAYLOAD_TYPE));
bytes32 public constant VOTE_MESSAGE_TYPEHASH =
keccak256(abi.encodePacked(VOTE_MESSAGE_TYPE));
bytes32 public constant VOTE_PAYLOAD_TYPEHASH =
keccak256(abi.encodePacked(VOTE_PAYLOAD_TYPE));
uint256 public chainId;
function DOMAIN_SEPARATOR(DaoRegistry dao, address actionId)
public
view
returns (bytes32)
{
return
keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256("Snapshot Message"), // string name
keccak256("4"), // string version
chainId, // uint256 chainId
address(dao), // address verifyingContract,
actionId
)
);
}
struct ProposalMessage {
uint256 timestamp;
bytes32 spaceHash;
ProposalPayload payload;
bytes sig;
}
struct ProposalPayload {
bytes32 nameHash;
bytes32 bodyHash;
string[] choices;
uint256 start;
uint256 end;
string snapshot;
}
struct VoteMessage {
uint256 timestamp;
VotePayload payload;
}
struct VotePayload {
uint32 choice;
bytes32 proposalId;
}
constructor(uint256 _chainId) {
chainId = _chainId;
}
function hashMessage(
DaoRegistry dao,
address actionId,
ProposalMessage memory message
) public view returns (bytes32) {
return
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(dao, actionId),
hashProposalMessage(message)
)
);
}
function hashProposalMessage(ProposalMessage memory message)
public
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
PROPOSAL_MESSAGE_TYPEHASH,
message.timestamp,
message.spaceHash,
hashProposalPayload(message.payload)
)
);
}
function hashProposalPayload(ProposalPayload memory payload)
public
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
PROPOSAL_PAYLOAD_TYPEHASH,
payload.nameHash,
payload.bodyHash,
keccak256(abi.encodePacked(toHashArray(payload.choices))),
payload.start,
payload.end,
keccak256(abi.encodePacked(payload.snapshot))
)
);
}
function hashVote(
DaoRegistry dao,
address actionId,
VoteMessage memory message
) public view returns (bytes32) {
return
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(dao, actionId),
hashVoteInternal(message)
)
);
}
function hashVoteInternal(VoteMessage memory message)
public
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
VOTE_MESSAGE_TYPEHASH,
message.timestamp,
hashVotePayload(message.payload)
)
);
}
function hashVotePayload(VotePayload memory payload)
public
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
VOTE_PAYLOAD_TYPEHASH,
payload.choice,
payload.proposalId
)
);
}
function toHashArray(string[] memory arr)
internal
pure
returns (bytes32[] memory result)
{
result = new bytes32[](arr.length);
for (uint256 i = 0; i < arr.length; i++) {
result[i] = keccak256(abi.encodePacked(arr[i]));
}
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "../../core/DaoRegistry.sol";
import "../../core/DaoConstants.sol";
import "../../extensions/bank/Bank.sol";
import "../../guards/MemberGuard.sol";
import "../../guards/AdapterGuard.sol";
import "../interfaces/IVoting.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
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.
*/
contract VotingContract is IVoting, DaoConstants, MemberGuard, AdapterGuard {
struct Voting {
uint256 nbYes;
uint256 nbNo;
uint256 startingTime;
uint256 blockNumber;
mapping(address => uint256) votes;
}
bytes32 constant VotingPeriod = keccak256("voting.votingPeriod");
bytes32 constant GracePeriod = keccak256("voting.gracePeriod");
mapping(address => mapping(bytes32 => Voting)) public votes;
string public constant ADAPTER_NAME = "VotingContract";
function getAdapterName() external pure override returns (string memory) {
return ADAPTER_NAME;
}
function configureDao(
DaoRegistry dao,
uint256 votingPeriod,
uint256 gracePeriod
) external onlyAdapter(dao) {
dao.setConfiguration(VotingPeriod, votingPeriod);
dao.setConfiguration(GracePeriod, gracePeriod);
}
//voting data is not used for pure onchain voting
function startNewVotingForProposal(
DaoRegistry dao,
bytes32 proposalId,
bytes calldata
) external override onlyAdapter(dao) {
//it is called from Registry
// compute startingPeriod for proposal
Voting storage vote = votes[address(dao)][proposalId];
vote.startingTime = block.timestamp;
vote.blockNumber = block.number;
}
function getSenderAddress(
DaoRegistry,
address,
bytes memory,
address sender
) external pure override returns (address) {
return sender;
}
function submitVote(
DaoRegistry dao,
bytes32 proposalId,
uint256 voteValue
) external onlyMember(dao) {
require(
dao.getProposalFlag(proposalId, DaoRegistry.ProposalFlag.SPONSORED),
"the proposal has not been sponsored yet"
);
require(
!dao.getProposalFlag(
proposalId,
DaoRegistry.ProposalFlag.PROCESSED
),
"the proposal has already been processed"
);
require(
voteValue < 3 && voteValue > 0,
"only yes (1) and no (2) are possible values"
);
Voting storage vote = votes[address(dao)][proposalId];
require(
vote.startingTime > 0,
"this proposalId has no vote going on at the moment"
);
require(
block.timestamp <
vote.startingTime + dao.getConfiguration(VotingPeriod),
"vote has already ended"
);
address memberAddr = dao.getAddressIfDelegated(msg.sender);
require(vote.votes[memberAddr] == 0, "member has already voted");
BankExtension bank = BankExtension(dao.getExtensionAddress(BANK));
uint256 correctWeight =
bank.getPriorAmount(memberAddr, UNITS, vote.blockNumber);
vote.votes[memberAddr] = voteValue;
if (voteValue == 1) {
vote.nbYes = vote.nbYes + correctWeight;
} else if (voteValue == 2) {
vote.nbNo = vote.nbNo + correctWeight;
}
}
//Public Functions
/**
possible results here:
0: has not started
1: tie
2: pass
3: not pass
4: in progress
*/
function voteResult(DaoRegistry dao, bytes32 proposalId)
external
view
override
returns (VotingState state)
{
Voting storage vote = votes[address(dao)][proposalId];
if (vote.startingTime == 0) {
return VotingState.NOT_STARTED;
}
if (
block.timestamp <
vote.startingTime + dao.getConfiguration(VotingPeriod)
) {
return VotingState.IN_PROGRESS;
}
if (
block.timestamp <
vote.startingTime +
dao.getConfiguration(VotingPeriod) +
dao.getConfiguration(GracePeriod)
) {
return VotingState.GRACE_PERIOD;
}
if (vote.nbYes > vote.nbNo) {
return VotingState.PASS;
} else if (vote.nbYes < vote.nbNo) {
return VotingState.NOT_PASS;
} else {
return VotingState.TIE;
}
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
/**
MIT License
Copyright (c) 2020 Openlaw
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.
*/
abstract contract DaoConstants {
// Adapters
bytes32 internal constant VOTING = keccak256("voting");
bytes32 internal constant ONBOARDING = keccak256("onboarding");
bytes32 internal constant NONVOTING_ONBOARDING =
keccak256("nonvoting-onboarding");
bytes32 internal constant TRIBUTE = keccak256("tribute");
bytes32 internal constant FINANCING = keccak256("financing");
bytes32 internal constant MANAGING = keccak256("managing");
bytes32 internal constant RAGEQUIT = keccak256("ragequit");
bytes32 internal constant GUILDKICK = keccak256("guildkick");
bytes32 internal constant EXECUTION = keccak256("execution");
bytes32 internal constant CONFIGURATION = keccak256("configuration");
bytes32 internal constant DISTRIBUTE = keccak256("distribute");
bytes32 internal constant TRIBUTE_NFT = keccak256("tribute-nft");
// Extensions
bytes32 internal constant BANK = keccak256("bank");
bytes32 internal constant NFT = keccak256("nft");
bytes32 internal constant ERC20_EXT = keccak256("erc20-ext");
// Reserved Addresses
address internal constant GUILD = address(0xdead);
address internal constant TOTAL = address(0xbabe);
address internal constant ESCROW = address(0x4bec);
address internal constant UNITS = address(0xFF1CE);
address internal constant LOOT = address(0xB105F00D);
address internal constant ETH_TOKEN = address(0x0);
address internal constant MEMBER_COUNT = address(0xDECAFBAD);
uint8 internal constant MAX_TOKENS_GUILD_BANK = 200;
//helper
function getFlag(uint256 flags, uint256 flag) public pure returns (bool) {
return (flags >> uint8(flag)) % 2 == 1;
}
function setFlag(
uint256 flags,
uint256 flag,
bool value
) public pure returns (uint256) {
if (getFlag(flags, flag) != value) {
if (value) {
return flags + 2**flag;
} else {
return flags - 2**flag;
}
} else {
return flags;
}
}
/**
* @notice Checks if a given address is reserved.
*/
function isNotReservedAddress(address addr) public pure returns (bool) {
return addr != GUILD && addr != TOTAL && addr != ESCROW;
}
/**
* @notice Checks if a given address is zeroed.
*/
function isNotZeroAddress(address addr) public pure returns (bool) {
return addr != address(0x0);
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "./DaoConstants.sol";
import "../guards/AdapterGuard.sol";
import "../guards/MemberGuard.sol";
import "../extensions/IExtension.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
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.
*/
contract DaoRegistry is MemberGuard, AdapterGuard {
bool public initialized = false; // internally tracks deployment under eip-1167 proxy pattern
enum DaoState {CREATION, READY}
/*
* EVENTS
*/
/// @dev - Events for Proposals
event SubmittedProposal(bytes32 proposalId, uint256 flags);
event SponsoredProposal(
bytes32 proposalId,
uint256 flags,
address votingAdapter
);
event ProcessedProposal(bytes32 proposalId, uint256 flags);
event AdapterAdded(
bytes32 adapterId,
address adapterAddress,
uint256 flags
);
event AdapterRemoved(bytes32 adapterId);
event ExtensionAdded(bytes32 extensionId, address extensionAddress);
event ExtensionRemoved(bytes32 extensionId);
/// @dev - Events for Members
event UpdateDelegateKey(address memberAddress, address newDelegateKey);
event ConfigurationUpdated(bytes32 key, uint256 value);
event AddressConfigurationUpdated(bytes32 key, address value);
enum MemberFlag {EXISTS}
enum ProposalFlag {EXISTS, SPONSORED, PROCESSED}
enum AclFlag {
REPLACE_ADAPTER,
SUBMIT_PROPOSAL,
UPDATE_DELEGATE_KEY,
SET_CONFIGURATION,
ADD_EXTENSION,
REMOVE_EXTENSION,
NEW_MEMBER
}
/*
* STRUCTURES
*/
struct Proposal {
// the structure to track all the proposals in the DAO
address adapterAddress; // the adapter address that called the functions to change the DAO state
uint256 flags; // flags to track the state of the proposal: exist, sponsored, processed, canceled, etc.
}
struct Member {
// the structure to track all the members in the DAO
uint256 flags; // flags to track the state of the member: exists, etc
}
struct Checkpoint {
// A checkpoint for marking number of votes from a given block
uint96 fromBlock;
uint160 amount;
}
struct DelegateCheckpoint {
// A checkpoint for marking number of votes from a given block
uint96 fromBlock;
address delegateKey;
}
struct AdapterEntry {
bytes32 id;
uint256 acl;
}
struct ExtensionEntry {
bytes32 id;
mapping(address => uint256) acl;
}
/*
* PUBLIC VARIABLES
*/
mapping(address => Member) public members; // the map to track all members of the DAO
address[] private _members;
// delegate key => member address mapping
mapping(address => address) public memberAddressesByDelegatedKey;
// memberAddress => checkpointNum => DelegateCheckpoint
mapping(address => mapping(uint32 => DelegateCheckpoint)) checkpoints;
// memberAddress => numDelegateCheckpoints
mapping(address => uint32) numCheckpoints;
DaoState public state;
/// @notice The map that keeps track of all proposasls submitted to the DAO
mapping(bytes32 => Proposal) public proposals;
/// @notice The map that tracks the voting adapter address per proposalId
mapping(bytes32 => address) public votingAdapter;
/// @notice The map that keeps track of all adapters registered in the DAO
mapping(bytes32 => address) public adapters;
/// @notice The inverse map to get the adapter id based on its address
mapping(address => AdapterEntry) public inverseAdapters;
/// @notice The map that keeps track of all extensions registered in the DAO
mapping(bytes32 => address) public extensions;
/// @notice The inverse map to get the extension id based on its address
mapping(address => ExtensionEntry) public inverseExtensions;
/// @notice The map that keeps track of configuration parameters for the DAO and adapters
mapping(bytes32 => uint256) public mainConfiguration;
mapping(bytes32 => address) public addressConfiguration;
uint256 public lockedAt;
/// @notice Clonable contract must have an empty constructor
// constructor() {
// }
/**
* @notice Initialises the DAO
* @dev Involves initialising available tokens, checkpoints, and membership of creator
* @dev Can only be called once
* @param creator The DAO's creator, who will be an initial member
* @param payer The account which paid for the transaction to create the DAO, who will be an initial member
*/
function initialize(address creator, address payer) external {
require(!initialized, "dao already initialized");
potentialNewMember(msg.sender);
potentialNewMember(payer);
potentialNewMember(creator);
initialized = true;
}
/**
* @notice default fallback function to prevent from sending ether to the contract
*/
receive() external payable {
revert("you cannot send money back directly");
}
/**
* @dev Sets the state of the dao to READY
*/
function finalizeDao() external {
state = DaoState.READY;
}
function lockSession() external {
if (isAdapter(msg.sender) || isExtension(msg.sender)) {
lockedAt = block.number;
}
}
function unlockSession() external {
if (isAdapter(msg.sender) || isExtension(msg.sender)) {
lockedAt = 0;
}
}
/**
* @notice Sets a configuration value
* @dev Changes the value of a key in the configuration mapping
* @param key The configuration key for which the value will be set
* @param value The value to set the key
*/
function setConfiguration(bytes32 key, uint256 value)
external
hasAccess(this, AclFlag.SET_CONFIGURATION)
{
mainConfiguration[key] = value;
emit ConfigurationUpdated(key, value);
}
function potentialNewMember(address memberAddress)
public
hasAccess(this, AclFlag.NEW_MEMBER)
{
require(memberAddress != address(0x0), "invalid member address");
Member storage member = members[memberAddress];
if (!getFlag(member.flags, uint8(MemberFlag.EXISTS))) {
require(
memberAddressesByDelegatedKey[memberAddress] == address(0x0),
"member address already taken as delegated key"
);
member.flags = setFlag(
member.flags,
uint8(MemberFlag.EXISTS),
true
);
memberAddressesByDelegatedKey[memberAddress] = memberAddress;
_members.push(memberAddress);
}
address bankAddress = extensions[BANK];
if (bankAddress != address(0x0)) {
BankExtension bank = BankExtension(bankAddress);
if (bank.balanceOf(memberAddress, MEMBER_COUNT) == 0) {
bank.addToBalance(memberAddress, MEMBER_COUNT, 1);
}
}
}
/**
* @notice Sets an configuration value
* @dev Changes the value of a key in the configuration mapping
* @param key The configuration key for which the value will be set
* @param value The value to set the key
*/
function setAddressConfiguration(bytes32 key, address value)
external
hasAccess(this, AclFlag.SET_CONFIGURATION)
{
addressConfiguration[key] = value;
emit AddressConfigurationUpdated(key, value);
}
/**
* @return The configuration value of a particular key
* @param key The key to look up in the configuration mapping
*/
function getConfiguration(bytes32 key) external view returns (uint256) {
return mainConfiguration[key];
}
/**
* @return The configuration value of a particular key
* @param key The key to look up in the configuration mapping
*/
function getAddressConfiguration(bytes32 key)
external
view
returns (address)
{
return addressConfiguration[key];
}
/**
* @notice Adds a new extension to the registry
* @param extensionId The unique identifier of the new extension
* @param extension The address of the extension
* @param creator The DAO's creator, who will be an initial member
*/
function addExtension(
bytes32 extensionId,
IExtension extension,
address creator
) external hasAccess(this, AclFlag.ADD_EXTENSION) {
require(extensionId != bytes32(0), "extension id must not be empty");
require(
extensions[extensionId] == address(0x0),
"extension Id already in use"
);
extensions[extensionId] = address(extension);
inverseExtensions[address(extension)].id = extensionId;
extension.initialize(this, creator);
emit ExtensionAdded(extensionId, address(extension));
}
function setAclToExtensionForAdapter(
address extensionAddress,
address adapterAddress,
uint256 acl
) external hasAccess(this, AclFlag.ADD_EXTENSION) {
require(isAdapter(adapterAddress), "not an adapter");
require(isExtension(extensionAddress), "not an extension");
inverseExtensions[extensionAddress].acl[adapterAddress] = acl;
}
/**
* @notice Replaces an adapter in the registry in a single step.
* @notice It handles addition and removal of adapters as special cases.
* @dev It removes the current adapter if the adapterId maps to an existing adapter address.
* @dev It adds an adapter if the adapterAddress parameter is not zeroed.
* @param adapterId The unique identifier of the adapter
* @param adapterAddress The address of the new adapter or zero if it is a removal operation
* @param acl The flags indicating the access control layer or permissions of the new adapter
* @param keys The keys indicating the adapter configuration names.
* @param values The values indicating the adapter configuration values.
*/
function replaceAdapter(
bytes32 adapterId,
address adapterAddress,
uint128 acl,
bytes32[] calldata keys,
uint256[] calldata values
) external hasAccess(this, AclFlag.REPLACE_ADAPTER) {
require(adapterId != bytes32(0), "adapterId must not be empty");
address currentAdapterAddr = adapters[adapterId];
if (currentAdapterAddr != address(0x0)) {
delete inverseAdapters[currentAdapterAddr];
delete adapters[adapterId];
emit AdapterRemoved(adapterId);
}
for (uint256 i = 0; i < keys.length; i++) {
bytes32 key = keys[i];
uint256 value = values[i];
mainConfiguration[key] = value;
emit ConfigurationUpdated(key, value);
}
if (adapterAddress != address(0x0)) {
require(
inverseAdapters[adapterAddress].id == bytes32(0),
"adapterAddress already in use"
);
adapters[adapterId] = adapterAddress;
inverseAdapters[adapterAddress].id = adapterId;
inverseAdapters[adapterAddress].acl = acl;
emit AdapterAdded(adapterId, adapterAddress, acl);
}
}
/**
* @notice Removes an adapter from the registry
* @param extensionId The unique identifier of the extension
*/
function removeExtension(bytes32 extensionId)
external
hasAccess(this, AclFlag.REMOVE_EXTENSION)
{
require(extensionId != bytes32(0), "extensionId must not be empty");
require(
extensions[extensionId] != address(0x0),
"extensionId not registered"
);
delete inverseExtensions[extensions[extensionId]];
delete extensions[extensionId];
emit ExtensionRemoved(extensionId);
}
/**
* @notice Looks up if there is an extension of a given address
* @return Whether or not the address is an extension
* @param extensionAddr The address to look up
*/
function isExtension(address extensionAddr) public view returns (bool) {
return inverseExtensions[extensionAddr].id != bytes32(0);
}
/**
* @notice Looks up if there is an adapter of a given address
* @return Whether or not the address is an adapter
* @param adapterAddress The address to look up
*/
function isAdapter(address adapterAddress) public view returns (bool) {
return inverseAdapters[adapterAddress].id != bytes32(0);
}
/**
* @notice Checks if an adapter has a given ACL flag
* @return Whether or not the given adapter has the given flag set
* @param adapterAddress The address to look up
* @param flag The ACL flag to check against the given address
*/
function hasAdapterAccess(address adapterAddress, AclFlag flag)
public
view
returns (bool)
{
return getFlag(inverseAdapters[adapterAddress].acl, uint8(flag));
}
/**
* @notice Checks if an adapter has a given ACL flag
* @return Whether or not the given adapter has the given flag set
* @param adapterAddress The address to look up
* @param flag The ACL flag to check against the given address
*/
function hasAdapterAccessToExtension(
address adapterAddress,
address extensionAddress,
uint8 flag
) public view returns (bool) {
return
isAdapter(adapterAddress) &&
getFlag(
inverseExtensions[extensionAddress].acl[adapterAddress],
uint8(flag)
);
}
/**
* @return The address of a given adapter ID
* @param adapterId The ID to look up
*/
function getAdapterAddress(bytes32 adapterId)
external
view
returns (address)
{
require(adapters[adapterId] != address(0), "adapter not found");
return adapters[adapterId];
}
/**
* @return The address of a given extension Id
* @param extensionId The ID to look up
*/
function getExtensionAddress(bytes32 extensionId)
external
view
returns (address)
{
require(extensions[extensionId] != address(0), "extension not found");
return extensions[extensionId];
}
/**
* PROPOSALS
*/
/**
* @notice Submit proposals to the DAO registry
*/
function submitProposal(bytes32 proposalId)
public
hasAccess(this, AclFlag.SUBMIT_PROPOSAL)
{
require(proposalId != bytes32(0), "invalid proposalId");
require(
!getProposalFlag(proposalId, ProposalFlag.EXISTS),
"proposalId must be unique"
);
proposals[proposalId] = Proposal(msg.sender, 1); // 1 means that only the first flag is being set i.e. EXISTS
emit SubmittedProposal(proposalId, 1);
}
/**
* @notice Sponsor proposals that were submitted to the DAO registry
* @dev adds SPONSORED to the proposal flag
* @param proposalId The ID of the proposal to sponsor
* @param sponsoringMember The member who is sponsoring the proposal
*/
function sponsorProposal(
bytes32 proposalId,
address sponsoringMember,
address votingAdapterAddr
) external onlyMember2(this, sponsoringMember) {
// also checks if the flag was already set
Proposal storage proposal =
_setProposalFlag(proposalId, ProposalFlag.SPONSORED);
uint256 flags = proposal.flags;
require(
proposal.adapterAddress == msg.sender,
"only the adapter that submitted the proposal can process it"
);
require(
!getFlag(flags, uint8(ProposalFlag.PROCESSED)),
"proposal already processed"
);
votingAdapter[proposalId] = votingAdapterAddr;
emit SponsoredProposal(proposalId, flags, votingAdapterAddr);
}
/**
* @notice Mark a proposal as processed in the DAO registry
* @param proposalId The ID of the proposal that is being processed
*/
function processProposal(bytes32 proposalId) external {
Proposal storage proposal =
_setProposalFlag(proposalId, ProposalFlag.PROCESSED);
require(proposal.adapterAddress == msg.sender, "err::adapter mismatch");
uint256 flags = proposal.flags;
emit ProcessedProposal(proposalId, flags);
}
/**
* @notice Sets a flag of a proposal
* @dev Reverts if the proposal is already processed
* @param proposalId The ID of the proposal to be changed
* @param flag The flag that will be set on the proposal
*/
function _setProposalFlag(bytes32 proposalId, ProposalFlag flag)
internal
returns (Proposal storage)
{
Proposal storage proposal = proposals[proposalId];
uint256 flags = proposal.flags;
require(
getFlag(flags, uint8(ProposalFlag.EXISTS)),
"proposal does not exist for this dao"
);
require(
proposal.adapterAddress == msg.sender,
"only the adapter that submitted the proposal can set its flag"
);
require(!getFlag(flags, uint8(flag)), "flag already set");
flags = setFlag(flags, uint8(flag), true);
proposals[proposalId].flags = flags;
return proposals[proposalId];
}
/*
* MEMBERS
*/
/**
* @return Whether or not a given address is a member of the DAO.
* @dev it will resolve by delegate key, not member address.
* @param addr The address to look up
*/
function isMember(address addr) public view returns (bool) {
address memberAddress = memberAddressesByDelegatedKey[addr];
return getMemberFlag(memberAddress, MemberFlag.EXISTS);
}
/**
* @return Whether or not a flag is set for a given proposal
* @param proposalId The proposal to check against flag
* @param flag The flag to check in the proposal
*/
function getProposalFlag(bytes32 proposalId, ProposalFlag flag)
public
view
returns (bool)
{
return getFlag(proposals[proposalId].flags, uint8(flag));
}
/**
* @return Whether or not a flag is set for a given member
* @param memberAddress The member to check against flag
* @param flag The flag to check in the member
*/
function getMemberFlag(address memberAddress, MemberFlag flag)
public
view
returns (bool)
{
return getFlag(members[memberAddress].flags, uint8(flag));
}
function getNbMembers() public view returns (uint256) {
return _members.length;
}
function getMemberAddress(uint256 index) public view returns (address) {
return _members[index];
}
/**
* @notice Updates the delegate key of a member
* @param memberAddr The member doing the delegation
* @param newDelegateKey The member who is being delegated to
*/
function updateDelegateKey(address memberAddr, address newDelegateKey)
external
hasAccess(this, AclFlag.UPDATE_DELEGATE_KEY)
{
require(newDelegateKey != address(0x0), "newDelegateKey cannot be 0");
// skip checks if member is setting the delegate key to their member address
if (newDelegateKey != memberAddr) {
require(
// newDelegate must not be delegated to
memberAddressesByDelegatedKey[newDelegateKey] == address(0x0),
"cannot overwrite existing delegated keys"
);
} else {
require(
memberAddressesByDelegatedKey[memberAddr] == address(0x0),
"address already taken as delegated key"
);
}
Member storage member = members[memberAddr];
require(
getFlag(member.flags, uint8(MemberFlag.EXISTS)),
"member does not exist"
);
// Reset the delegation of the previous delegate
memberAddressesByDelegatedKey[
getCurrentDelegateKey(memberAddr)
] = address(0x0);
memberAddressesByDelegatedKey[newDelegateKey] = memberAddr;
_createNewDelegateCheckpoint(memberAddr, newDelegateKey);
emit UpdateDelegateKey(memberAddr, newDelegateKey);
}
/**
* Public read-only functions
*/
/**
* @param checkAddr The address to check for a delegate
* @return the delegated address or the checked address if it is not a delegate
*/
function getAddressIfDelegated(address checkAddr)
public
view
returns (address)
{
address delegatedKey = memberAddressesByDelegatedKey[checkAddr];
return delegatedKey == address(0x0) ? checkAddr : delegatedKey;
}
/**
* @param memberAddr The member whose delegate will be returned
* @return the delegate key at the current time for a member
*/
function getCurrentDelegateKey(address memberAddr)
public
view
returns (address)
{
uint32 nCheckpoints = numCheckpoints[memberAddr];
return
nCheckpoints > 0
? checkpoints[memberAddr][nCheckpoints - 1].delegateKey
: memberAddr;
}
/**
* @param memberAddr The member address to look up
* @return The delegate key address for memberAddr at the second last checkpoint number
*/
function getPreviousDelegateKey(address memberAddr)
public
view
returns (address)
{
uint32 nCheckpoints = numCheckpoints[memberAddr];
return
nCheckpoints > 1
? checkpoints[memberAddr][nCheckpoints - 2].delegateKey
: memberAddr;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param memberAddr The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorDelegateKey(address memberAddr, uint256 blockNumber)
external
view
returns (address)
{
require(
blockNumber < block.number,
"Uni::getPriorDelegateKey: not yet determined"
);
uint32 nCheckpoints = numCheckpoints[memberAddr];
if (nCheckpoints == 0) {
return memberAddr;
}
// First check most recent balance
if (
checkpoints[memberAddr][nCheckpoints - 1].fromBlock <= blockNumber
) {
return checkpoints[memberAddr][nCheckpoints - 1].delegateKey;
}
// Next check implicit zero balance
if (checkpoints[memberAddr][0].fromBlock > blockNumber) {
return memberAddr;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
DelegateCheckpoint memory cp = checkpoints[memberAddr][center];
if (cp.fromBlock == blockNumber) {
return cp.delegateKey;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[memberAddr][lower].delegateKey;
}
/**
* @notice Creates a new delegate checkpoint of a certain member
* @param member The member whose delegate checkpoints will be added to
* @param newDelegateKey The delegate key that will be written into the new checkpoint
*/
function _createNewDelegateCheckpoint(
address member,
address newDelegateKey
) internal {
uint32 nCheckpoints = numCheckpoints[member];
if (
nCheckpoints > 0 &&
checkpoints[member][nCheckpoints - 1].fromBlock == block.number
) {
checkpoints[member][nCheckpoints - 1].delegateKey = newDelegateKey;
} else {
checkpoints[member][nCheckpoints] = DelegateCheckpoint(
uint96(block.number),
newDelegateKey
);
numCheckpoints[member] = nCheckpoints + 1;
}
}
}
pragma solidity ^0.8.0;
import "../core/DaoRegistry.sol";
// SPDX-License-Identifier: MIT
/**
MIT License
Copyright (c) 2020 Openlaw
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 IExtension {
function initialize(DaoRegistry dao, address creator) external;
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "../../core/DaoConstants.sol";
import "../../core/DaoRegistry.sol";
import "../IExtension.sol";
import "../../guards/AdapterGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
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.
*/
contract BankExtension is DaoConstants, AdapterGuard, IExtension {
using Address for address payable;
using SafeERC20 for IERC20;
uint8 public maxExternalTokens; // the maximum number of external tokens that can be stored in the bank
bool public initialized = false; // internally tracks deployment under eip-1167 proxy pattern
DaoRegistry public dao;
enum AclFlag {
ADD_TO_BALANCE,
SUB_FROM_BALANCE,
INTERNAL_TRANSFER,
WITHDRAW,
EXECUTE,
REGISTER_NEW_TOKEN,
REGISTER_NEW_INTERNAL_TOKEN,
UPDATE_TOKEN
}
modifier noProposal {
require(dao.lockedAt() < block.number, "proposal lock");
_;
}
/// @dev - Events for Bank
event NewBalance(address member, address tokenAddr, uint160 amount);
event Withdraw(address account, address tokenAddr, uint160 amount);
/*
* STRUCTURES
*/
struct Checkpoint {
// A checkpoint for marking number of votes from a given block
uint96 fromBlock;
uint160 amount;
}
address[] public tokens;
address[] public internalTokens;
// tokenAddress => availability
mapping(address => bool) public availableTokens;
mapping(address => bool) public availableInternalTokens;
// tokenAddress => memberAddress => checkpointNum => Checkpoint
mapping(address => mapping(address => mapping(uint32 => Checkpoint)))
public checkpoints;
// tokenAddress => memberAddress => numCheckpoints
mapping(address => mapping(address => uint32)) public numCheckpoints;
/// @notice Clonable contract must have an empty constructor
// constructor() {
// }
modifier hasExtensionAccess(AclFlag flag) {
require(
address(this) == msg.sender ||
address(dao) == msg.sender ||
dao.state() == DaoRegistry.DaoState.CREATION ||
dao.hasAdapterAccessToExtension(
msg.sender,
address(this),
uint8(flag)
),
"bank::accessDenied"
);
_;
}
/**
* @notice Initialises the DAO
* @dev Involves initialising available tokens, checkpoints, and membership of creator
* @dev Can only be called once
* @param creator The DAO's creator, who will be an initial member
*/
function initialize(DaoRegistry _dao, address creator) external override {
require(!initialized, "bank already initialized");
require(_dao.isMember(creator), "bank::not member");
dao = _dao;
initialized = true;
availableInternalTokens[UNITS] = true;
internalTokens.push(UNITS);
availableInternalTokens[MEMBER_COUNT] = true;
internalTokens.push(MEMBER_COUNT);
uint256 nbMembers = _dao.getNbMembers();
for (uint256 i = 0; i < nbMembers; i++) {
addToBalance(_dao.getMemberAddress(i), MEMBER_COUNT, 1);
}
_createNewAmountCheckpoint(creator, UNITS, 1);
_createNewAmountCheckpoint(TOTAL, UNITS, 1);
}
function withdraw(
address payable member,
address tokenAddr,
uint256 amount
) external hasExtensionAccess(AclFlag.WITHDRAW) {
require(
balanceOf(member, tokenAddr) >= amount,
"bank::withdraw::not enough funds"
);
subtractFromBalance(member, tokenAddr, amount);
if (tokenAddr == ETH_TOKEN) {
member.sendValue(amount);
} else {
IERC20 erc20 = IERC20(tokenAddr);
erc20.safeTransfer(member, amount);
}
emit Withdraw(member, tokenAddr, uint160(amount));
}
/**
* @return Whether or not the given token is an available internal token in the bank
* @param token The address of the token to look up
*/
function isInternalToken(address token) external view returns (bool) {
return availableInternalTokens[token];
}
/**
* @return Whether or not the given token is an available token in the bank
* @param token The address of the token to look up
*/
function isTokenAllowed(address token) public view returns (bool) {
return availableTokens[token];
}
/**
* @notice Sets the maximum amount of external tokens allowed in the bank
* @param maxTokens The maximum amount of token allowed
*/
function setMaxExternalTokens(uint8 maxTokens) external {
require(!initialized, "bank already initialized");
require(
maxTokens > 0 && maxTokens <= MAX_TOKENS_GUILD_BANK,
"max number of external tokens should be (0,200)"
);
maxExternalTokens = maxTokens;
}
/*
* BANK
*/
/**
* @notice Registers a potential new token in the bank
* @dev Can not be a reserved token or an available internal token
* @param token The address of the token
*/
function registerPotentialNewToken(address token)
external
hasExtensionAccess(AclFlag.REGISTER_NEW_TOKEN)
{
require(isNotReservedAddress(token), "reservedToken");
require(!availableInternalTokens[token], "internalToken");
require(
tokens.length <= maxExternalTokens,
"exceeds the maximum tokens allowed"
);
if (!availableTokens[token]) {
availableTokens[token] = true;
tokens.push(token);
}
}
/**
* @notice Registers a potential new internal token in the bank
* @dev Can not be a reserved token or an available token
* @param token The address of the token
*/
function registerPotentialNewInternalToken(address token)
external
hasExtensionAccess(AclFlag.REGISTER_NEW_INTERNAL_TOKEN)
{
require(isNotReservedAddress(token), "reservedToken");
require(!availableTokens[token], "availableToken");
if (!availableInternalTokens[token]) {
availableInternalTokens[token] = true;
internalTokens.push(token);
}
}
function updateToken(address tokenAddr)
external
hasExtensionAccess(AclFlag.UPDATE_TOKEN)
{
require(isTokenAllowed(tokenAddr), "token not allowed");
uint256 totalBalance = balanceOf(TOTAL, tokenAddr);
uint256 realBalance;
if (tokenAddr == ETH_TOKEN) {
realBalance = address(this).balance;
} else {
IERC20 erc20 = IERC20(tokenAddr);
realBalance = erc20.balanceOf(address(this));
}
if (totalBalance < realBalance) {
addToBalance(GUILD, tokenAddr, realBalance - totalBalance);
} else if (totalBalance > realBalance) {
uint256 tokensToRemove = totalBalance - realBalance;
uint256 guildBalance = balanceOf(GUILD, tokenAddr);
if (guildBalance > tokensToRemove) {
subtractFromBalance(GUILD, tokenAddr, tokensToRemove);
} else {
subtractFromBalance(GUILD, tokenAddr, guildBalance);
}
}
}
/**
* Public read-only functions
*/
/**
* Internal bookkeeping
*/
/**
* @return The token from the bank of a given index
* @param index The index to look up in the bank's tokens
*/
function getToken(uint256 index) external view returns (address) {
return tokens[index];
}
/**
* @return The amount of token addresses in the bank
*/
function nbTokens() external view returns (uint256) {
return tokens.length;
}
/**
* @return All the tokens registered in the bank.
*/
function getTokens() external view returns (address[] memory) {
return tokens;
}
/**
* @return The internal token at a given index
* @param index The index to look up in the bank's array of internal tokens
*/
function getInternalToken(uint256 index) external view returns (address) {
return internalTokens[index];
}
/**
* @return The amount of internal token addresses in the bank
*/
function nbInternalTokens() external view returns (uint256) {
return internalTokens.length;
}
/**
* @notice Adds to a member's balance of a given token
* @param member The member whose balance will be updated
* @param token The token to update
* @param amount The new balance
*/
function addToBalance(
address member,
address token,
uint256 amount
) public payable hasExtensionAccess(AclFlag.ADD_TO_BALANCE) {
require(
availableTokens[token] || availableInternalTokens[token],
"unknown token address"
);
uint256 newAmount = balanceOf(member, token) + amount;
uint256 newTotalAmount = balanceOf(TOTAL, token) + amount;
_createNewAmountCheckpoint(member, token, newAmount);
_createNewAmountCheckpoint(TOTAL, token, newTotalAmount);
}
/**
* @notice Remove from a member's balance of a given token
* @param member The member whose balance will be updated
* @param token The token to update
* @param amount The new balance
*/
function subtractFromBalance(
address member,
address token,
uint256 amount
) public hasExtensionAccess(AclFlag.SUB_FROM_BALANCE) {
uint256 newAmount = balanceOf(member, token) - amount;
uint256 newTotalAmount = balanceOf(TOTAL, token) - amount;
_createNewAmountCheckpoint(member, token, newAmount);
_createNewAmountCheckpoint(TOTAL, token, newTotalAmount);
}
/**
* @notice Make an internal token transfer
* @param from The member who is sending tokens
* @param to The member who is receiving tokens
* @param amount The new amount to transfer
*/
function internalTransfer(
address from,
address to,
address token,
uint256 amount
) public hasExtensionAccess(AclFlag.INTERNAL_TRANSFER) {
uint256 newAmount = balanceOf(from, token) - amount;
uint256 newAmount2 = balanceOf(to, token) + amount;
_createNewAmountCheckpoint(from, token, newAmount);
_createNewAmountCheckpoint(to, token, newAmount2);
}
/**
* @notice Returns an member's balance of a given token
* @param member The address to look up
* @param tokenAddr The token where the member's balance of which will be returned
* @return The amount in account's tokenAddr balance
*/
function balanceOf(address member, address tokenAddr)
public
view
returns (uint160)
{
uint32 nCheckpoints = numCheckpoints[tokenAddr][member];
return
nCheckpoints > 0
? checkpoints[tokenAddr][member][nCheckpoints - 1].amount
: 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorAmount(
address account,
address tokenAddr,
uint256 blockNumber
) external view returns (uint256) {
require(
blockNumber < block.number,
"Uni::getPriorAmount: not yet determined"
);
uint32 nCheckpoints = numCheckpoints[tokenAddr][account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (
checkpoints[tokenAddr][account][nCheckpoints - 1].fromBlock <=
blockNumber
) {
return checkpoints[tokenAddr][account][nCheckpoints - 1].amount;
}
// Next check implicit zero balance
if (checkpoints[tokenAddr][account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[tokenAddr][account][center];
if (cp.fromBlock == blockNumber) {
return cp.amount;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[tokenAddr][account][lower].amount;
}
/**
* @notice Creates a new amount checkpoint for a token of a certain member
* @dev Reverts if the amount is greater than 2**64-1
* @param member The member whose checkpoints will be added to
* @param token The token of which the balance will be changed
* @param amount The amount to be written into the new checkpoint
*/
function _createNewAmountCheckpoint(
address member,
address token,
uint256 amount
) internal {
bool isValidToken = false;
if (availableInternalTokens[token]) {
require(
amount < type(uint88).max,
"token amount exceeds the maximum limit for internal tokens"
);
isValidToken = true;
} else if (availableTokens[token]) {
require(
amount < type(uint160).max,
"token amount exceeds the maximum limit for external tokens"
);
isValidToken = true;
}
uint160 newAmount = uint160(amount);
require(isValidToken, "token not registered");
uint32 nCheckpoints = numCheckpoints[token][member];
if (
nCheckpoints > 0 &&
checkpoints[token][member][nCheckpoints - 1].fromBlock ==
block.number
) {
checkpoints[token][member][nCheckpoints - 1].amount = newAmount;
} else {
checkpoints[token][member][nCheckpoints] = Checkpoint(
uint96(block.number),
newAmount
);
numCheckpoints[token][member] = nCheckpoints + 1;
}
emit NewBalance(member, token, newAmount);
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "../core/DaoRegistry.sol";
import "../extensions/IExtension.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
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.
*/
abstract contract AdapterGuard {
/**
* @dev Only registered adapters are allowed to execute the function call.
*/
modifier onlyAdapter(DaoRegistry dao) {
require(
(dao.state() == DaoRegistry.DaoState.CREATION &&
creationModeCheck(dao)) || dao.isAdapter(msg.sender),
"onlyAdapter"
);
_;
}
modifier reentrancyGuard(DaoRegistry dao) {
require(dao.lockedAt() != block.number, "reentrancy guard");
dao.lockSession();
_;
dao.unlockSession();
}
modifier hasAccess(DaoRegistry dao, DaoRegistry.AclFlag flag) {
require(
(dao.state() == DaoRegistry.DaoState.CREATION &&
creationModeCheck(dao)) ||
dao.hasAdapterAccess(msg.sender, flag),
"accessDenied"
);
_;
}
function creationModeCheck(DaoRegistry dao) internal view returns (bool) {
return
dao.getNbMembers() == 0 ||
dao.isMember(msg.sender) ||
dao.isAdapter(msg.sender);
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "../core/DaoRegistry.sol";
import "../extensions/bank/Bank.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
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.
*/
abstract contract MemberGuard is DaoConstants {
/**
* @dev Only members of the DAO are allowed to execute the function call.
*/
modifier onlyMember(DaoRegistry dao) {
_onlyMember(dao, msg.sender);
_;
}
modifier onlyMember2(DaoRegistry dao, address _addr) {
_onlyMember(dao, _addr);
_;
}
function _onlyMember(DaoRegistry dao, address _addr) internal view {
require(isActiveMember(dao, _addr), "onlyMember");
}
function isActiveMember(DaoRegistry dao, address _addr)
public
view
returns (bool)
{
address bankAddress = dao.extensions(BANK);
if (bankAddress != address(0x0)) {
address memberAddr = dao.getAddressIfDelegated(_addr);
return BankExtension(bankAddress).balanceOf(memberAddr, UNITS) > 0;
}
return dao.isMember(_addr);
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
/**
MIT License
Copyright (c) 2020 Openlaw
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.
*/
library FairShareHelper {
/**
* @notice calculates the fair unit amount based the total units and current balance.
*/
function calc(
uint256 balance,
uint256 units,
uint256 totalUnits
) internal pure returns (uint256) {
require(totalUnits > 0, "totalUnits must be greater than 0");
require(
units <= totalUnits,
"units must be less than or equal to totalUnits"
);
if (balance == 0) {
return 0;
}
// The balance for Internal and External tokens are limited to 2^64-1 (see Bank.sol:L411-L421)
// The maximum number of units is limited to 2^64-1 (see ...)
// Worst case cenario is: balance=2^64-1 * units=2^64-1, no overflows.
uint256 prod = balance * units;
return prod / totalUnits;
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "../core/DaoRegistry.sol";
import "../guards/MemberGuard.sol";
import "../adapters/interfaces/IVoting.sol";
import "../helpers/FairShareHelper.sol";
import "../extensions/bank/Bank.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
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.
*/
library GuildKickHelper {
address internal constant TOTAL = address(0xbabe);
address internal constant UNITS = address(0xFF1CE);
address internal constant LOOT = address(0xB105F00D);
bytes32 internal constant BANK = keccak256("bank");
address internal constant GUILD = address(0xdead);
/**
* @notice Transfers the funds from the Guild account to the kicked member account based on the current kick proposal id.
* @notice The amount of funds is caculated using the actual balance of the member to make sure the member has not ragequited.
* @dev A kick proposal must be in progress.
* @dev Only one kick per DAO can be executed at time.
* @dev Only active members can be kicked out.
* @dev Only proposals that passed the voting process can be completed.
* @param dao The dao address.
*/
function rageKick(DaoRegistry dao, address kickedMember) internal {
// Get the bank extension
BankExtension bank = BankExtension(dao.getExtensionAddress(BANK));
uint256 nbTokens = bank.nbTokens();
// Calculates the total units, loot and locked loot before any internal transfers
// it considers the locked loot to be able to calculate the fair amount to ragequit,
// but locked loot can not be burned.
uint256 initialTotalUnitsAndLoot =
bank.balanceOf(TOTAL, UNITS) + bank.balanceOf(TOTAL, LOOT);
uint256 unitsToBurn = bank.balanceOf(kickedMember, UNITS);
uint256 lootToBurn = bank.balanceOf(kickedMember, LOOT);
uint256 unitsAndLootToBurn = unitsToBurn + lootToBurn;
// Transfers the funds from the internal Guild account to the internal member's account.
for (uint256 i = 0; i < nbTokens; i++) {
address token = bank.getToken(i);
// Calculates the fair amount of funds to ragequit based on the token, units and loot.
// It takes into account the historical guild balance when the kick proposal was created.
uint256 amountToRagequit =
FairShareHelper.calc(
bank.balanceOf(GUILD, token),
unitsAndLootToBurn,
initialTotalUnitsAndLoot
);
// Ony execute the internal transfer if the user has enough funds to receive.
if (amountToRagequit > 0) {
// gas optimization to allow a higher maximum token limit
// deliberately not using safemath here to keep overflows from preventing the function execution
// (which would break ragekicks) if a token overflows,
// it is because the supply was artificially inflated to oblivion, so we probably don"t care about it anyways
bank.internalTransfer(
GUILD,
kickedMember,
token,
amountToRagequit
);
}
}
bank.subtractFromBalance(kickedMember, UNITS, unitsToBurn);
bank.subtractFromBalance(kickedMember, LOOT, lootToBurn);
}
}
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT
import "../core/DaoRegistry.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
/**
MIT License
Copyright (c) 2020 Openlaw
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.
*/
abstract contract Signatures {
string public constant EIP712_DOMAIN =
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,address actionId)";
bytes32 public constant EIP712_DOMAIN_TYPEHASH =
keccak256(abi.encodePacked(EIP712_DOMAIN));
function hashMessage(
DaoRegistry dao,
uint256 chainId,
address actionId,
bytes32 message
) public pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator(dao, chainId, actionId),
message
)
);
}
function domainSeparator(
DaoRegistry dao,
uint256 chainId,
address actionId
) public pure returns (bytes32) {
return
keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256("Snapshot Message"), // string name
keccak256("4"), // string version
chainId, // uint256 chainId
address(dao), // address verifyingContract,
actionId
)
);
}
function recover(bytes32 hash, bytes memory sig)
public
pure
returns (address)
{
return ECDSA.recover(hash, sig);
}
}
// 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;
/**
* @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";
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;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
| check that the step is indeed part of the resultreturn 1 if yes, 2 if no and 0 if the vote is incorrectinvalid choiceinvalid proposal hashhas voted outside of the voting time | function getBadNodeError(
DaoRegistry dao,
bytes32 proposalId,
bool submitNewVote,
bytes32 resultRoot,
uint256 blockNumber,
uint256 gracePeriodStartingTime,
VoteResultNode memory node
) public view returns (BadNodeError) {
(address adapterAddress, ) = dao.proposals(proposalId);
require(resultRoot != bytes32(0), "no result available yet!");
bytes32 hashCurrent = nodeHash(dao, adapterAddress, node);
require(
MerkleProof.verify(node.proof, resultRoot, hashCurrent),
"proof:bad"
);
address account = dao.getMemberAddress(node.index);
address voter = dao.getPriorDelegateKey(account, blockNumber);
(address actionId, ) = dao.proposals(proposalId);
if (
(node.sig.length > 0 && !_isValidChoice(node.choice))
) {
return BadNodeError.INVALID_CHOICE;
}
if (node.proposalId != proposalId) {
return BadNodeError.WRONG_PROPOSAL_ID;
}
if (!submitNewVote && node.timestamp > gracePeriodStartingTime) {
return BadNodeError.AFTER_VOTING_PERIOD;
}
!_hasVoted(
dao,
actionId,
voter,
node.timestamp,
node.proposalId,
node.choice,
node.sig
)
) {
return BadNodeError.BAD_SIGNATURE;
}
return BadNodeError.OK;
}
| 13,603,407 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol";
import "./interfaces/IMembershipStaking.sol";
contract MembershipStaking is IMembershipStaking, OwnableUpgradeable {
using SafeCastUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @notice Burn address
address public constant BURN_ADDRESS =
0x000000000000000000000000000000000000dEaD;
/// @notice CPOOL token contract
IERC20Upgradeable public cpool;
/// @notice PoolFactory contract
address public factory;
/// @notice A checkpoint for marking stake size from a given block
struct Checkpoint {
uint256 fromBlock;
uint256 stake;
}
/// @notice A record of stake checkpoints for each account, by index
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping(address => uint32) public numCheckpoints;
/// @notice Mapping of addresses to their locked stake amounts
mapping(address => uint256) public locked;
/// @notice Amount of staked CPOOL required for active managers
uint256 public managerMinimalStake;
// EVENTS
/// @notice Event emitted when somebody stakes CPOOL
event Staked(address indexed account, uint256 amount);
/// @notice Event emitted when somebody unstaked CPOOls
event Unstaked(address indexed account, uint256 amount);
/// @notice Event emitted when somebody's stake is burned
event Burned(address indexed account, uint256 amount);
/// @notice Event emitted when new value for manager minimal stake is set
event ManagerMinimalStakeSet(uint256 stake);
/// @notice Event emitted when some account stake is locked
event StakeLocked(address indexed account, uint256 amount);
/// @notice Event emitted when some account stake is unlocked
event StakeUnlocked(address indexed account, uint256 amount);
// CONSTRUCTOR
/**
* @notice Upgradeable contract constructor
* @param cpool_ Address of the CPOOL contract
* @param factory_ Address of the PoolFactory contract
* @param managerMinimalStake_ Value of manager minimal stake
*/
function initialize(
IERC20Upgradeable cpool_,
address factory_,
uint256 managerMinimalStake_
) external initializer {
require(address(cpool_) != address(0), "AIZ");
require(factory_ != address(0), "AIZ");
__Ownable_init();
cpool = cpool_;
factory = factory_;
managerMinimalStake = managerMinimalStake_;
}
// PUBLIC FUNCTIONS
/**
* @notice Function is called to stake CPOOL
* @dev Approval for given amount should be made in prior
* @param amount Amount to stake
*/
function stake(uint256 amount) external {
_stake(msg.sender, amount);
}
/**
* @notice Function is called to unstake CPOOL
* @dev Only possible to unstake unlocked part of CPOOL
* @param amount Amount to unstake
*/
function unstake(uint256 amount) external {
uint256 currentStake = getCurrentStake(msg.sender);
require(locked[msg.sender] + amount <= currentStake, "NES");
_writeCheckpoint(msg.sender, currentStake - amount);
cpool.safeTransfer(msg.sender, amount);
emit Unstaked(msg.sender, amount);
}
// RESTRICTED FUNCTIONS
/**
* @notice Function is called only by owner to set manager minimal stake
* @param managerMinimalStake_ Minimal stake required to be a pool manager
*/
function setManagerMinimalStake(uint256 managerMinimalStake_)
external
onlyOwner
{
managerMinimalStake = managerMinimalStake_;
emit ManagerMinimalStakeSet(managerMinimalStake_);
}
/**
* @notice Function is called only by Factory to lock required manager's stake amount
* @param account Address whose stake should be locked
* @return Staked amount
*/
function lockStake(address account) external onlyFactory returns (uint256) {
uint256 availableStake = getAvailableStake(account);
if (managerMinimalStake > availableStake) {
_stake(account, managerMinimalStake - availableStake);
}
locked[account] += managerMinimalStake;
emit StakeLocked(account, managerMinimalStake);
return managerMinimalStake;
}
/**
* @notice Function is called only by Factory to unlock part of some stake
* @param account Address whose stake should be unlocked
* @param amount Amount to unlock
*/
function unlockStake(address account, uint256 amount) external onlyFactory {
locked[account] -= amount;
emit StakeUnlocked(account, amount);
}
/**
* @notice Function is called only by Factory to burn manager's stake in case of default
* @param account Address whose stake should be burned
* @param amount Amount to burn
*/
function burnStake(address account, uint256 amount) external onlyFactory {
locked[account] -= amount;
uint256 currentStake = getCurrentStake(account);
_writeCheckpoint(account, currentStake - amount);
cpool.safeTransfer(BURN_ADDRESS, amount);
emit Burned(account, amount);
}
// VIEW FUNCTIONS
/**
* @notice Gets available for unlocking part of the stake
* @param account The address to get available stake size
* @return The available stake size for `account`
*/
function getAvailableStake(address account) public view returns (uint256) {
return getCurrentStake(account) - locked[account];
}
/**
* @notice Gets the current stake size for `account`
* @param account The address to get stake size
* @return The current stake size for `account`
*/
function getCurrentStake(address account) public view returns (uint256) {
uint32 nCheckpoints = numCheckpoints[account];
return
nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].stake : 0;
}
/**
* @notice Determine the prior stake size for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the stake size at
* @return The stake size the account had as of the given block
*/
function getPriorVotes(address account, uint256 blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "NYD");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].stake;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.stake;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].stake;
}
// PRIVATE FUNCTIONS
/**
* @notice Internal function that writes new stake checkpoint for some account
* @param account The address to write checkpoint for
* @param newStake New stake size
*/
function _writeCheckpoint(address account, uint256 newStake) private {
uint32 nCheckpoints = numCheckpoints[account];
if (
nCheckpoints > 0 &&
checkpoints[account][nCheckpoints - 1].fromBlock == block.number
) {
checkpoints[account][nCheckpoints - 1].stake = newStake;
} else {
checkpoints[account][nCheckpoints] = Checkpoint(
block.number,
newStake
);
numCheckpoints[account] = nCheckpoints + 1;
}
}
/**
* @notice Internal function to stake CPOOL for some account
* @param account The address to stake for
* @param amount Amount to stake
*/
function _stake(address account, uint256 amount) private {
cpool.safeTransferFrom(account, address(this), amount);
_writeCheckpoint(account, getCurrentStake(account) + amount);
emit Staked(account, amount);
}
// MODIFIERS
/**
* @notice Modifier for the functions restricted to factory
*/
modifier onlyFactory() {
require(msg.sender == factory, "OF");
_;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.0 (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.0 (utils/math/SafeCast.sol)
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCastUpgradeable {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
interface IMembershipStaking {
function managerMinimalStake() external view returns (uint256);
function getPriorVotes(address account, uint256 blockNumber)
external
view
returns (uint256);
function lockStake(address account) external returns (uint256);
function unlockStake(address account, uint256 amount) external;
function burnStake(address account, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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 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
// OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
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
// OpenZeppelin Contracts v4.4.0 (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);
}
}
}
} | Internal function that writes new stake checkpoint for some account account The address to write checkpoint for newStake New stake size/ | function _writeCheckpoint(address account, uint256 newStake) private {
uint32 nCheckpoints = numCheckpoints[account];
if (
nCheckpoints > 0 &&
checkpoints[account][nCheckpoints - 1].fromBlock == block.number
) {
checkpoints[account][nCheckpoints - 1].stake = newStake;
checkpoints[account][nCheckpoints] = Checkpoint(
block.number,
newStake
);
numCheckpoints[account] = nCheckpoints + 1;
}
}
| 11,756,423 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.12;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
function transferWithPermit(address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Interface of the ERC2612 standard as defined in the EIP.
*
* Adds the {permit} method, which can be used to change one's
* {IERC20-allowance} without having to send a transaction, by signing a
* message. This allows users to spend tokens without having to hold Ether.
*
* See https://eips.ethereum.org/EIPS/eip-2612.
*/
interface IERC2612 {
/**
* @dev Returns the current ERC2612 nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
}
/// @dev Wrapped ERC-20 v10 (AnyswapV3ERC20) is an ERC-20 ERC-20 wrapper. You can `deposit` ERC-20 and obtain an AnyswapV3ERC20 balance which can then be operated as an ERC-20 token. You can
/// `withdraw` ERC-20 from AnyswapV3ERC20, which will then burn AnyswapV3ERC20 token in your wallet. The amount of AnyswapV3ERC20 token in any wallet is always identical to the
/// balance of ERC-20 deposited minus the ERC-20 withdrawn with that specific wallet.
interface IAnyswapV3ERC20 is IERC20, IERC2612 {
/// @dev Sets `value` as allowance of `spender` account over caller account's AnyswapV3ERC20 token,
/// after which a call is executed to an ERC677-compliant contract with the `data` parameter.
/// Emits {Approval} event.
/// Returns boolean value indicating whether operation succeeded.
/// For more information on approveAndCall format, see https://github.com/ethereum/EIPs/issues/677.
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
/// @dev Moves `value` AnyswapV3ERC20 token from caller's account to account (`to`),
/// after which a call is executed to an ERC677-compliant contract with the `data` parameter.
/// A transfer to `address(0)` triggers an ERC-20 withdraw matching the sent AnyswapV3ERC20 token in favor of caller.
/// Emits {Transfer} event.
/// Returns boolean value indicating whether operation succeeded.
/// Requirements:
/// - caller account must have at least `value` AnyswapV3ERC20 token.
/// For more information on transferAndCall format, see https://github.com/ethereum/EIPs/issues/677.
function transferAndCall(address to, uint value, bytes calldata data) external returns (bool);
}
interface ITransferReceiver {
function onTokenTransfer(address, uint, bytes calldata) external returns (bool);
}
interface IApprovalReceiver {
function onTokenApproval(address, uint, bytes calldata) external returns (bool);
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint 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");
}
}
}
contract Scorefam is IAnyswapV3ERC20 {
using SafeERC20 for IERC20;
string public name;
string public symbol;
uint8 public immutable override decimals;
address public immutable underlying;
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant TRANSFER_TYPEHASH = keccak256("Transfer(address owner,address to,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public immutable DOMAIN_SEPARATOR;
/// @dev Records amount of AnyswapV3ERC20 token owned by account.
mapping (address => uint256) public override balanceOf;
uint256 private _totalSupply;
// init flag for setting immediate vault, needed for CREATE2 support
bool private _init;
// flag to enable/disable swapout vs vault.burn so multiple events are triggered
bool private _vaultOnly;
// configurable delay for timelock functions
uint public delay = 2*24*3600;
// set of minters, can be this bridge or other bridges
mapping(address => bool) public isMinter;
address[] public minters;
// primary controller of the token contract
address public vault;
address public pendingMinter;
uint public delayMinter;
address public pendingVault;
uint public delayVault;
uint public pendingDelay;
uint public delayDelay;
modifier onlyAuth() {
require(isMinter[msg.sender], "AnyswapV4ERC20: FORBIDDEN");
_;
}
modifier onlyVault() {
require(msg.sender == mpc(), "AnyswapV3ERC20: FORBIDDEN");
_;
}
function owner() public view returns (address) {
return mpc();
}
function mpc() public view returns (address) {
if (block.timestamp >= delayVault) {
return pendingVault;
}
return vault;
}
function setVaultOnly(bool enabled) external onlyVault {
_vaultOnly = enabled;
}
function initVault(address _vault) external onlyVault {
require(_init);
vault = _vault;
pendingVault = _vault;
isMinter[_vault] = true;
minters.push(_vault);
delayVault = block.timestamp;
_init = false;
}
function setMinter(address _auth) external onlyVault {
pendingMinter = _auth;
delayMinter = block.timestamp + delay;
}
function setVault(address _vault) external onlyVault {
pendingVault = _vault;
delayVault = block.timestamp + delay;
}
function applyVault() external onlyVault {
require(block.timestamp >= delayVault);
vault = pendingVault;
}
function applyMinter() external onlyVault {
require(block.timestamp >= delayMinter);
isMinter[pendingMinter] = true;
minters.push(pendingMinter);
}
// No time delay revoke minter emergency function
function revokeMinter(address _auth) external onlyVault {
isMinter[_auth] = false;
}
function getAllMinters() external view returns (address[] memory) {
return minters;
}
function changeVault(address newVault) external onlyVault returns (bool) {
require(newVault != address(0), "AnyswapV3ERC20: address(0x0)");
pendingVault = newVault;
delayVault = block.timestamp + delay;
emit LogChangeVault(vault, pendingVault, delayVault);
return true;
}
function changeMPCOwner(address newVault) public onlyVault returns (bool) {
require(newVault != address(0), "AnyswapV3ERC20: address(0x0)");
pendingVault = newVault;
delayVault = block.timestamp + delay;
emit LogChangeMPCOwner(vault, pendingVault, delayVault);
return true;
}
function mint(address to, uint256 amount) external onlyAuth returns (bool) {
_mint(to, amount);
return true;
}
function burn(address from, uint256 amount) external onlyAuth returns (bool) {
require(from != address(0), "AnyswapV3ERC20: address(0x0)");
_burn(from, amount);
return true;
}
function Swapin(bytes32 txhash, address account, uint256 amount) public onlyAuth returns (bool) {
_mint(account, amount);
emit LogSwapin(txhash, account, amount);
return true;
}
function Swapout(uint256 amount, address bindaddr) public returns (bool) {
require(!_vaultOnly, "AnyswapV4ERC20: onlyAuth");
require(bindaddr != address(0), "AnyswapV3ERC20: address(0x0)");
_burn(msg.sender, amount);
emit LogSwapout(msg.sender, bindaddr, amount);
return true;
}
/// @dev Records current ERC2612 nonce for account. This value must be included whenever signature is generated for {permit}.
/// Every successful call to {permit} increases account's nonce by one. This prevents signature from being used multiple times.
mapping (address => uint256) public override nonces;
/// @dev Records number of AnyswapV3ERC20 token that account (second) will be allowed to spend on behalf of another account (first) through {transferFrom}.
mapping (address => mapping (address => uint256)) public override allowance;
event LogChangeVault(address indexed oldVault, address indexed newVault, uint indexed effectiveTime);
event LogChangeMPCOwner(address indexed oldOwner, address indexed newOwner, uint indexed effectiveHeight);
event LogSwapin(bytes32 indexed txhash, address indexed account, uint amount);
event LogSwapout(address indexed account, address indexed bindaddr, uint amount);
event LogAddAuth(address indexed auth, uint timestamp);
constructor(string memory _name, string memory _symbol, uint8 _decimals, address _underlying, address _vault) {
name = _name;
symbol = _symbol;
decimals = _decimals;
underlying = _underlying;
if (_underlying != address(0x0)) {
require(_decimals == IERC20(_underlying).decimals());
}
// Use init to allow for CREATE2 accross all chains
_init = true;
// Disable/Enable swapout for v1 tokens vs mint/burn for v3 tokens
_vaultOnly = false;
vault = _vault;
pendingVault = _vault;
delayVault = block.timestamp;
uint256 chainId;
assembly {chainId := chainid()}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256(bytes("1")),
chainId,
address(this)));
}
/// @dev Returns the total supply of AnyswapV3ERC20 token as the ETH held in this contract.
function totalSupply() external view override returns (uint256) {
return _totalSupply;
}
function depositWithPermit(address target, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s, address to) external returns (uint) {
IERC20(underlying).permit(target, address(this), value, deadline, v, r, s);
IERC20(underlying).safeTransferFrom(target, address(this), value);
return _deposit(value, to);
}
function depositWithTransferPermit(address target, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s, address to) external returns (uint) {
IERC20(underlying).transferWithPermit(target, address(this), value, deadline, v, r, s);
return _deposit(value, to);
}
function deposit() external returns (uint) {
uint _amount = IERC20(underlying).balanceOf(msg.sender);
IERC20(underlying).safeTransferFrom(msg.sender, address(this), _amount);
return _deposit(_amount, msg.sender);
}
function deposit(uint amount) external returns (uint) {
IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount);
return _deposit(amount, msg.sender);
}
function deposit(uint amount, address to) external returns (uint) {
IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount);
return _deposit(amount, to);
}
function depositVault(uint amount, address to) external onlyVault returns (uint) {
return _deposit(amount, to);
}
function _deposit(uint amount, address to) internal returns (uint) {
require(underlying != address(0x0) && underlying != address(this));
_mint(to, amount);
return amount;
}
function withdraw() external returns (uint) {
return _withdraw(msg.sender, balanceOf[msg.sender], msg.sender);
}
function withdraw(uint amount) external returns (uint) {
return _withdraw(msg.sender, amount, msg.sender);
}
function withdraw(uint amount, address to) external returns (uint) {
return _withdraw(msg.sender, amount, to);
}
function withdrawVault(address from, uint amount, address to) external onlyVault returns (uint) {
return _withdraw(from, amount, to);
}
function _withdraw(address from, uint amount, address to) internal returns (uint) {
_burn(from, amount);
IERC20(underlying).safeTransfer(to, amount);
return amount;
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply += amount;
balanceOf[account] += amount;
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
balanceOf[account] -= amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/// @dev Sets `value` as allowance of `spender` account over caller account's AnyswapV3ERC20 token.
/// Emits {Approval} event.
/// Returns boolean value indicating whether operation succeeded.
function approve(address spender, uint256 value) external override returns (bool) {
// _approve(msg.sender, spender, value);
allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/// @dev Sets `value` as allowance of `spender` account over caller account's AnyswapV3ERC20 token,
/// after which a call is executed to an ERC677-compliant contract with the `data` parameter.
/// Emits {Approval} event.
/// Returns boolean value indicating whether operation succeeded.
/// For more information on approveAndCall format, see https://github.com/ethereum/EIPs/issues/677.
function approveAndCall(address spender, uint256 value, bytes calldata data) external override returns (bool) {
// _approve(msg.sender, spender, value);
allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return IApprovalReceiver(spender).onTokenApproval(msg.sender, value, data);
}
/// @dev Sets `value` as allowance of `spender` account over `owner` account's AnyswapV3ERC20 token, given `owner` account's signed approval.
/// Emits {Approval} event.
/// Requirements:
/// - `deadline` must be timestamp in future.
/// - `v`, `r` and `s` must be valid `secp256k1` signature from `owner` account over EIP712-formatted function arguments.
/// - the signature must use `owner` account's current nonce (see {nonces}).
/// - the signer cannot be zero address and must be `owner` account.
/// For more information on signature format, see https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP section].
/// AnyswapV3ERC20 token implementation adapted from https://github.com/albertocuestacanada/ERC20Permit/blob/master/contracts/ERC20Permit.sol.
function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external override {
require(block.timestamp <= deadline, "AnyswapV3ERC20: Expired permit");
bytes32 hashStruct = keccak256(
abi.encode(
PERMIT_TYPEHASH,
target,
spender,
value,
nonces[target]++,
deadline));
require(verifyEIP712(target, hashStruct, v, r, s) || verifyPersonalSign(target, hashStruct, v, r, s));
// _approve(owner, spender, value);
allowance[target][spender] = value;
emit Approval(target, spender, value);
}
function transferWithPermit(address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external override returns (bool) {
require(block.timestamp <= deadline, "AnyswapV3ERC20: Expired permit");
bytes32 hashStruct = keccak256(
abi.encode(
TRANSFER_TYPEHASH,
target,
to,
value,
nonces[target]++,
deadline));
require(verifyEIP712(target, hashStruct, v, r, s) || verifyPersonalSign(target, hashStruct, v, r, s));
require(to != address(0) || to != address(this));
uint256 balance = balanceOf[target];
require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance");
balanceOf[target] = balance - value;
balanceOf[to] += value;
emit Transfer(target, to, value);
return true;
}
function verifyEIP712(address target, bytes32 hashStruct, uint8 v, bytes32 r, bytes32 s) internal view returns (bool) {
bytes32 hash = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hashStruct));
address signer = ecrecover(hash, v, r, s);
return (signer != address(0) && signer == target);
}
function verifyPersonalSign(address target, bytes32 hashStruct, uint8 v, bytes32 r, bytes32 s) internal view returns (bool) {
bytes32 hash = prefixed(hashStruct);
address signer = ecrecover(hash, v, r, s);
return (signer != address(0) && signer == target);
}
// Builds a prefixed hash to mimic the behavior of eth_sign.
function prefixed(bytes32 hash) internal view returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", DOMAIN_SEPARATOR, hash));
}
/// @dev Moves `value` AnyswapV3ERC20 token from caller's account to account (`to`).
/// A transfer to `address(0)` triggers an ETH withdraw matching the sent AnyswapV3ERC20 token in favor of caller.
/// Emits {Transfer} event.
/// Returns boolean value indicating whether operation succeeded.
/// Requirements:
/// - caller account must have at least `value` AnyswapV3ERC20 token.
function transfer(address to, uint256 value) external override returns (bool) {
require(to != address(0) || to != address(this));
uint256 balance = balanceOf[msg.sender];
require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance");
balanceOf[msg.sender] = balance - value;
balanceOf[to] += value;
emit Transfer(msg.sender, to, value);
return true;
}
/// @dev Moves `value` AnyswapV3ERC20 token from account (`from`) to account (`to`) using allowance mechanism.
/// `value` is then deducted from caller account's allowance, unless set to `type(uint256).max`.
/// A transfer to `address(0)` triggers an ETH withdraw matching the sent AnyswapV3ERC20 token in favor of caller.
/// Emits {Approval} event to reflect reduced allowance `value` for caller account to spend from account (`from`),
/// unless allowance is set to `type(uint256).max`
/// Emits {Transfer} event.
/// Returns boolean value indicating whether operation succeeded.
/// Requirements:
/// - `from` account must have at least `value` balance of AnyswapV3ERC20 token.
/// - `from` account must have approved caller to spend at least `value` of AnyswapV3ERC20 token, unless `from` and caller are the same account.
function transferFrom(address from, address to, uint256 value) external override returns (bool) {
require(to != address(0) || to != address(this));
if (from != msg.sender) {
// _decreaseAllowance(from, msg.sender, value);
uint256 allowed = allowance[from][msg.sender];
if (allowed != type(uint256).max) {
require(allowed >= value, "AnyswapV3ERC20: request exceeds allowance");
uint256 reduced = allowed - value;
allowance[from][msg.sender] = reduced;
emit Approval(from, msg.sender, reduced);
}
}
uint256 balance = balanceOf[from];
require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance");
balanceOf[from] = balance - value;
balanceOf[to] += value;
emit Transfer(from, to, value);
return true;
}
/// @dev Moves `value` AnyswapV3ERC20 token from caller's account to account (`to`),
/// after which a call is executed to an ERC677-compliant contract with the `data` parameter.
/// A transfer to `address(0)` triggers an ETH withdraw matching the sent AnyswapV3ERC20 token in favor of caller.
/// Emits {Transfer} event.
/// Returns boolean value indicating whether operation succeeded.
/// Requirements:
/// - caller account must have at least `value` AnyswapV3ERC20 token.
/// For more information on transferAndCall format, see https://github.com/ethereum/EIPs/issues/677.
function transferAndCall(address to, uint value, bytes calldata data) external override returns (bool) {
require(to != address(0) || to != address(this));
uint256 balance = balanceOf[msg.sender];
require(balance >= value, "AnyswapV3ERC20: transfer amount exceeds balance");
balanceOf[msg.sender] = balance - value;
balanceOf[to] += value;
emit Transfer(msg.sender, to, value);
return ITransferReceiver(to).onTokenTransfer(msg.sender, value, data);
}
} | Interface of the ERC20 standard as defined in the EIP./ | interface IERC20 {
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
function transferWithPermit(address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| 37,963 |
pragma solidity 0.4.21;
// ----------------------------------------------------------------------------
// 'ANDRS' 'Andreis Token' token contract
//
// Symbol : INO8
// Name : AndreisToken
// Total supply: Generated from contributions
// Decimals : 18
//
//
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals
// Receives ETH and generates tokens
// ----------------------------------------------------------------------------
contract AndreisToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint256 public sellPrice;
uint256 public buyPrice;
mapping(address => uint) public balances;
mapping(address => mapping(address => uint)) public allowed;
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function AndreisToken() public {
symbol = "ANDRS";
name = "AndreisToken";
decimals = 18;
_totalSupply = 250000000 * 10**uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view returns (uint) {
return safeSub(_totalSupply , balances[address(0)]);
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) onlyPayloadSize(safeMul(2,32)) public returns (bool success) {
_transfer(msg.sender, to, tokens); // makes the transfers
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) onlyPayloadSize(safeMul(3,32)) public returns (bool success) {
require (to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balances[from] >= tokens); // Check if the sender has enough
require (safeAdd(balances[to] , tokens) >= balances[to]); // Check for overflows
require(!frozenAccount[from]); // Check if sender is frozen
require(!frozenAccount[to]); // Check if recipient is frozen
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
/// @notice 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) onlyOwner public {
balances[target] = safeAdd(balances[target], mintedAmount);
_totalSupply = safeAdd(_totalSupply, mintedAmount);
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
/// @notice `freeze? Prevent | Allow` `from` from sending & receiving tokens
/// @param from Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address from, bool freeze) onlyOwner public {
frozenAccount[from] = freeze;
emit FrozenFunds(from, freeze);
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balances[_from] >= _value); // Check if the sender has enough
require (safeAdd(balances[_to] , _value) >= balances[_to]); // Check for overflows
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
balances[_from] = safeSub(balances[_from], _value);
balances[_to] = safeAdd(balances[_to], _value);
emit Transfer(_from, _to, _value);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/// @notice Buy tokens from contract by sending ether
function buy() payable public {
uint amount = safeDiv(msg.value , buyPrice); // calculates the amount
_transfer(this, msg.sender, amount); // makes the transfers
}
/// @notice Sell `amount` tokens to contract
/// @param amount amount of tokens to be sold
function sell(uint256 amount) public {
require(address(this).balance >= safeMul(amount ,sellPrice)); // checks if the contract has enough ether to buy
_transfer(msg.sender, this, amount); // makes the transfers
msg.sender.transfer(safeMul(amount ,sellPrice)); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
/**
* 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(balances[msg.sender] >= _value); // Check if the sender has enough
balances[msg.sender] = safeSub(balances[msg.sender], _value); // Subtract from the sender
_totalSupply = safeSub(_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(balances[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowed[_from][msg.sender]); // Check allowance
balances[_from] = safeSub(balances[_from], _value); // Subtract from the targeted balance
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value); // Subtract from the sender's allowance
_totalSupply = safeSub(_totalSupply, _value); // Update totalSupply
emit Burn(_from, _value);
return true;
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | Sell `amount` tokens to contract amount amount of tokens to be sold | function sell(uint256 amount) public {
}
| 1,520,731 |
./full_match/80001/0x94588694589dA99cf281d3275402D3AD19Ea4827/sources/contracts/RandomNumberGenerator.sol | Set the address for the MakiSwap Lottery _makiLottery: address of the MakiSwap lottery/ | function setLotteryAddress(address _makiLottery) external onlyOwner {
makiLottery = _makiLottery;
}
| 9,512,198 |
pragma solidity 0.8.6;
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);
}
abstract contract IERC20WithCheckpointing {
function balanceOf(address _owner) public view virtual returns (uint256);
function balanceOfAt(address _owner, uint256 _blockNumber)
public
view
virtual
returns (uint256);
function totalSupply() public view virtual returns (uint256);
function totalSupplyAt(uint256 _blockNumber) public view virtual returns (uint256);
}
abstract contract IIncentivisedVotingLockup is IERC20WithCheckpointing {
function getLastUserPoint(address _addr)
external
view
virtual
returns (
int128 bias,
int128 slope,
uint256 ts
);
function createLock(uint256 _value, uint256 _unlockTime) external virtual;
function withdraw() external virtual;
function increaseLockAmount(uint256 _value) external virtual;
function increaseLockLength(uint256 _unlockTime) external virtual;
function eject(address _user) external virtual;
function expireContract() external virtual;
function claimReward() public virtual;
function earned(address _account) public view virtual returns (uint256);
}
interface IBoostedVaultWithLockup {
/**
* @dev Stakes a given amount of the StakingToken for the sender
* @param _amount Units of StakingToken
*/
function stake(uint256 _amount) external;
/**
* @dev Stakes a given amount of the StakingToken for a given beneficiary
* @param _beneficiary Staked tokens are credited to this address
* @param _amount Units of StakingToken
*/
function stake(address _beneficiary, uint256 _amount) external;
/**
* @dev Withdraws stake from pool and claims any unlocked rewards.
* Note, this function is costly - the args for _claimRewards
* should be determined off chain and then passed to other fn
*/
function exit() external;
/**
* @dev Withdraws stake from pool and claims any unlocked rewards.
* @param _first Index of the first array element to claim
* @param _last Index of the last array element to claim
*/
function exit(uint256 _first, uint256 _last) external;
/**
* @dev Withdraws given stake amount from the pool
* @param _amount Units of the staked token to withdraw
*/
function withdraw(uint256 _amount) external;
/**
* @dev Claims only the tokens that have been immediately unlocked, not including
* those that are in the lockers.
*/
function claimReward() external;
/**
* @dev Claims all unlocked rewards for sender.
* Note, this function is costly - the args for _claimRewards
* should be determined off chain and then passed to other fn
*/
function claimRewards() external;
/**
* @dev Claims all unlocked rewards for sender. Both immediately unlocked
* rewards and also locked rewards past their time lock.
* @param _first Index of the first array element to claim
* @param _last Index of the last array element to claim
*/
function claimRewards(uint256 _first, uint256 _last) external;
/**
* @dev Pokes a given account to reset the boost
*/
function pokeBoost(address _account) external;
/**
* @dev Gets the last applicable timestamp for this reward period
*/
function lastTimeRewardApplicable() external view returns (uint256);
/**
* @dev Calculates the amount of unclaimed rewards per token since last update,
* and sums with stored to give the new cumulative reward per token
* @return 'Reward' per staked token
*/
function rewardPerToken() external view returns (uint256);
/**
* @dev Returned the units of IMMEDIATELY claimable rewards a user has to receive. Note - this
* does NOT include the majority of rewards which will be locked up.
* @param _account User address
* @return Total reward amount earned
*/
function earned(address _account) external view returns (uint256);
/**
* @dev Calculates all unclaimed reward data, finding both immediately unlocked rewards
* and those that have passed their time lock.
* @param _account User address
* @return amount Total units of unclaimed rewards
* @return first Index of the first userReward that has unlocked
* @return last Index of the last userReward that has unlocked
*/
function unclaimedRewards(address _account)
external
view
returns (
uint256 amount,
uint256 first,
uint256 last
);
}
interface IBoostDirector {
function getBalance(address _user) external returns (uint256);
function setDirection(
address _old,
address _new,
bool _pokeNew
) external;
function whitelistVaults(address[] calldata _vaults) external;
}
contract ModuleKeys {
// Governance
// ===========
// keccak256("Governance");
bytes32 internal constant KEY_GOVERNANCE =
0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d;
//keccak256("Staking");
bytes32 internal constant KEY_STAKING =
0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034;
//keccak256("ProxyAdmin");
bytes32 internal constant KEY_PROXY_ADMIN =
0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1;
// mStable
// =======
// keccak256("OracleHub");
bytes32 internal constant KEY_ORACLE_HUB =
0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040;
// keccak256("Manager");
bytes32 internal constant KEY_MANAGER =
0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f;
//keccak256("Recollateraliser");
bytes32 internal constant KEY_RECOLLATERALISER =
0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f;
//keccak256("MetaToken");
bytes32 internal constant KEY_META_TOKEN =
0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2;
// keccak256("SavingsManager");
bytes32 internal constant KEY_SAVINGS_MANAGER =
0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1;
// keccak256("Liquidator");
bytes32 internal constant KEY_LIQUIDATOR =
0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4;
// keccak256("InterestValidator");
bytes32 internal constant KEY_INTEREST_VALIDATOR =
0xc10a28f028c7f7282a03c90608e38a4a646e136e614e4b07d119280c5f7f839f;
}
interface INexus {
function governor() external view returns (address);
function getModule(bytes32 key) external view returns (address);
function proposeModule(bytes32 _key, address _addr) external;
function cancelProposedModule(bytes32 _key) external;
function acceptProposedModule(bytes32 _key) external;
function acceptProposedModules(bytes32[] calldata _keys) external;
function requestLockModule(bytes32 _key) external;
function cancelLockModule(bytes32 _key) external;
function lockModule(bytes32 _key) external;
}
abstract contract ImmutableModule is ModuleKeys {
INexus public immutable nexus;
/**
* @dev Initialization function for upgradable proxy contracts
* @param _nexus Nexus contract address
*/
constructor(address _nexus) {
require(_nexus != address(0), "Nexus address is zero");
nexus = INexus(_nexus);
}
/**
* @dev Modifier to allow function calls only from the Governor.
*/
modifier onlyGovernor() {
_onlyGovernor();
_;
}
function _onlyGovernor() internal view {
require(msg.sender == _governor(), "Only governor can execute");
}
/**
* @dev Modifier to allow function calls only from the Governance.
* Governance is either Governor address or Governance address.
*/
modifier onlyGovernance() {
require(
msg.sender == _governor() || msg.sender == _governance(),
"Only governance can execute"
);
_;
}
/**
* @dev Returns Governor address from the Nexus
* @return Address of Governor Contract
*/
function _governor() internal view returns (address) {
return nexus.governor();
}
/**
* @dev Returns Governance Module address from the Nexus
* @return Address of the Governance (Phase 2)
*/
function _governance() internal view returns (address) {
return nexus.getModule(KEY_GOVERNANCE);
}
/**
* @dev Return SavingsManager Module address from the Nexus
* @return Address of the SavingsManager Module contract
*/
function _savingsManager() internal view returns (address) {
return nexus.getModule(KEY_SAVINGS_MANAGER);
}
/**
* @dev Return Recollateraliser Module address from the Nexus
* @return Address of the Recollateraliser Module contract (Phase 2)
*/
function _recollateraliser() internal view returns (address) {
return nexus.getModule(KEY_RECOLLATERALISER);
}
/**
* @dev Return Liquidator Module address from the Nexus
* @return Address of the Liquidator Module contract
*/
function _liquidator() internal view returns (address) {
return nexus.getModule(KEY_LIQUIDATOR);
}
/**
* @dev Return ProxyAdmin Module address from the Nexus
* @return Address of the ProxyAdmin Module contract
*/
function _proxyAdmin() internal view returns (address) {
return nexus.getModule(KEY_PROXY_ADMIN);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
// Internal
/**
* @title BoostDirectorV2
* @author mStable
* @notice Supports the directing of balance from multiple StakedToken contracts up to X accounts
* @dev Uses a bitmap to store the id's of a given users chosen vaults in a gas efficient manner.
*/
contract BoostDirectorV2 is IBoostDirector, ImmutableModule {
event Directed(address user, address boosted);
event RedirectedBoost(address user, address boosted, address replaced);
event Whitelisted(address vaultAddress, uint8 vaultId);
event StakedTokenAdded(address token);
event StakedTokenRemoved(address token);
event BalanceDivisorChanged(uint256 newDivisor);
// Read the vMTA balance from here
IERC20[] public stakedTokenContracts;
// Whitelisted vaults set by governance (only these vaults can read balances)
uint8 private vaultCount;
// Vault address -> internal id for tracking
mapping(address => uint8) public _vaults;
// uint128 packed with up to 16 uint8's. Each uint is a vault ID
mapping(address => uint128) public _directedBitmap;
// Divisor for voting powers to make more reasonable in vault
uint256 private balanceDivisor;
/***************************************
ADMIN
****************************************/
// Simple constructor
constructor(address _nexus) ImmutableModule(_nexus) {
balanceDivisor = 12;
}
/**
* @dev Initialize function - simply sets the initial array of whitelisted vaults
*/
function initialize(address[] calldata _newVaults) external {
require(vaultCount == 0, "Already initialized");
_whitelistVaults(_newVaults);
}
/**
* @dev Adds a staked token to the list, if it does not yet exist
*/
function addStakedToken(address _stakedToken) external onlyGovernor {
uint256 len = stakedTokenContracts.length;
for (uint256 i = 0; i < len; i++) {
require(address(stakedTokenContracts[i]) != _stakedToken, "StakedToken already added");
}
stakedTokenContracts.push(IERC20(_stakedToken));
emit StakedTokenAdded(_stakedToken);
}
/**
* @dev Removes a staked token from the list
*/
function removeStakedTkoen(address _stakedToken) external onlyGovernor {
uint256 len = stakedTokenContracts.length;
for (uint256 i = 0; i < len; i++) {
// If we find it, then swap it with the last element and delete the end
if (address(stakedTokenContracts[i]) == _stakedToken) {
stakedTokenContracts[i] = stakedTokenContracts[len - 1];
stakedTokenContracts.pop();
emit StakedTokenRemoved(_stakedToken);
return;
}
}
}
/**
* @dev Sets the divisor, by which all balances will be scaled down
*/
function setBalanceDivisor(uint256 _newDivisor) external onlyGovernor {
require(_newDivisor != balanceDivisor, "No change in divisor");
require(_newDivisor < 15, "Divisor too large");
balanceDivisor = _newDivisor;
emit BalanceDivisorChanged(_newDivisor);
}
/**
* @dev Whitelist vaults - only callable by governance. Whitelists vaults, unless they
* have already been whitelisted
*/
function whitelistVaults(address[] calldata _newVaults) external override onlyGovernor {
_whitelistVaults(_newVaults);
}
/**
* @dev Takes an array of newVaults. For each, determines if it is already whitelisted.
* If not, then increment vaultCount and same the vault with new ID
*/
function _whitelistVaults(address[] calldata _newVaults) internal {
uint256 len = _newVaults.length;
require(len > 0, "Must be at least one vault");
for (uint256 i = 0; i < len; i++) {
uint8 id = _vaults[_newVaults[i]];
require(id == 0, "Vault already whitelisted");
vaultCount += 1;
_vaults[_newVaults[i]] = vaultCount;
emit Whitelisted(_newVaults[i], vaultCount);
}
}
/***************************************
Vault
****************************************/
/**
* @dev Gets the balance of a user that has been directed to the caller (a vault).
* If the user has not directed to this vault, or there are less than 6 directed,
* then add this to the list
* @param _user Address of the user for which to get balance
* @return bal Directed balance
*/
function getBalance(address _user) external override returns (uint256 bal) {
// Get vault details
uint8 id = _vaults[msg.sender];
// If vault has not been whitelisted, just return zero
if (id == 0) return 0;
// Get existing bitmap and balance
uint128 bitmap = _directedBitmap[_user];
uint256 len = stakedTokenContracts.length;
for (uint256 i = 0; i < len; i++) {
bal += stakedTokenContracts[i].balanceOf(_user);
}
bal /= balanceDivisor;
(bool isWhitelisted, uint8 count, ) = _indexExists(bitmap, id);
if (isWhitelisted) return bal;
if (count < 6) {
_directedBitmap[_user] = _direct(bitmap, count, id);
emit Directed(_user, msg.sender);
return bal;
}
if (count >= 6) return 0;
}
/**
* @dev Directs rewards to a vault, and removes them from the old vault. Provided
* that old is active and the new vault is whitelisted.
* @param _old Address of the old vault that will no longer get boosted
* @param _new Address of the new vault that will get boosted
* @param _pokeNew Bool to say if we should poke the boost on the new vault
*/
function setDirection(
address _old,
address _new,
bool _pokeNew
) external override {
uint8 idOld = _vaults[_old];
uint8 idNew = _vaults[_new];
require(idOld > 0 && idNew > 0, "Vaults not whitelisted");
uint128 bitmap = _directedBitmap[msg.sender];
(bool isWhitelisted, uint8 count, uint8 pos) = _indexExists(bitmap, idOld);
require(isWhitelisted && count >= 6, "No need to replace old");
_directedBitmap[msg.sender] = _direct(bitmap, pos, idNew);
IBoostedVaultWithLockup(_old).pokeBoost(msg.sender);
if (_pokeNew) {
IBoostedVaultWithLockup(_new).pokeBoost(msg.sender);
}
emit RedirectedBoost(msg.sender, _new, _old);
}
/**
* @dev Resets the bitmap given the new _id for _pos. Takes each uint8 in seperate and re-compiles
*/
function _direct(
uint128 _bitmap,
uint8 _pos,
uint8 _id
) internal pure returns (uint128 newMap) {
// bitmap = ... 00000000 00000000 00000011 00001010
// pos = 1, id = 1 = 00000001
// step = ... 00000000 00000000 00000001 00000000
uint8 id;
uint128 step;
for (uint8 i = 0; i < 6; i++) {
unchecked {
// id is either the one that is passed, or existing
id = _pos == i ? _id : uint8(_bitmap >> (i * 8));
step = uint128(uint128(id) << (i * 8));
}
newMap |= step;
}
}
/**
* @dev Given a 128 bit bitmap packed with 8 bit ids, should be able to filter for specific ids by moving
* the bitmap gradually to the right and reading each 8 bit section as a uint8.
*/
function _indexExists(uint128 _bitmap, uint8 _target)
internal
pure
returns (
bool isWhitelisted,
uint8 count,
uint8 pos
)
{
// bitmap = ... 00000000 00000000 00000011 00001010 // positions 1 and 2 have ids 10 and 6 respectively
// e.g.
// i = 1: bitmap moves 8 bits to the right
// bitmap = ... 00000000 00000000 00000000 00000011 // reading uint8 should return 6
uint8 id;
for (uint8 i = 0; i < 6; i++) {
unchecked {
id = uint8(_bitmap >> (i * 8));
}
if (id > 0) count += 1;
if (id == _target) {
isWhitelisted = true;
pos = i;
}
}
}
} | Removes a staked token from the list/ If we find it, then swap it with the last element and delete the end | function removeStakedTkoen(address _stakedToken) external onlyGovernor {
uint256 len = stakedTokenContracts.length;
for (uint256 i = 0; i < len; i++) {
if (address(stakedTokenContracts[i]) == _stakedToken) {
stakedTokenContracts[i] = stakedTokenContracts[len - 1];
stakedTokenContracts.pop();
emit StakedTokenRemoved(_stakedToken);
return;
}
}
}
| 638,710 |
./partial_match/1/0x1A963Df363D01EEBB2816b366d61C917F20e1EbE/sources/src/DAIInterestRateModelV3.sol | Calculates the current supply interest rate per block including the Dai savings rate cash The total amount of cash the market has borrows The total amount of borrows the market has outstanding reserves The total amnount of reserves the market has reserveFactorMantissa The current reserve factor the market has return The supply rate per block (as a percentage, and scaled by BASE)/ | function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) override public view returns (uint) {
uint protocolRate = super.getSupplyRate(cash, borrows, reserves, reserveFactorMantissa);
uint underlying = cash + borrows - reserves;
if (underlying == 0) {
return protocolRate;
uint cashRate = cash * dsrPerBlock() / underlying;
return cashRate + protocolRate;
}
}
| 2,594,800 |
./partial_match/1/0x883A0E7b329Df75476d9378462522CF2f78Fab3d/sources/Synthetix.sol | Ensure they're not trying to exceed their locked amount -- only if they have debt. Perform the transfer: if there is a problem, an exception will be thrown in this call. | function transferFrom(
address from,
address to,
uint value
) external onlyProxyOrInternal systemActive returns (bool) {
_canTransfer(from, value);
return _transferFromByProxy(messageSender, from, to, value);
}
| 15,766,129 |
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
import "./EternalStorage.sol";
import "./StorageDefinition.sol";
import "./Consortium.sol";
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) {
require(b <= a, "SafeMath: subtraction overflow");
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-solidity/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) {
// 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;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
library Counters {
using SafeMath for uint256;
struct Counter {
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
contract ERC165 {
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
_registerInterface(_INTERFACE_ID_ERC165);
}
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
contract Ownable {
address private _owner;
address private _newOwner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require( msg.sender == _owner, "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_newOwner = newOwner;
}
function acceptOwnership() public {
require(msg.sender == _newOwner);
_owner = _newOwner;
}
}
contract IERC721Receiver {
function onERC721Received(address operator, address from, string memory tokenId, bytes memory data)
public returns (bytes4);
}
contract ERC721 is ERC165, Ownable {
using SafeMath for uint256;
using Counters for Counters.Counter;
event Transfer(address indexed from, address indexed to, string tokenId);
event Approval(address indexed owner, address indexed approved, string tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
EternalStorage s;
Consortium registerContract;
// 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 token ID to owner
mapping (string => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (string => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
constructor (address storageAddress) public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
s = EternalStorage(storageAddress);
}
modifier onlyRegistrant() {
require(s.getUserDetails().role == StorageDefinition.roles.admin || s.getUserDetails().role == StorageDefinition.roles.registrant);
_;
}
/**
* @dev Gets the balance of the specified address.
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].current();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(string memory tokenId) public view returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, string memory tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(msg.sender == owner || isApprovedForAll(owner, msg.sender),
"ERC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
function BatchApprove(address to, string[] memory tokenId) public {
for (uint i=0; i< tokenId.length; i++){
address owner = ownerOf(tokenId[i]);
require(to != owner, "ERC721: approval to current owner");
require(msg.sender == owner || isApprovedForAll(owner, msg.sender),
"ERC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId[i]] = to;
emit Approval(owner, to, tokenId[i]);
}
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(string memory tokenId) public view returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
// function setApprovalForAll(address to, bool approved) public {
// require(to != msg.sender, "ERC721: approve to caller");
// _operatorApprovals[msg.sender][to] = approved;
// emit ApprovalForAll(msg.sender, to, approved);
// }
/**
* @dev Tells whether an operator is approved by a given owner.
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, string memory tokenId) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_transferFrom(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
// function safeTransferFrom(address from, address to, string memory tokenId) public {
// safeTransferFrom(from, to, tokenId, "");
// }
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
// function safeTransferFrom(address from, address to, string memory tokenId, bytes memory _data) public {
// transferFrom(from, to, tokenId);
// require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
// }
/**
* @dev Returns whether the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(string memory tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
// function _projectExists(string memory tokenId) internal view returns (bool) {
// string memory name = _tokenProject[tokenId];
// return (keccak256(abi.encodePacked((tokenId))) == keccak256(abi.encodePacked((""))) );
// }
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, string memory tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, string memory tokenId) internal {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, string memory tokenId) internal {
require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own");
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
function _burn(string memory tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, string memory tokenId) internal {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address.
* The call is not executed if the target address is not a contract.
*
* This function is deprecated.
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, string memory tokenId, bytes memory _data)
internal returns (bool)
{
uint256 size;
assembly { size := extcodesize(to) }
if (size == 0) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given token ID.
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(string memory tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
contract ERC721Burnable is ERC721 {
/**
* @dev Burns a specific ERC721 token.
* @param tokenId uint256 id of the ERC721 token to be burned.
*/
function burn(string memory tokenId) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
/**
* @title ERC721Mintable
* @dev ERC721 minting logic.
*/
contract ERC721Mintable is ERC721 {
/**
* @dev Function to mint tokens.
* @param to The address that will receive the minted tokens.
* @param tokenId The token id to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, string memory tokenId) internal returns (bool) {
_mint(to, tokenId);
return true;
}
}
contract ERC721Metadata is ERC165, ERC721{
struct deviceDetails {
string[] certificateURLs;
string[] ipfsHash;
string thingBrand;
string thingDescription;
string thingName;
string thingStory;
string thingValue;
uint256 timeStamp;
bytes32 projectId;
}
// Optional mapping for token URIs
mapping(string => string) private _tokenURIs;
// mapping for token deviceDetails
mapping(string => deviceDetails) private _tokenDetails;
// Optional mapping for project ids
// mapping(string => string) private _projectIds;
/*
* 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;
/**
* @dev Constructor function
*/
constructor () public {
// _name = "<%= tokenName %>";
// _symbol = "<%= tokenSymbol %>";
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
// /**
// * @dev Gets the token name.
// * @return string representing the token name
// */
// function name() external view returns (string memory) {
// return _name;
// }
// /**
// * @dev Gets the token symbol.
// * @return string representing the token symbol
// */
// function symbol() external view returns (string memory) {
// return _symbol;
// }
/**
* @dev Returns an URI for a given token ID.
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenURI(string calldata tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return (_tokenURIs[tokenId]);
}
function getProductDetails(string calldata tokenId) external view returns (deviceDetails memory,string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return (_tokenDetails[tokenId],_tokenURIs[tokenId]);
}
/**
* @dev Internal function to set the token URI for a given token.
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(string memory tokenId, string memory uri) internal {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = uri;
// _projectIds[tokenId] = projectId;
}
function _setProjectId (string memory tokenId, bytes32 projectId) internal{
require(_tokenDetails[tokenId].projectId == 0x0, "Project Id reassign denied!");
deviceDetails memory temp = _tokenDetails[tokenId];
temp.projectId = projectId;
_tokenDetails[tokenId] = temp;
}
function _setProductDetails(string memory tokenId,string[] memory certificateURLs, string[] memory ipfsHash, string memory thingBrand, string memory thingDescription, string memory thingName, string memory thingStory, string memory thingValue ) internal {
deviceDetails memory temp;
temp.certificateURLs = certificateURLs;
temp.ipfsHash = ipfsHash;
temp.thingBrand = thingBrand;
temp.thingDescription = thingDescription;
temp.thingValue = thingValue;
temp.thingStory = thingStory;
temp.thingName = thingName;
temp.timeStamp = block.timestamp;
_tokenDetails[tokenId] = temp;
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, string memory tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
contract ERC721Enumerable is ERC165, ERC721,ERC721Metadata {
// Mapping from owner to list of owned token IDs
mapping(address => string[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(string => uint256) private _ownedTokensIndex;
// Mapping from project to list of owned token IDs
mapping(bytes32 => string[]) private _ownedTokensByProject;
// Mapping from token ID to index of the project tokens list
mapping(string => uint256) private _ownedTokensByProjectIndex;
// Array with all token ids, used for enumeration
string[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(string => uint256) private _allTokensIndex;
/*
* 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 Constructor function.
*/
constructor () public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner.
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (string memory) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens.
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view returns (string memory) {
require(index < totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
function _setProjectId (string memory tokenId, bytes32 projectId) internal{
super._setProjectId(tokenId, projectId);
_addTokenToProjectEnumeration(projectId,tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, string memory tokenId) internal {
super._transferFrom(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
// _removeTokenFromProjectEnumeration(projectId, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
// _addTokenToProjectEnumeration(projectId, tokenId);
}
function _addTokenToProjectEnumeration(bytes32 projectId , string memory tokenId) private {
_ownedTokensIndex[tokenId] = _ownedTokensByProject[projectId].length;
_ownedTokensByProject[projectId].push(tokenId);
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, string memory tokenId) internal {
super._mint(to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
_addTokenToAllTokensEnumeration(tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, string memory tokenId) internal {
super._burn(owner, tokenId);
_removeTokenFromOwnerEnumeration(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_removeTokenFromAllTokensEnumeration(tokenId);
}
/**
* @dev Gets the list of token IDs of the requested owner.
* @param owner address owning the tokens
* @return uint256[] List of token IDs owned by the requested address
*/
function _tokensOfOwner(address owner) public view returns (string[] memory) {
return _ownedTokens[owner];
}
function _tokensOfProject(bytes32 projectId) public view returns (string[] memory) {
return _ownedTokensByProject[projectId];
}
/**
* @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, string memory tokenId) private {
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
/**
* @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(string memory 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, string memory 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 = _ownedTokens[from].length.sub(1);
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
string memory 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
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
/**
* @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(string memory 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.sub(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)
string memory 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
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
contract ThingContract is ERC721, ERC721Enumerable, ERC721Mintable, ERC721Burnable {
constructor(address storageAddress) ERC721(storageAddress) public {
}
event MetadataChanged(string tokenId , string metadata);
function setAdditionalDetails(string memory tokenId, string memory metadata ) public onlyRegistrant returns (bool) {
require(ownerOf(tokenId) == msg.sender, "ERC721: can not set metadata of token that is not own");
_setTokenURI(tokenId , metadata);
emit MetadataChanged(tokenId,metadata);
return true;
}
function setProjectId(string memory tokenId, bytes32 projectId ) public onlyRegistrant returns (bool) {
registerContract = Consortium(s.getRegisteredContractAddress("Consortium"));
require(ownerOf(tokenId) == msg.sender, "ERC721: can not set metadata of token that is not own");
_setProjectId(tokenId , projectId);
registerContract.addProductToProject(tokenId, projectId);
return true;
}
function MintWithDetailsAndProjectId (address to, string memory tokenId, string[] memory certificateURLs, string[] memory ipfsHash, string memory thingBrand, string memory thingDescription, string memory thingName, string memory thingStory, string memory thingValue, bytes32 projectId) public onlyRegistrant returns (bool){
registerContract = Consortium(s.getRegisteredContractAddress("Consortium"));
_setProductDetails(tokenId,certificateURLs, ipfsHash, thingBrand, thingDescription, thingName, thingStory, thingValue );
mint(to, tokenId);
_setProjectId(tokenId , projectId);
registerContract.addProductToProject(tokenId, projectId);
return true;
}
function MintWithDetails(address to, string memory tokenId, string[] memory certificateURLs, string[] memory ipfsHash, string memory thingBrand, string memory thingDescription, string memory thingName, string memory thingStory, string memory thingValue ) public onlyRegistrant returns (bool) {
_setProductDetails(tokenId,certificateURLs, ipfsHash, thingBrand, thingDescription, thingName, thingStory, thingValue );
mint(to, tokenId);
return true;
}
}
| Gets the token ID at a given index of all the tokens in this contract Reverts if the index is greater or equal to the total number of tokens. index uint256 representing the index to be accessed of the tokens list return uint256 token ID at the given index of the tokens list/ | function tokenByIndex(uint256 index) public view returns (string memory) {
require(index < totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
| 13,014,035 |
//SPDX-License-Identifier: MIT
//Copyright 2021 Louis Sobel
pragma solidity ^0.8.0;
/*
88888888ba, 88888888ba 888b 88 88888888888 888888888888
88 `"8b 88 "8b 8888b 88 88 88
88 `8b 88 ,8P 88 `8b 88 88 88
88 88 88aaaaaa8P' 88 `8b 88 88aaaaa 88
88 88 88""""""8b, 88 `8b 88 88""""" 88
88 8P 88 `8b 88 `8b 88 88 88
88 .a8P 88 a8P 88 `8888 88 88
88888888Y"' 88888888P" 88 `888 88 88
https://dbnft.io
Generate NFTs by compiling the DBN language to EVM opcodes, then
deploying a contract that can render your art as a bitmap.
> Line 0 0 100 100
╱
╱
╱
╱
╱
╱
╱
╱
╱
╱
*/
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./DBNERC721Enumerable.sol";
import "./OpenSeaTradable.sol";
import "./OwnerSignedTicketRestrictable.sol";
import "./Drawing.sol";
import "./Token.sol";
import "./Serialize.sol";
/**
* @notice Compile DBN drawings to Ethereum Virtual Machine opcodes and deploy the code as NFT art.
* @dev This contract implements the ERC721 (including Metadata and Enumerable extensions)
* @author Louis Sobel
*/
contract DBNCoordinator is Ownable, DBNERC721Enumerable, OpenSeaTradable, OwnerSignedTicketRestrictable {
using Counters for Counters.Counter;
using Strings for uint256;
/**
* @dev There's two ~types of tokenId out of the 10201 (101x101) total tokens
* - 101 "allowlisted ones" [0, 100]
* - And "Open" ones [101, 10200]
* Minting of the allowlisted ones is through mintTokenId function
* Minting of the Open ones is through plain mint
*/
uint256 private constant LAST_ALLOWLISTED_TOKEN_ID = 100;
uint256 private constant LAST_TOKEN_ID = 10200;
/**
* @dev Event emitted when a a token is minted, linking the token ID
* to the address of the deployed drawing contract
*/
event DrawingDeployed(uint256 tokenId, address addr);
// Configuration
enum ContractMode { AllowlistOnly, Open }
ContractMode private _contractMode;
uint256 private _mintPrice;
string private _baseExternalURI;
address payable public recipient;
bool public recipientLocked;
// Minting
Counters.Counter private _tokenIds;
mapping (uint256 => address) private _drawingAddressForTokenId;
/**
* @dev Initializes the contract
* @param owner address to immediately transfer the contract to
* @param baseExternalURI URL (like https//dbnft.io/dbnft/) to which
* tokenIDs will be appended to get the `external_URL` metadata field
* @param openSeaProxyRegistry address of the opensea proxy registry, will
* be saved and queried in isAllowedForAll to facilitate opensea listing
*/
constructor(
address owner,
string memory baseExternalURI,
address payable _recipient,
address openSeaProxyRegistry
) ERC721("Design By Numbers NFT", "DBNFT") {
transferOwnership(owner);
_baseExternalURI = baseExternalURI;
_contractMode = ContractMode.AllowlistOnly;
// first _open_ token id
_tokenIds._value = LAST_ALLOWLISTED_TOKEN_ID + 1;
// initial mint price
_mintPrice = 0;
// initial recipient
recipient = _recipient;
// set up the opensea proxy registry
_setOpenSeaRegistry(openSeaProxyRegistry);
}
/******************************************************************************************
* _____ ____ _ _ ______ _____ _____
* / ____/ __ \| \ | | ____|_ _/ ____|
* | | | | | | \| | |__ | || | __
* | | | | | | . ` | __| | || | |_ |
* | |___| |__| | |\ | | _| || |__| |
* \_____\____/|_| \_|_| |_____\_____|
*
* Functions for configuring / interacting with the contract itself
*/
/**
* @notice The current "mode" of the contract: either AllowlistOnly (0) or Open (1).
* In AllowlistOnly mode, a signed ticket is required to mint. In Open mode,
* minting is open to all.
*/
function getContractMode() public view returns (ContractMode) {
return _contractMode;
}
/**
* @notice Moves the contract mode to Open. Only the owner can call this. Once the
* contract moves to Open, it cannot be moved back to AllowlistOnly
*/
function openMinting() public onlyOwner {
_contractMode = ContractMode.Open;
}
/**
* @notice Returns the current cost to mint. Applies to either mode.
* (And of course, this does not include gas ⛽️)
*/
function getMintPrice() public view returns (uint256) {
return _mintPrice;
}
/**
* @notice Sets the cost to mint. Only the owner can call this.
*/
function setMintPrice(uint256 price) public onlyOwner {
_mintPrice = price;
}
/**
* @notice Sets the recipient. Cannot be called after the recipient is locked.
* Only the owner can call this.
*/
function setRecipient(address payable to) public onlyOwner {
require(!recipientLocked, "RECIPIENT_LOCKED");
recipient = to;
}
/**
* @notice Prevents any future changes to the recipient.
* Only the owner can call this.
* @dev This enables post-deploy configurability of the recipient,
* combined with the ability to lock it in to facilitate
* confidence as to where the funds will be able to go.
*/
function lockRecipient() public onlyOwner {
recipientLocked = true;
}
/**
* @notice Disburses the contract balance to the stored recipient.
* Only the owner can call this.
*/
function disburse() public onlyOwner {
recipient.transfer(address(this).balance);
}
/******************************************************************************************
* __ __ _____ _ _ _______ _____ _ _ _____
* | \/ |_ _| \ | |__ __|_ _| \ | |/ ____|
* | \ / | | | | \| | | | | | | \| | | __
* | |\/| | | | | . ` | | | | | | . ` | | |_ |
* | | | |_| |_| |\ | | | _| |_| |\ | |__| |
* |_| |_|_____|_| \_| |_| |_____|_| \_|\_____|
*
* Functions for minting tokens!
*/
/**
* @notice Mints a token by deploying the given drawing bytecode
* @param bytecode The bytecode of the drawing to mint a token for.
* This bytecode should have been created by the DBN Compiler, otherwise
* the behavior of this function / the subsequent token is undefined.
*
* Requires passed value of at least the current mint price.
* Will revert if there are no more tokens available or if the current contract
* mode is not yet Open.
*/
function mint(bytes memory bytecode) public payable {
require(_contractMode == ContractMode.Open, "NOT_OPEN");
uint256 tokenId = _tokenIds.current();
require(tokenId <= LAST_TOKEN_ID, 'SOLD_OUT');
_tokenIds.increment();
_mintAtTokenId(bytecode, tokenId);
}
/**
* @notice Mints a token at the specific token ID by deploying the given drawing bytecode.
* Requires passing a ticket id and a signature generated by the contract owner
* granting permission for the caller to mint the specific token ID.
* @param bytecode The bytecode of the drawing to mint a token for
* This bytecode should have been created by the DBN Compiler, otherwise
* the behavior of this function / the subsequent token is undefined.
* @param tokenId The token ID to mint. Needs to be in the range [0, LAST_ALLOWLISTED_TOKEN_ID]
* @param ticketId The ID of the ticket; included as part of the signed data
* @param signature The bytes of the signature that must have been generated
* by the current owner of the contract.
*
* Requires passed value of at least the current mint price.
*/
function mintTokenId(
bytes memory bytecode,
uint256 tokenId,
uint256 ticketId,
bytes memory signature
) public payable onlyWithTicketFor(tokenId, ticketId, signature) {
require(tokenId <= LAST_ALLOWLISTED_TOKEN_ID, 'WRONG_TOKENID_RANGE');
_mintAtTokenId(bytecode, tokenId);
}
/**
* @dev Internal function that does the actual minting for both open and allowlisted mint
* @param bytecode The bytecode of the drawing to mint a token for
* @param tokenId The token ID to mint
*/
function _mintAtTokenId(
bytes memory bytecode,
uint256 tokenId
) internal {
require(msg.value >= _mintPrice, "WRONG_PRICE");
// Deploy the drawing
address addr = Drawing.deploy(bytecode, tokenId);
// Link the token ID to the drawing address
_drawingAddressForTokenId[tokenId] = addr;
// Mint the token (to the sender)
_safeMint(msg.sender, tokenId);
emit DrawingDeployed(tokenId, addr);
}
/**
* @notice Allows gas-less trading on OpenSea by safelisting the ProxyRegistry of the user
* @dev Override isApprovedForAll to check first if current operator is owner's OpenSea proxy
* @inheritdoc ERC721
*/
function isApprovedForAll(
address owner,
address operator
) public view override returns (bool) {
return super.isApprovedForAll(owner, operator) || _isOwnersOpenSeaProxy(owner, operator);
}
/******************************************************************************************
* _______ ____ _ ________ _ _ _____ ______ _____ ______ _____ _____
* |__ __/ __ \| |/ / ____| \ | | | __ \| ____| /\ | __ \| ____| __ \ / ____|
* | | | | | | ' /| |__ | \| | | |__) | |__ / \ | | | | |__ | |__) | (___
* | | | | | | < | __| | . ` | | _ /| __| / /\ \ | | | | __| | _ / \___ \
* | | | |__| | . \| |____| |\ | | | \ \| |____ / ____ \| |__| | |____| | \ \ ____) |
* |_| \____/|_|\_\______|_| \_| |_| \_\______/_/ \_\_____/|______|_| \_\_____/
*
* Functions for reading / querying tokens
*/
/**
* @dev Helper that gets the address for a given token and reverts if it is not present
* @param tokenId the token to get the address of
*/
function _addressForToken(uint256 tokenId) internal view returns (address) {
address addr = _drawingAddressForTokenId[tokenId];
require(addr != address(0), "UNKNOWN_ID");
return addr;
}
/**
* @dev Helper that pulls together the metadata struct for a given token
* @param tokenId the token to get the metadata for
* @param addr the address of its drawing contract
*/
function _getMetadata(uint256 tokenId, address addr) internal view returns (Token.Metadata memory) {
string memory tokenIdAsString = tokenId.toString();
return Token.Metadata(
string(abi.encodePacked("DBNFT #", tokenIdAsString)),
string(Drawing.description(addr)),
string(abi.encodePacked(_baseExternalURI, tokenIdAsString)),
uint256(uint160(addr)).toHexString()
);
}
/**
* @notice The ERC721 tokenURI of the given token as an application/json data URI
* @param tokenId the token to get the tokenURI of
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
address addr = _addressForToken(tokenId);
(, bytes memory bitmapData) = Drawing.render(addr);
Token.Metadata memory metadata = _getMetadata(tokenId, addr);
return Serialize.tokenURI(bitmapData, metadata);
}
/**
* @notice Returns the metadata of the token, without the image data, as a JSON string
* @param tokenId the token to get the metadata of
*/
function tokenMetadata(uint256 tokenId) public view returns (string memory) {
address addr = _addressForToken(tokenId);
Token.Metadata memory metadata = _getMetadata(tokenId, addr);
return Serialize.metadataAsJSON(metadata);
}
/**
* @notice Returns the underlying bytecode of the drawing contract
* @param tokenId the token to get the drawing bytecode of
*/
function tokenCode(uint256 tokenId) public view returns (bytes memory) {
address addr = _addressForToken(tokenId);
return addr.code;
}
/**
* @notice Renders the token and returns an estimate of the gas used and the bitmap data itself
* @param tokenId the token to render
*/
function renderToken(uint256 tokenId) public view returns (uint256, bytes memory) {
address addr = _addressForToken(tokenId);
return Drawing.render(addr);
}
/**
* @notice Returns a list of which tokens in the [0, LAST_ALLOWLISTED_TOKEN_ID]
* have already been minted.
*/
function mintedAllowlistedTokens() public view returns (uint256[] memory) {
uint8 count = 0;
for (uint8 i = 0; i <= LAST_ALLOWLISTED_TOKEN_ID; i++) {
if (_exists(i)) {
count++;
}
}
uint256[] memory result = new uint256[](count);
count = 0;
for (uint8 i = 0; i <= LAST_ALLOWLISTED_TOKEN_ID; i++) {
if (_exists(i)) {
result[count] = i;
count++;
}
}
return result;
}
}
// 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 "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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
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 "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
/**
* @dev Modified copy of OpenZeppelin ERC721 Enumerable.
*
* Changes:
* - gets rid of _removeTokenFromAllTokensEnumeration: no burns (saves space)
* - adds public accessor for the allTokens array
*/
abstract contract DBNERC721Enumerable 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;
/**
* @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), "OWNER_INDEX_OOB");
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 < DBNERC721Enumerable.totalSupply(), "GLOBAL_INDEX_OOB");
return _allTokens[index];
}
/**
* @notice Get a list of all minted tokens.
* @dev No guarantee of order.
*/
function allTokens() public view returns (uint256[] memory) {
return _allTokens;
}
/**
* @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`.
* - `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 != 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 {
_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];
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// Based off of https://gist.github.com/dievardump/483eb43bc6ed30b14f01e01842e3339b/
/// - but removes the _contractURI bits
/// - and makes it abstract
/// @title OpenSea contract helper that defines a few things
/// @author Simon Fremaux (@dievardump)
/// @dev This is a contract used to add OpenSea's
/// gas-less trading and contractURI support
abstract contract OpenSeaTradable {
address private _proxyRegistry;
/// @notice Returns the current OS proxyRegistry address registered
function openSeaProxyRegistry() public view returns (address) {
return _proxyRegistry;
}
/// @notice Helper allowing OpenSea gas-less trading by verifying who's operator
/// for owner
/// @dev Allows to check if `operator` is owner's OpenSea proxy on eth mainnet / rinkeby
/// or to check if operator is OpenSea's proxy contract on Polygon and Mumbai
/// @param owner the owner we check for
/// @param operator the operator (proxy) we check for
function _isOwnersOpenSeaProxy(address owner, address operator) internal virtual view
returns (bool)
{
address proxyRegistry_ = _proxyRegistry;
// if we have a proxy registry
if (proxyRegistry_ != address(0)) {
address ownerProxy = ProxyRegistry(proxyRegistry_).proxies(owner);
return ownerProxy == operator;
}
return false;
}
/// @dev Internal function to set the _proxyRegistry
/// @param proxyRegistryAddress the new proxy registry address
function _setOpenSeaRegistry(address proxyRegistryAddress) internal virtual {
_proxyRegistry = proxyRegistryAddress;
}
}
contract ProxyRegistry {
mapping(address => address) public proxies;
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
/**
* @dev Implements a mixin that uses ECDSA cryptography to restrict token minting to "ticket"-holders.
* This allows off-chain, gasless allowlisting of minting.
*
* A "Ticket" is a logical tuple of:
* - the Token ID
* - the address of a minter
* - the address of the token contract
* - a ticket ID (random number)
*
* By signing this tuple, the owner of the contract can grant permission to a specific address
* to mint a specific token ID at that specific token contract.
*/
abstract contract OwnerSignedTicketRestrictable is Ownable {
// Mapping to enable (very basic) ticket revocation
mapping (uint256 => bool) private _revokedTickets;
/**
* @dev Throws if the given signature, signed by the contract owner, does not grant
* the transaction sender a ticket to mint the given tokenId
* @param tokenId the ID of the token to check
* @param ticketId the ID of the ticket (included in signature)
* @param signature the bytes of the signature to use for verification
*
* This delegates straight into the checkTicket public function.
*/
modifier onlyWithTicketFor(uint256 tokenId, uint256 ticketId, bytes memory signature) {
checkTicket(msg.sender, tokenId, ticketId, signature);
_;
}
/**
* @notice Check the validity of a signature
* @dev Throws if the given signature wasn't signed by the contract owner for the
* "ticket" described by address(this) and the passed parameters
* (or if the ticket ID is revoked)
* @param minter the address of the minter in the ticket
* @param tokenId the token ID of the ticket
* @param ticketId the ticket ID
* @param signature the bytes of the signature
*
* Reuse of a ticket is prevented by existing controls preventing double-minting.
*/
function checkTicket(
address minter,
uint256 tokenId,
uint256 ticketId,
bytes memory signature
) public view {
bytes memory params = abi.encode(
address(this),
minter,
tokenId,
ticketId
);
address addr = ECDSA.recover(
ECDSA.toEthSignedMessageHash(keccak256(params)),
signature
);
require(addr == owner(), "BAD_SIGNATURE");
require(!_revokedTickets[ticketId], "TICKET_REVOKED");
}
/**
* @notice Revokes the given ticket IDs, preventing them from being used in the future
* @param ticketIds the ticket IDs to revoke
* @dev This can do nothing if the ticket ID has already been used, but
* this function gives an escape hatch for accidents, etc.
*/
function revokeTickets(uint256[] calldata ticketIds) public onlyOwner {
for (uint i=0; i<ticketIds.length; i++) {
_revokedTickets[ticketIds[i]] = true;
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./BitmapHeader.sol";
/**
* @dev Internal helper library to encapsulate interactions with a "Drawing" contract
*/
library Drawing {
/**
* @dev Deploys the given bytecode as a drawing contract
* @param bytecode The bytecode to pass to the CREATE opcode
* Must have been generated by the DBN compiler for predictable results.
* @param tokenId The tokenId to inject into the bytecode
* @return the address of the newly created contract
*
* Will also inject the given tokenID into the bytecode before deploy so that
* It is available in the deployed contract's context via a codecopy.
*
* The bytecode passed needs to be _deploy_ bytecode (so end up returning the
* actual bytecode). If any issues occur with the CREATE the transaction
* will fail with an assert (consuming all remaining gas). Detailed reasoning inline.
*/
function deploy(bytes memory bytecode, uint256 tokenId) internal returns (address) {
// First, inject the token id into the bytecode.
// The end of the bytecode is [2 bytes token id][32 bytes ipfs hash]
// (and we get the tokenID in in bigendian)
// This clearly assumes some coordination with the compiler (leaving this space blank!)
bytecode[bytecode.length - 32 - 2] = bytes1(uint8((tokenId & 0xFF00) >> 8));
bytecode[bytecode.length - 32 - 1] = bytes1(uint8(tokenId & 0xFF));
address addr;
assembly {
addr := create(0, add(bytecode, 0x20), mload(bytecode))
}
/*
if addr is zero, a few things could have happened:
a) out-of-gas in the create (which gets forwarded [current*(63/64) - 32000])
b) other exceptional halt (call stack too deep, invalid jump, etc)
c) revert from the create
in a): we should drain all existing gas and effectively bubble up the out of gas.
this makes sure that gas estimators do the right thing
in b): this is a nasty situation, so let's just drain away our gas anyway (true assert)
in c): pretty much same as b) — this is a bug in the passed bytecode, and we should fail.
that said, we _could_ check the μo return buffer for REVERT data, but no need for now.
So no matter what, we want to "assert" the addr is not zero
*/
assert(addr != address(0));
return addr;
}
/**
* @dev Renders the specified drawing contract as a bitmap
* @param addr The address of the drawing contract
* @return an estimation of the gas used and the 10962 bytes of the bitmap
*
* It calls the "0xBD" opcode of the drawing to get just the bitmap pixel data;
* the bitmap header is generated within this calling contract. This is to ensure
* that even if the deployed drawing doesn't conform to the DBN-drawing spec,
* a valid bitmap will always be returned.
*
* To further ensure that a valid bitmap is always returned, if the call
* to the drawing contract reverts, a bitmap will still be returned
* (though with the center pixel set to "55" to facilitate debugging)
*/
function render(address addr) internal view returns (uint256, bytes memory) {
uint bitmapLength = 10962;
uint headerLength = 40 + 14 + 404;
uint pixelDataLength = (10962 - headerLength);
bytes memory result = new bytes(bitmapLength);
bytes memory input = hex"BD";
uint256 startGas = gasleft();
BitmapHeader.writeTo(result);
uint resultOffset = 0x20 + headerLength; // after the header (and 0x20 for the dynamic byte length)
assembly {
let success := staticcall(
gas(),
addr,
add(input, 0x20),
1,
0, // return dst, but we're using the returnbuffer
0 // return length (we're using the returnbuffer)
)
let dataDst := add(result, resultOffset)
switch success
case 1 {
// Render call succeeded!
// copy min(returndataize, pixelDataLength) from the returnbuffer
// in happy path: returndatasize === pixeldatalength
// -> then great, either
// unexpected (too little data): returndatasize < pixeldatalength
// -> then we mustn't copy too much from the buffer! (use returndatasize)
// unexpected (too much data): returndatasize > pixeldatalength
// -> then we mustn't overflow our result! (use pixeldatalength)
let copySize := returndatasize()
if gt(copySize, pixelDataLength) {
copySize := pixelDataLength
}
returndatacopy(
dataDst, // dst offset
0, // src offset
copySize // length
)
}
case 0 {
// Render call failed :/
// Leave a little indicating pixel to hopefully help debugging
mstore8(
add(dataDst, 5250), // location of the center pixel (50 * 104 + 50)
0x55
)
}
}
// this overestimates _some_, but that's fine
uint256 endGas = gasleft();
return ((startGas - endGas), result);
}
/**
* @dev Gets the description stored in the code of a drawing contract
* @param addr The address of the drawing contract
* @return a (possibly empty) string description of the drawing
*
* It calls the "0xDE" opcode of the drawing to get its description.
* If the call fails, it will return an empty string.
*/
function description(address addr) internal view returns (string memory) {
(bool success, bytes memory desc) = addr.staticcall(hex"DE");
if (success) {
return string(desc);
} else {
return "";
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Namespace to encapsulate a "Metadata" struct for a drawing
*/
library Token {
struct Metadata {
string name;
string description;
string externalUrl;
string drawingAddress;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Token.sol";
import "./Base64.sol";
/**
* @dev Internal library encapsulating JSON / Token URI serialization
*/
library Serialize {
/**
* @dev Generates a ERC721 TokenURI for the given data
* @param bitmapData The raw bytes of the drawing's bitmap
* @param metadata The struct holding information about the drawing
* @return a string application/json data URI containing the token information
*
* We do _not_ base64 encode the JSON. This results in a slightly non-compliant
* data URI, because of the commas (and potential non-URL-safe characters).
* Empirically, this is fine: and re-base64-encoding everything would use
* gas and time and is not worth it.
*
* There's also a few ways we could encode the image in the metadata JSON:
* 1. image/bmp data url in the `image` field (base64-encoded given binary data)
* 2. raw svg data in the `image_data` field
* 3. image/svg data url in the `image` field (containing a base64-encoded image, but not itself base64-encoded)
* 4. (3), but with another layer of base64 encoding
* Through some trial and error, (1) does not work with Rarible or OpenSea. The rest do. (4) would be yet another
* layer of base64 (taking time, so is not desirable), (2) uses a potentially non-standard field, so we use (3).
*/
function tokenURI(bytes memory bitmapData, Token.Metadata memory metadata) internal pure returns (string memory) {
string memory imageKey = "image";
bytes memory imageData = _svgDataURI(bitmapData);
string memory fragment = _metadataJSONFragmentWithoutImage(metadata);
return string(abi.encodePacked(
'data:application/json,',
fragment,
// image data :)
'","', imageKey, '":"', imageData, '"}'
));
}
/**
* @dev Returns just the metadata of the image (no bitmap data) as a JSON string
* @param metadata The struct holding information about the drawing
*/
function metadataAsJSON(Token.Metadata memory metadata) internal pure returns (string memory) {
string memory fragment = _metadataJSONFragmentWithoutImage(metadata);
return string(abi.encodePacked(
fragment,
'"}'
));
}
/**
* @dev Returns a partial JSON string with the metadata of the image.
* Used by both the full tokenURI and the plain-metadata serializers.
* @param metadata The struct holding information about the drawing
*/
function _metadataJSONFragmentWithoutImage(Token.Metadata memory metadata) internal pure returns (string memory) {
return string(abi.encodePacked(
// name
'{"name":"',
metadata.name,
// description
'","description":"',
metadata.description,
// external_url
'","external_url":"',
metadata.externalUrl,
// code address
'","drawing_address":"',
metadata.drawingAddress
));
}
/**
* @dev Generates a data URI of an SVG containing an <image> tag containing the given bitmapData
* @param bitmapData The raw bytes of the drawing's bitmap
*/
function _svgDataURI(bytes memory bitmapData) internal pure returns (bytes memory) {
return abi.encodePacked(
"data:image/svg+xml,",
"<svg xmlns='http://www.w3.org/2000/svg' width='303' height='303'><image width='303' height='303' style='image-rendering: pixelated' href='",
"data:image/bmp;base64,",
Base64.encode(bitmapData),
"'/></svg>"
);
}
}
// 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 "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @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
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;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library encapsulating logic to generate the header + palette for a bitmap.
*
* Uses the "40-byte" header format, as described at
* http://www.ece.ualberta.ca/~elliott/ee552/studentAppNotes/2003_w/misc/bmp_file_format/bmp_file_format.htm
*
* Note that certain details (width, height, palette size, file size) are hardcoded
* based off the DBN-specific assumptions of 101x101 with 101 shades of grey.
*
*/
library BitmapHeader {
bytes32 internal constant HEADER1 = 0x424dd22a000000000000ca010000280000006500000065000000010008000000;
bytes22 internal constant HEADER2 = 0x00000000000000000000000000006500000000000000;
/**
* @dev Writes a 458 byte bitmap header + palette to the given array
* @param output The destination array. Gets mutated!
*/
function writeTo(bytes memory output) internal pure {
assembly {
mstore(add(output, 0x20), HEADER1)
mstore(add(output, 0x40), HEADER2)
}
// palette index is "DBN" color : [0, 100]
// map that to [0, 255] via:
// 255 - ((255 * c) / 100)
for (uint i = 0; i < 101; i++) {
bytes1 c = bytes1(uint8(255 - ((255 * i) / 100)));
uint o = i*4 + 54; // after the header
output[o] = c;
output[o + 1] = c;
output[o + 2] = c;
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Helper library for base64-encoding bytes
*/
library Base64 {
uint256 internal constant ALPHA1 = 0x4142434445464748494a4b4c4d4e4f505152535455565758595a616263646566;
uint256 internal constant ALPHA2 = 0x6768696a6b6c6d6e6f707172737475767778797a303132333435363738392b2f;
/**
* @dev Encodes the given bytearray to base64
* @param input The input data
* @return the output data
*/
function encode(bytes memory input) internal pure returns (bytes memory) {
if (input.length == 0) {
return input;
}
bytes memory output = new bytes(_encodedLength(input.length));
uint remaining = input.length;
assembly {
let src := add(input, 0x20)
let dst := add(output, 0x20)
// chunk loop
for {} gt(remaining, 0) {} {
let chunk := shr(16, mload(src))
let processing := 30
let sixtetCounter := 240 // 30 * 8
if lt(remaining, 30) {
processing := remaining
// slide right by 30–#remaining bytes (shl by 3 to get bits)
chunk := shr(shl(3, sub(30, remaining)), chunk)
// but now it needs to be nudge to the left by a few bits,
// to make sure total number of bits is multiple of 6
// 0 mod 3: nudge 0 bits
// 1 mod 3: nudge 4 bits
// 2 mod 3: nudge 2 bits
// we take advantage that this is the same as
// (v * 4) % 6
// this is empirically true, though I don't remember the number theory proving it
let nudgeBits := mulmod(remaining, 4, 6)
chunk := shl(nudgeBits, chunk)
// initial sixtet (remaining * 8 + nudge)
sixtetCounter := add(shl(3, remaining), nudgeBits)
}
remaining := sub(remaining, processing)
src := add(src, processing)
// byte loop
for {} gt(sixtetCounter, 0) {} {
sixtetCounter := sub(sixtetCounter, 6)
let val := shr(sixtetCounter, and(shl(sixtetCounter, 0x3F), chunk))
let alpha := ALPHA1
if gt(val, 0x1F) {
alpha := ALPHA2
val := sub(val, 0x20)
}
let char := byte(val, alpha)
mstore8(dst, char)
dst := add(dst, 1)
}
}
// padding depending on input length % 3
switch mod(mload(input), 3)
case 1 {
// two pads
mstore8(dst, 0x3D) // 0x3d is =
mstore8(add(1, dst), 0x3D) // 0x3d is =
}
case 2 {
// one pad
mstore8(dst, 0x3D)
}
}
return output;
}
/**
* @dev Helper to get the length of the output data
*
* Implements Ceil(inputLength / 3) * 4
*/
function _encodedLength(uint inputLength) internal pure returns (uint) {
return ((inputLength + 2) / 3) * 4;
}
} | Returns a partial JSON string with the metadata of the image. Used by both the full tokenURI and the plain-metadata serializers. metadata The struct holding information about the drawing/ name | function _metadataJSONFragmentWithoutImage(Token.Metadata memory metadata) internal pure returns (string memory) {
return string(abi.encodePacked(
'{"name":"',
metadata.name,
'","description":"',
metadata.description,
'","external_url":"',
metadata.externalUrl,
'","drawing_address":"',
metadata.drawingAddress
));
}
function _svgDataURI(bytes memory bitmapData) internal pure returns (bytes memory) {
return abi.encodePacked(
"data:image/svg+xml,",
"data:image/bmp;base64,",
Base64.encode(bitmapData),
"'/></svg>"
);
}
}
| 13,463,339 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.9.0;
pragma experimental ABIEncoderV2;
import "@chainlink/contracts/src/v0.6/ChainlinkClient.sol";
interface GetCurrencyInfoInterface {
function addCurrency(int256 _currencyQuantity) external;
function getCurrencyName(int256 _id) external view returns (bytes32);
function getCurrencyFullName(int256 _id) external view returns (bytes32);
function getCurrencyOverviewUrl(int256 _id) external view returns (bytes32);
function getCurrencyAssetLaunchDate(int256 _id)
external
view
returns (bytes32);
function getCurrencyLogoUrl(int256 _id) external view returns (bytes32);
function getCurrencyIntro(int256 _id) external view returns (bytes memory);
}
interface GetAnswerInterface {
function strAdd(
string calldata _a,
string calldata _b,
string calldata _c
) external returns (string memory);
function getVolume() external view returns (uint256);
function requestVolumeData(
string calldata _currenyName,
string calldata _questionName,
string calldata _apiUrl
) external returns (bytes32 requestId);
}
interface GetVRFInterface {
function getVRF() external view returns (uint256);
function getRandomNumber() external returns (bytes32 requestId);
}
interface GenerateBadgeInterface {
function issueNFT(string calldata name, address userAddress) external;
}
contract AddGameInfo is ChainlinkClient {
int256 public currencyQuantity;
int256 public dailyGameQuantity;
int256 public weeklyGameQuantity;
int256 public monthlyGameQuantity;
bytes32 public reqID_VRF;
int256 public rand_b;
uint public randomNum=now/10000000;
int256 public totalGameQty;
// Key: gameListId
struct GameList {
int256 questionId; // 2 items
int256 currencyId; // which currency // currencyQuantity items
uint256 revealTime; // gameParticipateStartTime
int256 lifeLengthId; // 3 items
string property; // 1 items
bool isActivity; //
bool isClose; //
int256[] options;
}
struct CurrencyList {
bytes32 name;
bytes32 fullName;
bytes32 overviewUrl;
bytes32 assetLaunchDate;
bytes32 logoUrl;
string currencyIntro;
}
struct QuestionList{
string questionName; //json path
string questionDescription; //question text
}
struct OptionsList {
int256 optionsContet;
int256 userQuantity;
address[] userAddress;
}
struct LifeLengthList {
int256 lifeLength; // daily=1,weekly=7,monthly=30
int256 gameQuantity; // daily=30,weekly=4,monthly=1
string title;
}
struct GameInfo {
int256 gameId;
string gameTitle;
string gameQuestion;
string gameDescription;
uint256 gameParticipateStartTime;
string gameWindow; // Daily, Weekly, Monthly, Lifetime
string gameProperty;
string gameLogoLink;
int256 numOfParticipants;
}
mapping(int256 => CurrencyList) public currencyList; // key: currencyId
mapping(int256 => GameList) public gameList; // key: gameListId
mapping(int256 => GameInfo) public gameInfoList; // return to front-end
mapping(int256 => mapping(int256 => OptionsList)) public optionsList; // key1: gameListId, key2: optionsListId
mapping(int256 => string) public propertyList;
mapping(int256 => LifeLengthList) public lifeLengthList;
mapping(int256 => QuestionList) public questionList;
/*
* Network: Polygon
*/
address GetCurrencyInfoInterfaceAddress = 0x59F08372ab30E64F61AF8594c1163379ACAD27C5;
GetCurrencyInfoInterface getCurrencyInfoContract = GetCurrencyInfoInterface(GetCurrencyInfoInterfaceAddress);
address GetAnswerInterfaceAddress = 0xbE56D8D1d1a529DD83F1188d3B0949A2828F45a5;
GetAnswerInterface getAnswerContract = GetAnswerInterface(GetCurrencyInfoInterfaceAddress);
address GetVRFInterfaceAddress = 0xa7986Fb6438db392b60aaA6Fba3b1B7c5514dD10;
GetVRFInterface getVRFContract = GetVRFInterface(GetVRFInterfaceAddress);
address GenerateBadgeInterfaceAddress = 0x0404E505c13C659b444F3566777901C824C82566;
GenerateBadgeInterface generateBadgeContract = GenerateBadgeInterface(GenerateBadgeInterfaceAddress);
constructor() public {
setChainlinkToken(0x326C977E6efc84E512bB9C30f76E30c160eD06FB);
questionList[1].questionName = "VOLUME";
questionList[1]
.questionDescription = "Guess the first digit before the decimal point (unit digit)for the future price";
questionList[2].questionName = "VOLUME";
questionList[2]
.questionDescription = "Guess the hundreds digit (or hundredths if below $10) of the totol volumne";
questionList[3].questionName = "VOLUME";
questionList[3]
.questionDescription = "Guess the tens digit (or tenths if below $5) of the future price";
questionList[4].questionName = "PRICE";
questionList[4]
.questionDescription = "Guess the hundreds digit (or hundredths if below $10) of the future price";
questionList[5].questionName = "PRICE";
questionList[5]
.questionDescription = "Guess the first digit before the decimal point (unit digit)for the future price";
questionList[6].questionName = "PRICE";
questionList[6]
.questionDescription = "Guess the tens digit (or tenths if below $5) of the future price";
propertyList[1] = "Crypto Currency";
lifeLengthList[1].lifeLength = 1;
lifeLengthList[1].gameQuantity = 10;
lifeLengthList[1].title = "Daily";
lifeLengthList[2].lifeLength = 7;
lifeLengthList[2].gameQuantity = 2;
lifeLengthList[2].title = "Weekly";
lifeLengthList[3].lifeLength = 30;
lifeLengthList[3].gameQuantity = 1;
lifeLengthList[3].title = "Monthly";
currencyQuantity = 10;
}
// 1. Update currency list every monthly. currency list is volume of top 10.
function makeCurrencyList() public{
LinkTokenInterface linkToken = LinkTokenInterface(chainlinkTokenAddress());
require(linkToken.transfer(GetCurrencyInfoInterfaceAddress, linkToken.balanceOf(address(this))), "Unable to transfer");
getCurrencyInfoContract.addCurrency(currencyQuantity);
}
// 2. Get currency information after execute the function of makeCurrencyList
function getCurrencyList() public{
for(int256 i=1;i<=currencyQuantity;i++){
currencyList[i].name = getCurrencyInfoContract.getCurrencyName(i);
currencyList[i].fullName = getCurrencyInfoContract.getCurrencyFullName(i);
currencyList[i].overviewUrl = getCurrencyInfoContract.getCurrencyOverviewUrl(i);
currencyList[i].assetLaunchDate = getCurrencyInfoContract.getCurrencyAssetLaunchDate(i);
currencyList[i].logoUrl = getCurrencyInfoContract.getCurrencyLogoUrl(i);
}
}
function getRandom() public returns (int256) {
LinkTokenInterface linkToken =
LinkTokenInterface(chainlinkTokenAddress());
require(
linkToken.transfer(
GetVRFInterfaceAddress,
linkToken.balanceOf(address(this))
),
"Unable to transfer"
);
reqID_VRF = getVRFContract.getRandomNumber();
randomNum = getVRFContract.getVRF() / 10000000;
return int256(randomNum);
}
// 3.5
function makeOptions(int256 _questionId, int256 _gameId) public{
if(_questionId == 1){
gameList[_gameId].options = [1,2,3,4,5,6,7,8,9,0];
optionsList[_gameId][1].optionsContet = 1;
optionsList[_gameId][2].optionsContet = 2;
optionsList[_gameId][3].optionsContet = 3;
optionsList[_gameId][4].optionsContet = 4;
optionsList[_gameId][5].optionsContet = 5;
optionsList[_gameId][6].optionsContet = 6;
optionsList[_gameId][7].optionsContet = 7;
optionsList[_gameId][8].optionsContet = 8;
optionsList[_gameId][9].optionsContet = 9;
optionsList[_gameId][10].optionsContet = 0;
} else if (_questionId == 2) {
optionsList[_gameId][1].optionsContet = 0;
optionsList[_gameId][2].optionsContet = 1;
optionsList[_gameId][3].optionsContet = 2;
}
}
// 3. make Game information list
int256 currentTotalGameQty;
function makeDailyGame() public {
currentTotalGameQty = 1;
uint8 totalQuestion = 6;
randomNum = now / 10000000;
for (int256 i = 1; i <= 3; i++) {
// i=1 daily,i=2 weekly,i=3 monthly
for (
int256 gameId = 1;
gameId <= lifeLengthList[i].gameQuantity;
gameId++
) {
// gameList for indexes
gameList[currentTotalGameQty].questionId = int256(
((int256(randomNum) * gameId) % totalQuestion) + 1
);
makeOptions(
((int256(randomNum) * gameId) % 2) + 1,
currentTotalGameQty
);
gameList[currentTotalGameQty].currencyId =
((int256(randomNum) * gameId) % currencyQuantity) +
1;
gameList[currentTotalGameQty].revealTime = 0;
gameList[currentTotalGameQty].lifeLengthId = i;
gameList[currentTotalGameQty].property = propertyList[1];
gameList[currentTotalGameQty].isActivity = false;
gameList[currentTotalGameQty].isClose = false;
// gameInfo for details
gameInfoList[currentTotalGameQty].gameId = currentTotalGameQty;
gameInfoList[currentTotalGameQty].gameTitle = bytes32ToString(
currencyList[gameList[currentTotalGameQty].currencyId].name
);
gameInfoList[currentTotalGameQty].gameQuestion = questionList[
gameList[currentTotalGameQty].questionId
]
.questionDescription;
// gameInfoList[currentTotalGameQty].gameDescription = currencyList[gameList[currentTotalGameQty].currencyId].currencyIntro;
gameInfoList[currentTotalGameQty].gameDescription = "";
gameInfoList[currentTotalGameQty]
.gameParticipateStartTime = now;
gameInfoList[currentTotalGameQty].gameWindow = lifeLengthList[
gameList[currentTotalGameQty].lifeLengthId
]
.title;
gameInfoList[currentTotalGameQty].gameProperty = gameList[
currentTotalGameQty
]
.property;
gameInfoList[currentTotalGameQty]
.gameLogoLink = bytes32ToString(
currencyList[gameList[currentTotalGameQty].currencyId]
.logoUrl
);
gameInfoList[currentTotalGameQty].numOfParticipants = 0;
currentTotalGameQty++;
}
}
}
// 4.
function activeGameStatus() public{
gameList[1].isActivity = true;
gameList[1].isClose = true;
gameList[1+lifeLengthList[1].gameQuantity].isActivity = true;
gameList[1+lifeLengthList[1].gameQuantity].isClose = true;
gameList[1+lifeLengthList[1].gameQuantity+lifeLengthList[2].gameQuantity].isActivity = true;
gameList[1+lifeLengthList[1].gameQuantity+lifeLengthList[2].gameQuantity].isClose = true;
}
/*
struct GameInfo{
int256 gameId;
bytes32 gameTitle;
string gameQuestion;
bytes gameDescription;
//int256[][] gameAnsOptions;
//uint gameWindowEndTime;
uint gameParticipateStartTime;
//uint gameParticipateEndTime;
string gameWindow;
string gameProperty;
bytes32 gameLogoLink;
int256 numOfParticipants;
}
*/
int256[] availableGameIds;
function storeAvailableGameIds() public {
delete availableGameIds;
int256 totalGameQty =
lifeLengthList[1].gameQuantity +
lifeLengthList[2].gameQuantity +
lifeLengthList[3].gameQuantity;
for (int256 gameId = totalGameQty; gameId > 0; gameId--) {
if (gameList[gameId].isActivity || gameList[gameId].isClose) {
availableGameIds.push(gameId);
}
}
}
function getAvailableGameIds() public view returns (int256[] memory) {
int256[] memory list = availableGameIds;
return list;
}
function bytes32ToString(bytes32 _bytes32) public 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);
}
function getAnswer(int256 _gameId) public {
string memory url_main;
string memory url_sub;
bytes32 reqID;
string memory currencyName =
bytes32ToString(currencyList[gameList[_gameId].currencyId].name);
url_main = "https://min-api.cryptocompare.com/data/pricemultifull?fsyms=";
url_sub = "&tsyms=USD";
LinkTokenInterface linkToken =
LinkTokenInterface(chainlinkTokenAddress());
require(
linkToken.transfer(
GetAnswerInterfaceAddress,
linkToken.balanceOf(address(this))
),
"Unable to transfer"
);
reqID = getAnswerContract.requestVolumeData(
currencyName,
questionList[gameList[_gameId].questionId].questionName,
getAnswerContract.strAdd(url_main, currencyName, url_sub)
);
}
function returnAnswer() public view returns (uint256) {
//return getAnswerContract.getVolume();
}
function processGameResult(int256 gameId) public {
int preciseAnswer = int(getPreciseAnswer(gameId));
for (uint k = 1; k <= gameList[gameId].options.length; k++) {
address[] memory users = optionsList[gameId][int(k)].userAddress;
if (gameList[gameId].options[uint(k)] == preciseAnswer) {
// daily games issue NFT as reward
if (gameList[gameId].lifeLengthId == 1) {
for (uint i = 1; i <= users.length; i++) {
generateBadgeContract.issueNFT(bytes32ToString(currencyList[gameList[gameId].currencyId].name), users[k]);
}
} else {
for (uint i = 1; i <= users.length; i++) {
// issueCurrency(gameId, users[k], true, gameList[gameId].lifeLengthId);
}
}
} else {
for (uint i = 1; i <= users.length; i++) {
// issueCurrency(gameId, users[k], false, gameList[gameId].lifeLengthId);
}
}
}
}
function getPreciseAnswer(int256 gameId) public returns (uint) {
int256 _qid = gameList[gameId].questionId;
uint answer;
// uint volume = getAnswerContract.getVolume();
uint volume = 12342;
// PRICE uses decimal
if (keccak256(abi.encodePacked(questionList[_qid].questionName)) == keccak256(abi.encodePacked("PRICE"))) {
answer = volume % 10;
} else {
answer = volume % 3;
}
return answer;
}
//
function addParticipant(int256 _gameId, address _userAddress, int256 _optionId) public{
optionsList[_gameId][_optionId].userAddress.push(_userAddress);
optionsList[_gameId][_optionId].userQuantity++;
}
/**
* Withdraw LINK from this contract
*
* DO NOT USE THIS IN PRODUCTION AS IT CAN BE CALLED BY ANY ADDRESS.
* THIS IS PURELY FOR EXAMPLE PURPOSES.
*/
function withdrawLink() external {
LinkTokenInterface linkToken = LinkTokenInterface(chainlinkTokenAddress());
require(linkToken.transfer(msg.sender, linkToken.balanceOf(address(this))), "Unable to transfer");
}
}
| return getAnswerContract.getVolume(); | function returnAnswer() public view returns (uint256) {
}
| 12,721,511 |
./full_match/1/0xE39dEC81B2186A1A2e36bFC260F3Df444b36948A/sources/contracts/DIVAOwnershipMain.sol | Check whether the 7 day minimum staking period has been respected Check that outside of ownership claim submission period | function unstake(address _candidate, uint256 _amount) external override nonReentrant {
uint _minStakingPeriodEnd =
_voterToTimestampLastStakedForCandidate[msg.sender][_candidate] + _MIN_STAKING_PERIOD;
if (block.timestamp < _minStakingPeriodEnd) {
revert MinStakingPeriodNotExpired(block.timestamp, _minStakingPeriodEnd);
}
if (_isWithinSubmitOwnershipClaimPeriod()) {
revert WithinSubmitOwnershipClaimPeriod(block.timestamp, _submitOwnershipClaimPeriodEnd);
}
_candidateToStakedAmount[_candidate] -= _amount;
}
| 16,496,000 |
/**
*Submitted for verification at Etherscan.io on 2021-11-19
*/
pragma solidity 0.8.10;
/**
* @title Multisig
* @author 0age (derived from Christian Lundkvist's Simple Multisig)
* @notice This contract is a multisig based on Christian Lundkvist's Simple
* Multisig (found at https://github.com/christianlundkvist/simple-multisig).
* Any changes in destination, ownership, or signature threshold will require
* deploying a new multisig.
*/
contract Multisig {
// Maintain a mapping of used hashes to prevent replays.
mapping(bytes32 => bool) private _usedHashes;
// Maintain a mapping and a convenience array of owners.
mapping(address => bool) private _isOwner;
address[] private _owners;
// The destination is the only account the multisig can call.
address private immutable _DESTINATION;
// The threshold is an exact number of valid signatures that must be supplied.
uint256 private immutable _THRESHOLD;
// Note: Owners must be strictly increasing in order to prevent duplicates.
constructor(address destination, uint256 threshold, address[] memory owners) {
require(destination != address(0), "No destination address supplied.");
_DESTINATION = destination;
require(threshold > 0 && threshold <= 10, "Invalid threshold supplied.");
_THRESHOLD = threshold;
require(owners.length <= 10, "Cannot have more than 10 owners.");
require(threshold <= owners.length, "Threshold cannot exceed total owners.");
address lastAddress = address(0);
for (uint256 i = 0; i < owners.length; i++) {
require(
owners[i] > lastAddress, "Owner addresses must be strictly increasing."
);
_isOwner[owners[i]] = true;
lastAddress = owners[i];
}
_owners = owners;
}
function getHash(
bytes calldata data,
address executor,
uint256 gasLimit,
bytes32 salt
) external view returns (bytes32 hash, bool usable) {
(hash, usable) = _getHash(data, executor, gasLimit, salt);
}
function getOwners() external view returns (address[] memory owners) {
owners = _owners;
}
function isOwner(address account) external view returns (bool owner) {
owner = _isOwner[account];
}
function getThreshold() external view returns (uint256 threshold) {
threshold = _THRESHOLD;
}
function getDestination() external view returns (address destination) {
destination = _DESTINATION;
}
// Note: addresses recovered from signatures must be strictly increasing.
function execute(
bytes calldata data,
address executor,
uint256 gasLimit,
bytes32 salt,
bytes calldata signatures
) external returns (bool success, bytes memory returnData) {
require(
executor == msg.sender || executor == address(0),
"Must call from the executor account if one is specified."
);
// Derive the message hash and ensure that it has not been used before.
(bytes32 rawHash, bool usable) = _getHash(data, executor, gasLimit, salt);
require(usable, "Hash in question has already been used previously.");
// wrap the derived message hash as an eth signed messsage hash.
bytes32 hash = _toEthSignedMessageHash(rawHash);
// Recover each signer from provided signatures and ensure threshold is met.
address[] memory signers = _recoverGroup(hash, signatures);
require(signers.length == _THRESHOLD, "Total signers must equal threshold.");
// Verify that each signatory is an owner and is strictly increasing.
address lastAddress = address(0); // cannot have address(0) as an owner
for (uint256 i = 0; i < signers.length; i++) {
require(
_isOwner[signers[i]], "Signature does not correspond to an owner."
);
require(
signers[i] > lastAddress, "Signer addresses must be strictly increasing."
);
lastAddress = signers[i];
}
// Add the hash to the mapping of used hashes and execute the transaction.
_usedHashes[rawHash] = true;
(success, returnData) = _DESTINATION.call{gas:gasLimit}(data);
}
function _getHash(
bytes memory data,
address executor,
uint256 gasLimit,
bytes32 salt
) internal view returns (bytes32 hash, bool usable) {
// Prevent replays across different chains.
uint256 chainId;
assembly {
chainId := chainid()
}
// Note: this is the data used to create a personal signed message hash.
hash = keccak256(
abi.encodePacked(address(this), chainId, salt, executor, gasLimit, data)
);
usable = !_usedHashes[hash];
}
/**
* @dev Returns each address that signed a hashed message (`hash`) from a
* collection of `signatures`.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* NOTE: This call _does not revert_ if a signature is invalid, or if the
* signer is otherwise unable to be retrieved. In those scenarios, the zero
* address is returned for that signature.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that recover
* to arbitrary addresses for non-hashed data.
*/
function _recoverGroup(
bytes32 hash,
bytes memory signatures
) internal pure returns (address[] memory signers) {
// Ensure that the signatures length is a multiple of 65.
if (signatures.length % 65 != 0) {
return new address[](0);
}
// Create an appropriately-sized array of addresses for each signer.
signers = new address[](signatures.length / 65);
// Get each signature location and divide into r, s and v variables.
bytes32 signatureLocation;
bytes32 r;
bytes32 s;
uint8 v;
for (uint256 i = 0; i < signers.length; i++) {
assembly {
signatureLocation := add(signatures, mul(i, 65))
r := mload(add(signatureLocation, 32))
s := mload(add(signatureLocation, 64))
v := byte(0, mload(add(signatureLocation, 96)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove
// this possibility and make the signature unique.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
continue;
}
if (v != 27 && v != 28) {
continue;
}
// If signature is valid & not malleable, add signer address.
signers[i] = ecrecover(hash, v, r, s);
}
}
function _toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
} | Prevent replays across different chains. | function _getHash(
bytes memory data,
address executor,
uint256 gasLimit,
bytes32 salt
) internal view returns (bytes32 hash, bool usable) {
uint256 chainId;
assembly {
chainId := chainid()
}
abi.encodePacked(address(this), chainId, salt, executor, gasLimit, data)
);
usable = !_usedHashes[hash];
}
| 1,967,951 |
pragma solidity 0.8.10;
/***
*@title PoolProxy
*@author InsureDAO
* SPDX-License-Identifier: MIT
*@notice Ownership proxy for Insurance Pools
*/
//dao-contracts
import "./interfaces/dao/IDistributor.sol";
//pool-contracts
import "./interfaces/pool/ICDSTemplate.sol";
import "./interfaces/pool/IFactory.sol";
import "./interfaces/pool/IIndexTemplate.sol";
import "./interfaces/pool/IOwnership.sol";
import "./interfaces/pool/IParameters.sol";
import "./interfaces/pool/IPoolTemplate.sol";
import "./interfaces/pool/IPremiumModel.sol";
import "./interfaces/pool/IRegistry.sol";
import "./interfaces/pool/IUniversalMarket.sol";
import "./interfaces/pool/IVault.sol";
//libraries
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
contract PoolProxy is ReentrancyGuard {
using SafeERC20 for IERC20;
event CommitAdmins(
address ownership_admin,
address parameter_admin,
address emergency_admin
);
event ApplyAdmins(
address ownership_admin,
address parameter_admin,
address emergency_admin
);
event CommitDefaultReportingAdmin(address default_reporting_admin);
event AcceptDefaultReportingAdmin(address default_reporting_admin);
event SetReportingAdmin(address pool, address reporter);
event AddDistributor(address distributor);
address public ownership_admin;
address public parameter_admin;
address public emergency_admin;
address public default_reporting_admin; //default reporting module address when arbitrary reporting module is not set.
mapping(address => address) public reporting_admin; //Pool => Payout Decision Maker's address. (ex. ReportingDAO)
address parameters; //pool-contracts Parameters.sol
address public future_ownership_admin;
address public future_parameter_admin;
address public future_emergency_admin;
address public future_default_reporting_admin;
struct Distributor {
string name;
address addr;
}
/***
USDC
id 0 = dev
id 1 = buy back and burn
id 2 = reporting member
*/
mapping(address => mapping(uint256 => Distributor)) public distributors; // token distibutor contracts. token => ID => Distributor / (ex. USDC => 1 => FeeDistributorV1)
mapping(address => uint256) public n_distributors; //token => distrobutor#
mapping(address => mapping(uint256 => uint256)) public distributor_weight; // token => ID => weight
mapping(address => mapping(uint256 => uint256)) public distributable; //distributor => allocated amount
mapping(address => uint256) public total_weights; //token => total allocation point
bool public distributor_kill;
constructor(
address _ownership_admin,
address _parameter_admin,
address _emergency_admin
) {
ownership_admin = _ownership_admin;
parameter_admin = _parameter_admin;
emergency_admin = _emergency_admin;
}
//==================================[Fee Distributor]==================================//
/***
*@notice add new distributor.
*@dev distributor weight is 0 at the moment of addition.
*@param _token address of fee token
*@param _name FeeDistributor name
*@param _addr FeeDistributor address
*/
function add_distributor(
address _token,
string memory _name,
address _addr
) external returns (bool) {
require(msg.sender == ownership_admin, "only ownership admin");
require(_token != address(0), "_token cannot be zero address");
Distributor memory new_distributor = Distributor({
name: _name,
addr: _addr
});
uint256 id = n_distributors[_token];
distributors[_token][id] = new_distributor;
n_distributors[_token] += 1;
return true;
}
/***
*@notice overwrites new distributor to distributor already existed;
*@dev new distributor takes over the old distributor's weight and distributable state;
*/
function _set_distributor(
address _token,
uint256 _id,
Distributor memory _distributor
) internal {
require(_id < n_distributors[_token], "distributor not added yet");
//if Distributor set to ZERO_ADDRESS, set the weight to 0.
if (_distributor.addr == address(0)) {
_set_distributor_weight(_token, _id, 0);
}
distributors[_token][_id] = _distributor;
}
/***
*@notice Set new distributor or name or both.
*@dev id has to be added already.
*@param _token Fee Token address
*@param _id Distributor id
*@param _name Distributor name
*@param _distributor Distributor address
*/
function set_distributor(
address _token,
uint256 _id,
string memory _name,
address _distributor
) external {
require(msg.sender == ownership_admin, "only ownership admin");
Distributor memory new_distributor = Distributor(_name, _distributor);
_set_distributor(_token, _id, new_distributor);
}
/***
*@notice set new weight to a distributor
*@param _token fee token address
*@param _id distributor id
*@param _weight new weight of the distributor
*/
function _set_distributor_weight(
address _token,
uint256 _id,
uint256 _weight
) internal {
require(_id < n_distributors[_token], "distributor not added yet");
require(
distributors[_token][_id].addr != address(0),
"distributor not set"
);
uint256 new_weight = _weight;
uint256 old_weight = distributor_weight[_token][_id];
//update distibutor weight and total_weight
distributor_weight[_token][_id] = new_weight;
total_weights[_token] = total_weights[_token] + new_weight - old_weight;
}
/***
*@notice set new weight to a distributor
*@param _token fee token address
*@param _id distributor id
*@param _weight new weight of the distributor
*/
function set_distributor_weight(
address _token,
uint256 _id,
uint256 _weight
) external returns (bool) {
require(msg.sender == parameter_admin, "only parameter admin");
_set_distributor_weight(_token, _id, _weight);
return true;
}
/***
*@notice set new weights to distributors[20]
*@param _tokens fee token addresses[20]
*@param _ids distributor ids[20]
*@param _weights new weights of the distributors[20]
*@dev [20] 20 is ramdomly decided and has no meaning.
*/
function set_distributor_weight_many(
address[20] memory _tokens,
uint256[20] memory _ids,
uint256[20] memory _weights
) external {
require(msg.sender == parameter_admin, "only parameter admin");
for (uint256 i; i < 20; ) {
if (_tokens[i] == address(0)) {
break;
}
_set_distributor_weight(_tokens[i], _ids[i], _weights[i]);
unchecked {
++i;
}
}
}
/***
*@notice Get Function for distributor's name
*@param _token fee token address
*@param _id distributor id
*/
function get_distributor_name(address _token, uint256 _id)
external
view
returns (string memory)
{
return distributors[_token][_id].name;
}
/***
*@notice Get Function for distributor's address
*@param _token fee token address
*@param _id distributor id
*/
function get_distributor_address(address _token, uint256 _id)
external
view
returns (address)
{
return distributors[_token][_id].addr;
}
//==================================[Fee Distribution]==================================//
/***
*@notice Withdraw admin fees from `_vault`
*@dev any account can execute this function
*@param _token fee token address to withdraw and allocate to the token's distributors
*/
function withdraw_admin_fee(address _token) external nonReentrant {
require(_token != address(0), "_token cannot be zero address");
address _vault = IParameters(parameters).getVault(_token); //dev: revert when parameters not set
uint256 amount = IVault(_vault).withdrawAllAttribution(address(this));
if (amount != 0) {
//allocate the fee to corresponding distributors
uint256 _distributors = n_distributors[_token];
for (uint256 id; id < _distributors; ) {
uint256 aloc_point = distributor_weight[_token][id];
uint256 aloc_amount = (amount * aloc_point) /
total_weights[_token]; //round towards zero.
distributable[_token][id] += aloc_amount; //count up the allocated fee
unchecked {
++id;
}
}
}
}
/***
*@notice Re_allocate _token in this contract with the latest allocation. For token left after rounding down or switched to zero_address
*/
/**
function re_allocate(address _token)external{
//re-allocate the all fee token in this contract with the current allocation.
require(msg.sender == ownership_admin, "Access denied");
uint256 amount = IERC20(_token).balanceOf(address(this));
//allocate the fee to corresponding distributors
for(uint256 id=0; id<n_distributors[_token]; id++){
uint256 aloc_point = distributor_weight[_token][id];
uint256 aloc_amount = amount.mul(aloc_point).div(total_weights[_token]); //round towards zero.
distributable[_token][id] = aloc_amount;
}
}
*/
/***
*@notice distribute accrued `_token` via a preset distributor
*@param _token fee token to be distributed
*@param _id distributor id
*/
function _distribute(address _token, uint256 _id) internal {
require(_id < n_distributors[_token], "distributor not added yet");
address _addr = distributors[_token][_id].addr;
uint256 amount = distributable[_token][_id];
distributable[_token][_id] = 0;
IERC20(_token).safeApprove(_addr, amount);
require(
IDistributor(_addr).distribute(_token),
"dev: should implement distribute()"
);
}
/***
*@notice distribute accrued `_token` via a preset distributor
*@dev Only callable by an EOA to prevent
*@param _token fee token to be distributed
*@param _id distributor id
*/
function distribute(address _token, uint256 _id) external nonReentrant {
require(tx.origin == msg.sender); //only EOA
require(!distributor_kill, "distributor is killed");
_distribute(_token, _id);
}
/***
*@notice distribute accrued admin fees from multiple coins
*@dev Only callable by an EOA to prevent flashloan exploits
*@param _id List of distributor id
*/
function distribute_many(
address[20] memory _tokens,
uint256[20] memory _ids
) external nonReentrant {
//any EOA
require(tx.origin == msg.sender);
require(!distributor_kill, "distribution killed");
for (uint256 i; i < 20; ) {
if (_tokens[i] == address(0)) {
break;
}
_distribute(_tokens[i], _ids[i]);
unchecked {
++i;
}
}
}
/***
@notice Kill or unkill `distribute` functionality
@param _is_killed Distributor kill status
*/
function set_distributor_kill(bool _is_killed) external {
require(
msg.sender == emergency_admin || msg.sender == ownership_admin,
"Access denied"
);
distributor_kill = _is_killed;
}
//==================================[Configuration]==================================//
// admins
function commit_set_admins(
address _o_admin,
address _p_admin,
address _e_admin
) external {
/***
*@notice Set ownership admin to `_o_admin`, parameter admin to `_p_admin` and emergency admin to `_e_admin`
*@param _o_admin Ownership admin
*@param _p_admin Parameter admin
*@param _e_admin Emergency admin
*/
require(msg.sender == ownership_admin, "Access denied");
future_ownership_admin = _o_admin;
future_parameter_admin = _p_admin;
future_emergency_admin = _e_admin;
emit CommitAdmins(_o_admin, _p_admin, _e_admin);
}
/***
*@notice Accept the effects of `commit_set_admins`
*/
function accept_set_admins() external {
require(msg.sender == future_ownership_admin, "Access denied");
ownership_admin = future_ownership_admin;
parameter_admin = future_parameter_admin;
emergency_admin = future_emergency_admin;
emit ApplyAdmins(ownership_admin, parameter_admin, emergency_admin);
}
//==================================[Reporting Module]==================================//
/***
*@notice Set reporting admin to `_r_admin`
*@param _pool Target address
*@param _r_admin Reporting admin
*/
function commit_set_default_reporting_admin(address _r_admin) external {
require(msg.sender == ownership_admin, "Access denied");
future_default_reporting_admin = _r_admin;
emit CommitDefaultReportingAdmin(future_default_reporting_admin);
}
/***
*@notice Accept the effects of `commit_set_default_reporting_admin`
*/
function accept_set_default_reporting_admin() external {
require(msg.sender == future_default_reporting_admin, "Access denied");
default_reporting_admin = future_default_reporting_admin;
emit AcceptDefaultReportingAdmin(default_reporting_admin);
}
/***
*@notice set arbitrary reporting module for specific _pool.
*@notice "ownership_admin" or "default_reporting_admin" can execute this function.
*/
function set_reporting_admin(address _pool, address _reporter)
external
returns (bool)
{
require(
address(msg.sender) == ownership_admin ||
address(msg.sender) == default_reporting_admin,
"Access denied"
);
reporting_admin[_pool] = _reporter;
emit SetReportingAdmin(_pool, _reporter);
return true;
}
/***
*@notice get reporting module set for the _pool. If none is set, default_reporting_admin will be returned.
*@dev public function
*/
function get_reporter(address _pool) public view returns (address) {
address reporter = reporting_admin[_pool] != address(0)
? reporting_admin[_pool]
: default_reporting_admin;
return reporter;
}
//==================================[Pool Contracts]==================================//
/***
* pool-contracts' owner is this contract.
* For the detail of each function, see the pool-contracts repository.
*/
//ownership
function ownership_accept_transfer_ownership(address _ownership_contract)
external
{
require(msg.sender == ownership_admin, "Access denied");
IOwnership(_ownership_contract).acceptTransferOwnership();
}
function ownership_commit_transfer_ownership(
address _ownership_contract,
address newOwner
) external {
require(msg.sender == ownership_admin, "Access denied");
IOwnership(_ownership_contract).commitTransferOwnership(newOwner);
}
//Factory
function factory_approve_template(
address _factory,
address _template_addr,
bool _approval,
bool _isOpen,
bool _duplicate
) external {
require(msg.sender == ownership_admin, "Access denied");
IUniversalMarket _template = IUniversalMarket(_template_addr);
IFactory(_factory).approveTemplate(
_template,
_approval,
_isOpen,
_duplicate
);
}
function factory_approve_reference(
address _factory,
address _template_addr,
uint256 _slot,
address _target,
bool _approval
) external {
require(msg.sender == ownership_admin, "Access denied");
IUniversalMarket _template = IUniversalMarket(_template_addr);
IFactory(_factory).approveReference(
_template,
_slot,
_target,
_approval
);
}
function factory_set_condition(
address _factory,
address _template_addr,
uint256 _slot,
uint256 _target
) external {
require(msg.sender == ownership_admin, "Access denied");
IUniversalMarket _template = IUniversalMarket(_template_addr);
IFactory(_factory).setCondition(_template, _slot, _target);
}
function factory_create_market(
address _factory,
address _template_addr,
string memory _metaData,
uint256[] memory _conditions,
address[] memory _references
) external returns (address) {
require(msg.sender == ownership_admin, "Access denied");
IUniversalMarket _template = IUniversalMarket(_template_addr);
address _market = IFactory(_factory).createMarket(
_template,
_metaData,
_conditions,
_references
);
return _market;
}
//Premium model
function pm_set_premium(
address _premium,
uint256 _multiplierPerYear,
uint256 _initialBaseRatePerYear,
uint256 _finalBaseRatePerYear,
uint256 _goalTVL
) external {
require(msg.sender == parameter_admin, "Access denied");
IPremiumModel(_premium).setPremiumParameters(
_multiplierPerYear,
_initialBaseRatePerYear,
_finalBaseRatePerYear,
_goalTVL
);
}
//Universal(Pool/Index/CDS)
function pm_set_paused(address _pool, bool _state) external nonReentrant {
require(
msg.sender == emergency_admin || msg.sender == ownership_admin,
"Access denied"
);
IUniversalMarket(_pool).setPaused(_state);
}
function pm_change_metadata(address _pool, string calldata _metadata)
external
{
require(msg.sender == parameter_admin, "Access denied");
IUniversalMarket(_pool).changeMetadata(_metadata);
}
//Pool
function pool_apply_cover(
address _pool,
uint256 _pending,
uint256 _payoutNumerator,
uint256 _payoutDenominator,
uint256 _incidentTimestamp,
bytes32 _merkleRoot,
string calldata _rawdata,
string calldata _memo
) external {
require(
msg.sender == default_reporting_admin ||
msg.sender == reporting_admin[_pool],
"Access denied"
);
IPoolTemplate(_pool).applyCover(
_pending,
_payoutNumerator,
_payoutDenominator,
_incidentTimestamp,
_merkleRoot,
_rawdata,
_memo
);
}
function pool_apply_bounty(
address _pool,
uint256 _amount,
address _contributor,
uint256[] calldata _ids
) external {
require(
msg.sender == default_reporting_admin ||
msg.sender == reporting_admin[_pool],
"Access denied"
);
IPoolTemplate(_pool).applyBounty(_amount, _contributor, _ids);
}
//Index
function index_set_leverage(address _index, uint256 _target) external {
require(msg.sender == parameter_admin, "Access denied");
IIndexTemplate(_index).setLeverage(_target);
}
function index_set(
address _index_address,
uint256 _indexA,
uint256 _indexB,
address _pool,
uint256 _allocPoint
) external {
require(msg.sender == parameter_admin, "Access denied");
IIndexTemplate(_index_address).set(
_indexA,
_indexB,
_pool,
_allocPoint
);
}
//CDS
function defund(
address _cds,
address _to,
uint256 _amount
) external {
require(msg.sender == ownership_admin, "Access denied");
ICDSTemplate(_cds).defund(_to, _amount);
}
//Vault
function vault_withdraw_redundant(
address _vault,
address _token,
address _to
) external {
require(msg.sender == ownership_admin, "Access denied");
IVault(_vault).withdrawRedundant(_token, _to);
}
function vault_set_keeper(address _vault, address _keeper) external {
require(msg.sender == ownership_admin, "Access denied");
IVault(_vault).setKeeper(_keeper);
}
function vault_set_controller(address _vault, address _controller)
external
{
require(msg.sender == ownership_admin, "Access denied");
IVault(_vault).setController(_controller);
}
//Parameters
function set_parameters(address _parameters) external {
/***
* @notice set parameter contract
*/
require(msg.sender == ownership_admin, "Access denied");
parameters = _parameters;
}
function parameters_set_vault(
address _parameters,
address _token,
address _vault
) external {
require(msg.sender == ownership_admin, "Access denied");
IParameters(_parameters).setVault(_token, _vault);
}
function parameters_set_lockup(
address _parameters,
address _address,
uint256 _target
) external {
require(msg.sender == parameter_admin, "Access denied");
IParameters(_parameters).setLockup(_address, _target);
}
function parameters_set_grace(
address _parameters,
address _address,
uint256 _target
) external {
require(msg.sender == parameter_admin, "Access denied");
IParameters(_parameters).setGrace(_address, _target);
}
function parameters_set_mindate(
address _parameters,
address _address,
uint256 _target
) external {
require(msg.sender == parameter_admin, "Access denied");
IParameters(_parameters).setMinDate(_address, _target);
}
function parameters_set_upper_slack(
address _parameters,
address _address,
uint256 _target
) external {
require(msg.sender == parameter_admin, "Access denied");
IParameters(_parameters).setUpperSlack(_address, _target);
}
function parameters_set_lower_slack(
address _parameters,
address _address,
uint256 _target
) external {
require(msg.sender == parameter_admin, "Access denied");
IParameters(_parameters).setLowerSlack(_address, _target);
}
function parameters_set_withdrawable(
address _parameters,
address _address,
uint256 _target
) external {
require(msg.sender == parameter_admin, "Access denied");
IParameters(_parameters).setWithdrawable(_address, _target);
}
function parameters_set_premium_model(
address _parameters,
address _address,
address _target
) external {
require(msg.sender == parameter_admin, "Access denied");
IParameters(_parameters).setPremiumModel(_address, _target);
}
function setFeeRate(
address _parameters,
address _address,
uint256 _target
) external {
require(msg.sender == parameter_admin, "Access denied");
IParameters(_parameters).setFeeRate(_address, _target);
}
function parameters_set_max_list(
address _parameters,
address _address,
uint256 _target
) external {
require(msg.sender == parameter_admin, "Access denied");
IParameters(_parameters).setMaxList(_address, _target);
}
function parameters_set_condition_parameters(
address _parameters,
bytes32 _reference,
bytes32 _target
) external {
require(msg.sender == parameter_admin, "Access denied");
IParameters(_parameters).setCondition(_reference, _target);
}
//Registry
function registry_set_factory(address _registry, address _factory)
external
{
require(msg.sender == ownership_admin, "Access denied");
IRegistry(_registry).setFactory(_factory);
}
function registry_support_market(address _registry, address _market)
external
{
require(msg.sender == ownership_admin, "Access denied");
IRegistry(_registry).supportMarket(_market);
}
function registry_set_existence(
address _registry,
address _template,
address _target
) external {
require(msg.sender == ownership_admin, "Access denied");
IRegistry(_registry).setExistence(_template, _target);
}
function registry_set_cds(
address _registry,
address _address,
address _target
) external {
require(msg.sender == ownership_admin, "Access denied");
IRegistry(_registry).setCDS(_address, _target);
}
}
| distribute accrued admin fees from multiple coins Only callable by an EOA to prevent flashloan exploits _id List of distributor id/any EOA | function distribute_many(
address[20] memory _tokens,
uint256[20] memory _ids
) external nonReentrant {
require(tx.origin == msg.sender);
require(!distributor_kill, "distribution killed");
for (uint256 i; i < 20; ) {
if (_tokens[i] == address(0)) {
break;
}
_distribute(_tokens[i], _ids[i]);
unchecked {
++i;
}
}
}
| 1,821,962 |
pragma solidity 0.5.11;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/access/Roles.sol";
interface IFC
{
event Transfer(address indexed from, address indexed to, uint256 value);
event Lock(address indexed account, uint256 value);
event Write(address indexed account, uint256 CPool, uint256 PPool, uint256 PPoolLocked);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function stateOf(address account) external view returns (uint256, uint256, uint256);
function circulationRatio() external view returns (uint256);
function setTotalSupply(uint256 total) external;
function setStateOf(address account, uint256 ConfluxPool, uint256 PersonalPool, uint256 PersonalLocked) external;
function setCirculationRatio(uint256 value) external;
function transfer(address recipient, uint256 value) external returns (bool);
function send(address recipient, uint256 value, bytes calldata data) external returns (bool);
function mint(address account, uint256 value) external returns (bool);
function burn(uint256 value) external;
}
contract FCRoles {
using Roles for Roles.Role;
Roles.Role private _minters;
Roles.Role private _pausers;
Roles.Role private _admins;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
event AdminAdded(address indexed account);
event AdminRemoved(address indexed account);
//---------- Admin Begin ---------//
constructor () internal {
_addAdmin(msg.sender);
}
modifier onlyAdmin() {
require(isAdmin(msg.sender), "AdminRole: caller does not have the Admin role");
_;
}
function onlyAdminMock() public view onlyAdmin {
// solhint-disable-previous-line no-empty-blocks
}
function isAdmin(address account) public view returns (bool) {
return _admins.has(account);
}
function addAdmin(address account) public onlyAdmin {
_addAdmin(account);
}
function renounceAdmin() public {
_removeAdmin(msg.sender);
}
function _addAdmin(address account) internal {
_admins.add(account);
emit AdminAdded(account);
}
function _removeAdmin(address account) internal {
_admins.remove(account);
emit AdminRemoved(account);
}
//---------- Admin End ---------//
//---------- Minter Begin ---------//
modifier onlyMinter() {
require(isMinter(msg.sender) || isAdmin(msg.sender), "MinterRole: caller does not have the Minter role or above");
_;
}
function onlyMinterMock() public view onlyMinter {
// solhint-disable-previous-line no-empty-blocks
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyAdmin {
_addMinter(account);
}
function removeMinter(address account) public onlyAdmin {
_removeMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
//---------- Minter End ---------//
//---------- Pauser Begin ---------//
modifier onlyPauser() {
require(isPauser(msg.sender) || isAdmin(msg.sender), "PauserRole: caller does not have the Pauser role or above");
_;
}
function onlyPauserMock() public view onlyPauser {
// solhint-disable-previous-line no-empty-blocks
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyAdmin {
_addPauser(account);
}
function removePauser(address account) public onlyAdmin {
_removePauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
//---------- Pauser End ---------//
}
contract FCPausable is FCRoles {
event TransferPaused(address account);
event TransferUnpaused(address account);
event BurnPaused(address account);
event BurnUnpaused(address account);
event MigratePaused(address account);
event MigrateUnpaused(address account);
bool private _transferPaused;
bool private _burnPaused;
bool private _migratePaused;
constructor () internal
{
_transferPaused = false;
_burnPaused = true;
_migratePaused = true;
}
// IsPaused
function isTransferPaused() public view returns (bool) {
return _transferPaused;
}
function isBurnPaused() public view returns (bool) {
return _burnPaused;
}
function isMigratePaused() public view returns (bool) {
return _migratePaused;
}
// WhenNotPaused
modifier whenTransferNotPaused() {
require(!_transferPaused, "Pausable: Transfer paused");
_;
}
modifier whenBurnNotPaused() {
require(!_burnPaused, "Pausable: Burn paused");
_;
}
modifier whenMigrateNotPaused() {
require(!_migratePaused, "Pausable: Migrate paused");
_;
}
// WhenPaused
modifier whenTransferPaused() {
require(_transferPaused, "Pausable: Transfer not paused");
_;
}
modifier whenBurnPaused() {
require(_burnPaused, "Pausable: Burn not paused");
_;
}
modifier whenMigratePaused() {
require(_migratePaused, "Pausable: Migrate not paused");
_;
}
// Pause
function pauseTransfer() internal {
_transferPaused = true;
emit TransferPaused(msg.sender);
}
function pauseBurn() internal {
_burnPaused = true;
emit BurnPaused(msg.sender);
}
function pauseMigrate() internal {
_migratePaused = true;
emit MigratePaused(msg.sender);
}
// Unpause
function unpauseTransfer() internal {
_transferPaused = false;
emit TransferUnpaused(msg.sender);
}
function unpauseBurn() internal {
_burnPaused = false;
emit BurnUnpaused(msg.sender);
}
function unpauseMigrate() internal {
_migratePaused = false;
emit MigrateUnpaused(msg.sender);
}
// Before Migration
function pauseBeforeMigration() public onlyPauser {
pauseTransfer();
pauseBurn();
pauseMigrate();
}
// During Migration
function pauseDuringMigration() public onlyPauser {
pauseTransfer();
pauseBurn();
unpauseMigrate();
}
// After Initialization
function pauseAfterInitialization() public onlyPauser {
unpauseTransfer();
pauseBurn();
pauseMigrate();
}
// For Exchange
function pauseForExchange() public onlyPauser {
pauseTransfer();
unpauseBurn();
pauseMigrate();
}
}
contract SponsorWhitelistControl {
// ------------------------------------------------------------------------
// Someone will sponsor the gas cost for contract `contract_addr` with an
// `upper_bound` for a single transaction.
// ------------------------------------------------------------------------
function set_sponsor_for_gas(address contract_addr, uint upper_bound) public payable {
}
// ------------------------------------------------------------------------
// Someone will sponsor the storage collateral for contract `contract_addr`.
// ------------------------------------------------------------------------
function set_sponsor_for_collateral(address contract_addr) public payable {
}
// ------------------------------------------------------------------------
// Add commission privilege for address `user` to some contract.
// ------------------------------------------------------------------------
function add_privilege(address[] memory) public {
}
// ------------------------------------------------------------------------
// Remove commission privilege for address `user` from some contract.
// ------------------------------------------------------------------------
function remove_privilege(address[] memory) public {
}
}
contract FC is IFC, FCPausable
{
using SafeMath for uint256;
using Address for address;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _cap;
uint256 private _totalSupply;
uint256 private _circulationRatio; // For r units of FC, lock 100 FC
mapping (address => uint256) private _confluxBalances; // Conflux Pool
mapping (address => uint256) private _personalBalances; // Personal Pool
mapping (address => uint256) private _personalLockedBalances; // Personal Locked Pool
mapping (address => bool) private _accountCheck;
address[] private _accountList;
IERC1820Registry constant private ERC1820_REGISTRY = IERC1820Registry(address(0x866aCA87FF33a0ae05D2164B3D999A804F583222));
// keccak256("ERC777TokensRecipient")
bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
SponsorWhitelistControl constant public SPONSOR = SponsorWhitelistControl(address(0x0888000000000000000000000000000000000001));
constructor()
FCPausable()
public
{
_name = "FansCoin";
_symbol = "FC";
_decimals = 18;
_circulationRatio = 0;
uint256 fc_cap = 100000000;
_cap = fc_cap.mul(10 ** uint256(_decimals));
// register interfaces
ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));
// register all users as sponsees
address[] memory users = new address[](1);
users[0] = address(0);
SPONSOR.add_privilege(users);
}
// Fallback
function deposit() public onlyAdmin payable {
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function cap() public view returns (uint256) {
return _cap;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _confluxBalances[account].add(_personalBalances[account]).add(_personalLockedBalances[account]);
}
function circulationRatio() public view returns (uint256) {
return _circulationRatio;
}
function stateOf(address account) public view returns (uint256, uint256, uint256) {
return (_confluxBalances[account], _personalBalances[account], _personalLockedBalances[account]);
}
function balanceOfContract() public view returns (uint256) {
return address(this).balance;
}
//---------------- Data Migration ----------------------
function accountTotal() public view returns (uint256) {
return _accountList.length;
}
function accountList(uint256 begin) public view returns (address[100] memory) {
require(begin >= 0 && begin < _accountList.length, "FC: accountList out of range");
address[100] memory res;
uint256 range = _min(_accountList.length, begin.add(100));
for (uint256 i = begin; i < range; i++) {
res[i-begin] = _accountList[i];
}
return res;
}
function setStateOf(address account, uint256 ConfluxPool, uint256 Personal, uint256 Locked) public onlyPauser whenMigrateNotPaused {
require(account != address(0), "FC: Migration to the zero address");
if (!_accountCheck[account]) {
_accountCheck[account] = true;
_accountList.push(account);
}
_confluxBalances[account] = ConfluxPool;
_personalBalances[account] = Personal;
_personalLockedBalances[account] = Locked;
emit Write(account, ConfluxPool, Personal, Locked);
}
function setTotalSupply(uint256 total) public onlyPauser whenMigrateNotPaused {
_totalSupply = total;
}
//---------------- End Data Migration ----------------------
function setCirculationRatio(uint256 value) public onlyAdmin {
_circulationRatio = value;
}
function mint(address account, uint256 value) public onlyMinter returns (bool) {
if (!_accountCheck[account]) {
_accountCheck[account] = true;
_accountList.push(account);
}
_mint(account, value);
_callTokensReceived(msg.sender, address(0), account, value, "", "", true);
return true;
}
function transfer(address recipient, uint256 value) public whenTransferNotPaused returns (bool) {
bool success = _transfer(msg.sender, recipient, value);
_callTokensReceived(msg.sender, msg.sender, recipient, value, "", "", false);
return success;
}
function send(address recipient, uint256 value, bytes memory data) public whenTransferNotPaused returns (bool) {
bool success = _transfer(msg.sender, recipient, value);
_callTokensReceived(msg.sender, msg.sender, recipient, value, data, "", true);
return success;
}
function _transfer(address sender, address recipient, uint256 value) internal returns (bool) {
require(recipient != address(0), "FC: transfer to the zero address");
if (!_accountCheck[recipient]) {
_accountCheck[recipient] = true;
_accountList.push(recipient);
}
if (_circulationRatio != 0) {
// If the given amount is greater than
// the unlocked balance of the sender, revert
_confluxBalances[sender].add(_personalBalances[sender].mul(_circulationRatio).div(_circulationRatio.add(100))).sub(value);
} else {
_confluxBalances[sender].add(_personalBalances[sender]).sub(value);
}
// Favor Conflux Pool due to the lack of circulation restriction
if (value <= _confluxBalances[sender]) {
_transferC2P(sender, recipient, value);
} else {
_transferP2P(sender, recipient, value.sub(_confluxBalances[sender]));
_transferC2P(sender, recipient, _confluxBalances[sender]);
}
emit Transfer(sender, recipient, value);
return true;
}
function burn(uint256 value) public whenBurnNotPaused {
require(msg.sender != address(0), "FC: burn from the zero address");
// If the given amount is greater than the balance of the sender, revert
_confluxBalances[msg.sender].add(_personalBalances[msg.sender]).add(_personalLockedBalances[msg.sender]).sub(value);
if (address(this).balance < value) {
value = address(this).balance;
}
// Personal Locked Pool > Personal Pool > Conflux Pool
_burnCPool(msg.sender, value > _personalBalances[msg.sender].add(_personalLockedBalances[msg.sender]) ?
_min(value.sub(_personalLockedBalances[msg.sender]).sub(_personalBalances[msg.sender]), _confluxBalances[msg.sender]) : 0);
_burnPPool(msg.sender, value > _personalLockedBalances[msg.sender] ?
_min(value.sub(_personalLockedBalances[msg.sender]), _personalBalances[msg.sender]): 0);
_burnPPoolLocked(msg.sender, _min(value, _personalLockedBalances[msg.sender]));
// Transfer CFX to the burn request sender
msg.sender.transfer(value);
emit Transfer(msg.sender, address(0), value);
}
//---------- Helper Begin ----------//
function _mint(address account, uint256 value) internal {
require(account != address(0), "FC: mint to the zero address");
require(totalSupply().add(value) <= _cap, "FC: cap exceeded");
_totalSupply = _totalSupply.add(value);
_confluxBalances[account] = _confluxBalances[account].add(value);
emit Transfer(address(0), account, value);
}
function _transferC2P(address sender, address recipient, uint256 value) internal {
require(sender != address(0), "FC: transfer from the zero address");
require(recipient != address(0), "FC: transfer to the zero address");
_confluxBalances[sender] = _confluxBalances[sender].sub(value);
_personalBalances[recipient] = _personalBalances[recipient].add(value);
}
function _transferP2P(address sender, address recipient, uint256 value) internal {
require(sender != address(0), "FC: transfer from the zero address");
require(recipient != address(0), "FC: transfer to the zero address");
uint256 lockedAmount = _circulationRatio == 0 ? 0 : _max(value.mul(100).div(_circulationRatio), 1);
// Spend: -(value + value * 100 / r)
_personalBalances[sender] = _personalBalances[sender].sub(value.add(lockedAmount));
// Lock: + value * 100 / r, at least 1
_personalLockedBalances[sender] = _personalLockedBalances[sender].add(lockedAmount);
// Transfer: +value
_personalBalances[recipient] = _personalBalances[recipient].add(value);
emit Lock(sender, lockedAmount);
}
function _burnPPoolLocked(address account, uint256 value) internal {
require(account != address(0), "FC: burn from the zero address");
_personalLockedBalances[account] = _personalLockedBalances[account].sub(value);
_totalSupply = _totalSupply.sub(value);
}
function _burnPPool(address account, uint256 value) internal {
require(account != address(0), "FC: burn from the zero address");
_personalBalances[account] = _personalBalances[account].sub(value);
_totalSupply = _totalSupply.sub(value);
}
function _burnCPool(address account, uint256 value) internal {
require(account != address(0), "FC: burn from the zero address");
_confluxBalances[account] = _confluxBalances[account].sub(value);
_totalSupply = _totalSupply.sub(value);
}
function _min(uint256 value1, uint256 value2) internal pure returns (uint256) {
if (value1 > value2) {
return value2;
}
return value1;
}
function _max(uint256 value1, uint256 value2) internal pure returns (uint256) {
if (value1 < value2) {
return value2;
}
return value1;
}
//---------- Helper End ------------//
//---------- Token Received Begin ----------//
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
private
{
address implementer = ERC1820_REGISTRY.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
} else if (requireReceptionAck) {
require(!to.isContract(), "FC: token recipient contract has no implementer for ERC777TokensRecipient");
}
}
//---------- Token Received End ----------//
}
| solhint-disable-previous-line no-empty-blocks | function onlyPauserMock() public view onlyPauser {
}
| 1,008,862 |
./full_match/4/0x4051F88D4f17B7E7F03F1a1E6C0180355b58D0Bb/sources/browser/GangMemberFactory.sol | Must be sent from the owner proxy or owner.Gang bundle full gang | function mint(uint256 _optionId, address _toAddress) public override {
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
assert(
address(proxyRegistry.proxies(owner())) == msg.sender ||
owner() == msg.sender
);
GangMember member = GangMember(nftAddress);
if((_optionId + 1) % 7 == 0){
uint startId = _optionId - 6;
for(uint i = startId; i < _optionId; i++){
member.mintWithTokenType(_toAddress, i + 100);
}
}
{
member.mintWithTokenType(_toAddress, _optionId + 100);
}
}
| 12,308,109 |
pragma solidity ^0.4.24;
contract KAICompany {
// Company name and address of who did BD
bytes32 public name;
address public initiator;
// link back to the address of CEngine
address public contractInitiated;
// mapping of addresses to booleans that holds true if a user is on IC, HOD or on bd team
mapping(address => bool) public onProject;
// Conviction list for the company
mapping(address => uint256) public convictionList;
uint256 public totalConviction; // total cumulative amount
// Negative Conviction List for the company
mapping(address => uint256) public nconvictionList;
uint256 public totalnConviction; // total cumulative amount
// BD team
mapping(address => bool) public teamCheck;
address[] public teamList;
uint256 public teamListLength;
// HOD address
address public HOD;
bool public isHODSet;
// IC team
mapping(address => bool) public icteamCheck;
address[] public icteamList;
uint256 public icteamListLength;
// Investment stages
enum States { ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EXIT, HOLD }
States public state;
bool public onHold;
// HOLD state (holds previous state when company goes on hold)
States public heldState;
// project ID
uint256 public id;
// modifier to make functions only accessible to owners
modifier onlyOwner() {
if (msg.sender != contractInitiated) {
revert("Function was not called by owner.");
}
_; // continue executing rest of method body
}
// Constructor and variable init + assignment
constructor(uint256 _amount, bytes32 _name, address _from, uint256 _id, uint256 _rank) public {
contractInitiated = msg.sender;
initiator = _from;
name = _name;
convictionList[_from] = _amount;
totalConviction = _amount;
state = States.ZERO;
id = _id;
// Add user to the project
onProject[_from] = true;
// Add user to the team
teamCheck[_from] = true;
teamList.push(_from);
teamListLength += 1;
}
// addTeam adds a team member (uses map to check whether a member is on the team or not) given (address of sender: _adder, address of addee: _addee)
function addTeam(address _adder, address _addee) public onlyOwner {
require(teamCheck[_adder], "You must be on the team to add people to the team.");
onProject[_addee] = true;
// User Management
teamCheck[_addee] = true;
teamList.push(_addee);
teamListLength += 1;
}
// addConviction adds conviction amount with possible state restrictions given (address of sender: _from, token amount: _amount)
function addConviction(address _from, uint256 _amount) public onlyOwner {
if(teamCheck[_from] && (uint(state) == 0 || uint(state) == 1 || uint(state) == 4 || uint(state) == 6)){
convictionList[_from] += _amount;
totalConviction += _amount;
}else if(_from == HOD && uint(state) == 2){
convictionList[_from] += _amount;
totalConviction += _amount;
}else if (icteamCheck[_from] && uint(state) == 3){
convictionList[_from] += _amount;
totalConviction += _amount;
}else{
revert("undefined rule");
}
}
// addnConviction adds negative conviction amount with possible state restrictions given (address of sender: _from, token amount: _amount)
function addnConviction(address _from, uint256 _amount) public onlyOwner {
if(teamCheck[_from] && (uint(state) == 0 || uint(state) == 1 || uint(state) == 4 || uint(state) == 6)){
convictionList[_from] += _amount;
totalConviction += _amount;
}else if(_from == HOD && uint(state) == 2){
convictionList[_from] += _amount;
totalConviction += _amount;
}else if (icteamCheck[_from] && uint(state) == 3){
convictionList[_from] += _amount;
totalConviction += _amount;
}else{
revert("undefined rule");
}
}
// setHOD sets HOD status to an address for the project given (address of sender: _from, address of hod: _hod)
function setHOD(address _from, address _hod) public onlyOwner{
require(!isHODSet && onProject[_from], "HOD already set");
onProject[_hod] = true;
HOD = _hod;
isHODSet = true;
}
// unhold unholds a project from the hold state given (address of sender: _from)
function unhold(address _from) public onlyOwner {
require(onProject[_from] && state == States.HOLD, "not on team");
onHold = false;
state = States(uint(heldState));
}
// hold holds a project from an investment state given (address of sender: _from)
function hold(address _from) public onlyOwner {
require(onProject[_from] && state != States.HOLD, "must be on team");
onHold = true;
heldState = state;
state = States.HOLD;
}
// nextStage progresses the stage given state restrictions (address of sender: _from)
function nextStage(address _from) public onlyOwner{
require(uint(state) < uint(States.EXIT), "Company already at exit state.");
require(convictionList[_from] - nconvictionList[_from] > 0, "Moving the stage requires atleast one coin.");
if(teamCheck[_from] && (uint(state) == 0 || uint(state) == 1 || uint(state) == 4 || uint(state) == 7)){
state = States(uint(state) + 1);
}else if(_from == HOD && uint(state) == 2) {
state = States(uint(state) + 1);
}else if(icteamCheck[_from] && uint(state) == 3) {
state = States(uint(state) + 1);
}else{
revert("undefined rule");
}
}
}
| hold holds a project from an investment state given (address of sender: _from) | function hold(address _from) public onlyOwner {
require(onProject[_from] && state != States.HOLD, "must be on team");
onHold = true;
heldState = state;
state = States.HOLD;
}
| 12,557,854 |
pragma solidity ^0.5.0;
// Safe math
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
//not a SafeMath function
function max(uint a, uint b) private pure returns (uint) {
return a > b ? a : b;
}
}
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// Owned contract
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
/// @title A test contract to store and exchange Dai, Ether, and test INCH tokens.
/// @author Decentralized
/// @notice Use the 4 withdrawel and deposit functions in your this contract to short and long ETH. ETH/Dai price is
/// pegged at 300 to 1. INCH burn rate is 1% per deposit
/// Because there is no UI for this contract, KEEP IN MIND THAT ALL VALUES ARE IN MINIMUM DENOMINATIONS
/// IN OTHER WORDS ALL TOKENS UNCLUDING ETHER ARE DISPLAYED AND INPUT AS 10^-18 * THE BASE UNIT OF CURRENCY
/// Other warnings: This is a test contract. Do not risk any significant value. You are not guaranteed a
/// refund, even if it's my fault. Do not send any tokens or assets directly to the contract.
/// DO NOT SEND ANY TOKENS OR ASSETS DIRECTLY TO THE CONTRACT. Use only the withdrawel and deposit functions
/// @dev Addresses and 'deployership' must be initialized before use. INCH must be deposited in contract
/// Ownership will be set to 0x0 after initialization
contract VaultPOC is Owned {
using SafeMath for uint;
uint public constant initialSupply = 1000000000000000000000;
uint public constant etherPeg = 300;
uint8 public constant burnRate = 1;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
ERC20Interface inchWormContract;
ERC20Interface daiContract;
address deployer; //retains ability to transfer mistaken ERC20s after ownership is revoked
//____________________________________________________________________________________
// Inititialization functions
/// @notice Sets the address for the INCH and Dai tokens, as well as the deployer
function initialize(address _inchwormAddress, address _daiAddress) external onlyOwner {
inchWormContract = ERC20Interface(_inchwormAddress);
daiContract = ERC20Interface(_daiAddress);
deployer = owner;
}
//____________________________________________________________________________________
//____________________________________________________________________________________
// Deposit and withdrawel functions
/* @notice Make a deposit by including payment in function call
Wei deposited will be rewarded with INCH tokens. Exchange rate changes over time
Call will fail with insufficient Wei balance from sender or INCH balance in vault
ALL TOKENS UNCLUDING ETHER ARE DISPLAYED AND INPUT AS 10^-18 * THE BASE UNIT OF CURRENCY
@dev Function will fail if totalSupply < 0.01 * initialSupply.To be fixed
Exchange rate is 1 Wei : 300 * totalSupply/initialSupply *10**-18
*/
function depositWeiForInch() external payable {
uint _percentOfInchRemaining = inchWormContract.totalSupply().mul(100).div(initialSupply);
uint _tokensToWithdraw = msg.value.mul(etherPeg);
_tokensToWithdraw = _tokensToWithdraw.mul(_percentOfInchRemaining).div(100);
inchWormContract.transfer(msg.sender, _tokensToWithdraw);
}
/* @param Dai to deposit in contract, denomination 1*10**-18 Dai
@notice Dai deposited will be rewarded with INCH tokens. Exchange rate changes over time
Call will fail with insufficient Dai balance from sender or INCH balance in vault
ALL TOKENS UNCLUDING ETHER ARE DISPLAYED AND INPUT AS 10^-18 * THE BASE UNIT OF CURRENCY
@dev Exchange rate is 1*10**-18 Dai : totalSupply/initialSupply
*/
function depositDaiForInch(uint _daiToDeposit) external {
uint _percentOfInchRemaining = inchWormContract.totalSupply().mul(100).div(initialSupply);
uint _tokensToWithdraw = _daiToDeposit.mul(_percentOfInchRemaining).div(100);
inchWormContract.transfer(msg.sender, _tokensToWithdraw);
daiContract.transferFrom(msg.sender, address(this), _daiToDeposit);
}
/* @param Wei to withdraw from contract
@notice INCH must be deposited in exchange for the withdrawel. Exchange rate changes over time
Call will fail with insufficient INCH balance from sender or insufficient Wei balance in the vault
1% of INCH deposited is burned
ALL TOKENS UNCLUDING ETHER ARE DISPLAYED AND INPUT AS 10^-18 * THE BASE UNIT OF CURRENCY
@dev Exchange rate is 1 Wei : 300 * totalSupply/initialSupply *10**-18
*/
function withdrawWei(uint _weiToWithdraw) external {
uint _inchToDeposit = _weiToWithdraw.mul(etherPeg).mul((initialSupply.div(inchWormContract.totalSupply())));
inchWormContract.transferFrom(msg.sender, address(this), _inchToDeposit);
uint _inchToBurn = _inchToDeposit.mul(burnRate).div(100);
inchWormContract.transfer(address(0), _inchToBurn);
msg.sender.transfer(1 wei * _weiToWithdraw);
}
/* @param Dai to withdraw from contract, denomination 1*10**-18 Dai
@notice INCH must be deposited in exchange for the withdrawel. Exchange rate changes over time
Call will fail with insufficient INCH balance from sender or insufficient Dai balance in the vault
1% of INCH deposited is burned
ALL TOKENS UNCLUDING ETHER ARE DISPLAYED AND INPUT AS 10^-18 * THE BASE UNIT OF CURRENCY
@dev Exchange rate is 1*10**-18 Dai : totalSupply/initialSupply
*/
function withdrawDai(uint _daiToWithdraw) external {
uint _inchToDeposit = _daiToWithdraw.mul(initialSupply.div(inchWormContract.totalSupply()));
inchWormContract.transferFrom(msg.sender, address(this), _inchToDeposit);
uint _inchToBurn = _inchToDeposit.mul(burnRate).div(100);
inchWormContract.transfer(address(0), _inchToBurn);
daiContract.transfer(msg.sender, _daiToWithdraw);
}
//____________________________________________________________________________________
//____________________________________________________________________________________
// view functions
/// @notice Returns the number of INCH recieved per Dai,
/// ALL TOKENS UNCLUDING ETHER ARE DISPLAYED AS 10^-18 * THE BASE UNIT OF CURRENCY
function getInchDaiRate() public view returns(uint) {
return initialSupply.div(inchWormContract.totalSupply());
}
/// @notice Returns the number of INCH recieved per Eth
/// ALL TOKENS UNCLUDING ETHER ARE DISPLAYED AS 10^-18 * THE BASE UNIT OF CURRENCY
function getInchEthRate() public view returns(uint) {
etherPeg.mul((initialSupply.div(inchWormContract.totalSupply())));
}
/// @notice Returns the Wei balance of the vault contract
/// ALL TOKENS UNCLUDING ETHER ARE DISPLAYED AS 10^-18 * THE BASE UNIT OF CURRENCY
function getEthBalance() public view returns(uint) {
return address(this).balance;
}
/// @notice Returns the INCH balance of the vault contract
/// ALL TOKENS UNCLUDING ETHER ARE DISPLAYED AS 10^-18 * THE BASE UNIT OF CURRENCY
function getInchBalance() public view returns(uint) {
return inchWormContract.balanceOf(address(this));
}
/// @notice Returns the Dai balance of the vault contract
/// ALL TOKENS UNCLUDING ETHER ARE DISPLAYED AS 10^-18 * THE BASE UNIT OF CURRENCY
function getDaiBalance() public view returns(uint) {
return daiContract.balanceOf(address(this));
}
/// @notice Returns the percent of INCH that has not been burned (sent to 0X0)
/// @dev Implicitly floors the result
/// INCH sent to burn addresses other than 0x0 are not currently included in calculation
function getPercentOfInchRemaining() external view returns(uint) {
return inchWormContract.totalSupply().mul(100).div(initialSupply);
}
//____________________________________________________________________________________
//____________________________________________________________________________________
// emergency and fallback functions
/// @notice original deployer can transfer out tokens other than Dai and INCH
function transferAccidentalERC20Tokens(address tokenAddress, uint tokens) external returns (bool success) {
require(msg.sender == deployer);
require(tokenAddress != address(inchWormContract));
require(tokenAddress != address(daiContract));
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
// fallback function
function () external payable {
revert();
}
//____________________________________________________________________________________
} | Returns the INCH balance of the vault contract ALL TOKENS UNCLUDING ETHER ARE DISPLAYED AS 10^-18 THE BASE UNIT OF CURRENCY | function getInchBalance() public view returns(uint) {
return inchWormContract.balanceOf(address(this));
}
| 893,040 |
pragma solidity ^0.5.0;
import "./GhostOwnership.sol";
contract AuctionBase {
// @notice The ERC-165 interface signature for ERC-721.
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9f40b779);
ERC721 public nonFungibleContract;
constructor (address _nftAddress) public {
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
nonFungibleContract = candidateContract;
}
struct Auction {
// creator who this auction create.
address payable seller;
// current the most bid person and price (in wei) that this person bidding.
address payable winner;
uint256 maxPrice;
//uint256 sumPrice;
// Duration (in seconds) of auction
uint64 duration;
// Time when auction started
uint64 startedAt;
}
// TODO: setting minimum auctioneer and bid price
//uint16 constant minAuctioneer = 0;
//uint128 constant minPrice = 0;
// mapping from token ID(ghost ID) to Auction.
mapping (uint256 => Auction) public tokenIdToAuction;
// mapping from token ID(ghost ID) to bidders and amounts.
// allocate one more mapping to calculate the number of bidders who participating in auction.
mapping (uint256 => mapping (address => uint256)) tokenIdToBidderAndAmount;
mapping (uint256 => address[]) tokenIdToBidders;
event AuctionCreated(uint256 gene, uint256 duration, uint256 auctionType);
event AuctionSuccessful(uint256 gene, uint256 maxPrice, address payable winner);
event AuctionCancelled(uint256 gene);
event BidderCreated(uint256 gene, address payable bidder, uint256 newAmount);
event BidAmountUpdated(uint256 gene, address payable bidder, uint256 newAmount);
// @notice Returns true if given address owns the token.
function _owns(address _owner, uint256 _tokenId) internal view returns (bool) {
return nonFungibleContract.ownerOf(_tokenId) == _owner;
}
// @notice Escrows the NFT, assigning ownership to this contract.
// @param _owner - Current owner address of token to escrow.
// @param _tokenId - ID of token whose approval to verify.
function _escrow(address _owner, uint256 _tokenId) internal {
nonFungibleContract.transferFrom(_owner, address(this), _tokenId);
}
// @notice Transfers an NFT owned by this contract to another address.
function _transfer(address _to, uint256 _tokenId) internal {
nonFungibleContract.transfer(_to, _tokenId);
}
// @notice Adds an auction to the list of auctions.
// @param _tokenId - Ghost ID to put on auction.
function _addAuction(uint256 _tokenId, Auction memory _auction, uint256 _auctionType) internal {
tokenIdToAuction[_tokenId] = _auction;
uint256 gene = nonFungibleContract.getGene(_tokenId);
emit AuctionCreated(gene, uint256(_auction.duration), _auctionType);
}
// @notice removes an auction from the list of auctions.
// @param _tokenId - auctioned Ghost ID.
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
uint256 idx;
for (idx = 0; idx < tokenIdToBidders[_tokenId].length; idx++) {
delete tokenIdToBidderAndAmount[_tokenId][tokenIdToBidders[_tokenId][idx]];
}
delete tokenIdToBidders[_tokenId];
}
// @notice cancel ongoing auction.
// @param _tokenId - Ghost ID in auction to cancel.
function _cancelAuction(uint256 _tokenId) internal {
_transfer(tokenIdToAuction[_tokenId].seller, _tokenId);
_removeAuction(_tokenId);
uint256 gene = nonFungibleContract.getGene(_tokenId);
emit AuctionCancelled(gene);
}
// @notice check if auction is ongoing.
function _isOnAuction(uint256 _tokenId) internal view returns (bool) {
Auction storage auction = tokenIdToAuction[_tokenId];
return auction.startedAt > 0;
}
// @notice bidder who have not participated participates in the ongoing auction.
// @param _tokenId - auctioned Ghost ID.
// @dev when bidder has not yet bid
function _addBidder(uint256 _tokenId, address payable _bidder, uint256 _bidAmount) internal {
require(tokenIdToBidderAndAmount[_tokenId][_bidder] == uint256(0));
Auction storage auction = tokenIdToAuction[_tokenId];
require(auction.maxPrice < _bidAmount);
tokenIdToBidderAndAmount[_tokenId][_bidder] = _bidAmount;
tokenIdToBidders[_tokenId].push(_bidder);
auction.winner = _bidder;
auction.maxPrice = _bidAmount;
uint256 gene = nonFungibleContract.getGene(_tokenId);
emit BidderCreated(gene, _bidder, _bidAmount);
}
// @notice amount of bidder who have participated updates.
// @param _tokenId - auctioned Ghost ID.
// @dev when bidder has been bid
function _updateBidAmount(uint256 _tokenId, address payable _bidder, uint256 _bidAmount) internal {
require(tokenIdToBidderAndAmount[_tokenId][_bidder] != uint256(0));
Auction storage auction = tokenIdToAuction[_tokenId];
require(auction.maxPrice < _bidAmount);
require(auction.winner != _bidder);
tokenIdToBidderAndAmount[_tokenId][_bidder] = _bidAmount;
//auction.sumPrice += _bidAmount;
auction.winner = _bidder;
auction.maxPrice = _bidAmount;
uint256 gene = nonFungibleContract.getGene(_tokenId);
emit BidAmountUpdated(gene, _bidder, _bidAmount);
}
// @notice check if the auction is finished by checking startedAt and duration of auction.
function _isFinished(uint256 _tokenId) internal view returns (bool) {
uint256 passedSeconds = 0;
if (now > tokenIdToAuction[_tokenId].startedAt) {
passedSeconds = now - tokenIdToAuction[_tokenId].startedAt;
}
if (passedSeconds >= tokenIdToAuction[_tokenId].duration){
return true;
}
return false;
}
// @notice bids on special auction.
// @dev Auction should be ongoing.
function _bid(uint256 _tokenId, address payable _bidder, uint256 _bidAmount) internal {
require(_isOnAuction(_tokenId));
require(!_isFinished(_tokenId));
//require(tokenIdToBidders[_tokenId].length >= minAuctioneer);
require(_bidAmount > 0);
if (tokenIdToBidderAndAmount[_tokenId][_bidder] == 0) {
_addBidder(_tokenId, _bidder, _bidAmount);
} else {
_updateBidAmount(_tokenId, _bidder, _bidAmount);
}
}
// @notice Finish auction.
function _endAuction(uint256 _tokenId) internal {
require(_isFinished(_tokenId));
Auction storage auction = tokenIdToAuction[_tokenId];
if (auction.winner != address(0)) {
_transfer(auction.winner, _tokenId);
uint256 gene = nonFungibleContract.getGene(_tokenId);
emit AuctionSuccessful(gene, uint256(auction.maxPrice), auction.winner);
_removeAuction(_tokenId);
} else {
_cancelAuction(_tokenId);
}
}
}
| cancel ongoing auction. _tokenId - Ghost ID in auction to cancel. | function _cancelAuction(uint256 _tokenId) internal {
_transfer(tokenIdToAuction[_tokenId].seller, _tokenId);
_removeAuction(_tokenId);
uint256 gene = nonFungibleContract.getGene(_tokenId);
emit AuctionCancelled(gene);
}
| 1,780,925 |
/**
* @authors: [@hbarcelos]
* @reviewers: []
* @auditors: []
* @bounties: []
* @deployments: []
*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.7.6;
import "@kleros/erc-792/contracts/erc-1497/IEvidence.sol";
import "./dependencies/IAMB.sol";
import "./CrossChainBinaryArbitration.sol";
contract HomeBinaryArbitrationProxy is IHomeBinaryArbitrationProxy {
/**
* State chart for AribtrableItem status.
* (I) Means the initial state.
* (F) Means a final state.
* [condition] Means a guard condition.
*
* Receive Request +----------+
* +-------------------->+ Rejected |
* | [Rejected] +-----+----+
* | |
* | |
* | | Relay Rejected
* +-(I)--+ |
* | None +<----------------------+
* +--+---+ |
* | |
* | | Receive Dispute Failed
* | |
* | Receive Request +-----+----+ +--(F)--+
* +-------------------->+ Accepted +-------------------->+ Ruled |
* [Accepted] +----------+ Receive Ruling +-------+
*/
enum Status {None, Rejected, Accepted, Ruled}
struct ArbitrableItem {
Status status;
address arbitrator;
uint256 arbitratorDisputeID;
uint256 ruling;
}
/// @dev Maps an arbitrable contract and and arbitrable item ID to a status
mapping(ICrossChainArbitrable => mapping(uint256 => ArbitrableItem)) public arbitrableItems;
/// @dev The contract governor. TRUSTED.
address public governor = msg.sender;
/// @dev ArbitraryMessageBridge contract address. TRUSTED.
IAMB public amb;
/// @dev Address of the counter-party proxy on the Foreign Chain. TRUSTED.
address public foreignProxy;
/// @dev The chain ID where the foreign proxy is deployed.
uint256 public foreignChainId;
modifier onlyGovernor() {
require(msg.sender == governor, "Only governor allowed");
_;
}
modifier onlyForeignProxy() {
require(msg.sender == address(amb), "Only AMB allowed");
require(amb.messageSourceChainId() == bytes32(foreignChainId), "Only foreign chain allowed");
require(amb.messageSender() == foreignProxy, "Only foreign proxy allowed");
_;
}
modifier onlyIfInitialized() {
require(foreignProxy != address(0), "Not initialized yet");
_;
}
/**
* @notice Creates an arbitration proxy on the foreign chain. @dev The contract will still require initialization before being usable. @param _amb ArbitraryMessageBridge contract address.
*/
constructor(IAMB _amb) {
amb = _amb;
}
/**
* @notice Sets the address of a new governor.
* @param _governor The address of the new governor.
*/
function changeGovernor(address _governor) external onlyGovernor {
governor = _governor;
}
/**
* @notice Sets the address of the ArbitraryMessageBridge.
* @param _amb The address of the new ArbitraryMessageBridge.
*/
function changeAmb(IAMB _amb) external onlyGovernor {
amb = _amb;
}
/**
* @notice Sets the address of the arbitration proxy on the Foreign Chain.
* @param _foreignProxy The address of the proxy.
* @param _foreignChainId The ID of the chain where the foreign proxy is deployed.
*/
function setForeignProxy(address _foreignProxy, uint256 _foreignChainId) external onlyGovernor {
require(foreignProxy == address(0), "Foreign proxy already set");
foreignProxy = _foreignProxy;
foreignChainId = _foreignChainId;
}
/**
* @notice Registers the meta evidence at the arbitrable item level.
* @dev Should be called only by the arbitrable contract.
* @param _arbitrableItemID The ID of the arbitrable item on the arbitrable contract.
* @param _metaEvidence The MetaEvicence related to the arbitrable item.
*/
function registerMetaEvidence(uint256 _arbitrableItemID, string calldata _metaEvidence)
external
override
onlyIfInitialized
{
emit MetaEvidenceRegistered(ICrossChainArbitrable(msg.sender), _arbitrableItemID, _metaEvidence);
bytes4 methodSelector = IForeignBinaryArbitrationProxy(0).receiveMetaEvidence.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, msg.sender, _arbitrableItemID, _metaEvidence);
amb.requireToPassMessage(foreignProxy, data, amb.maxGasPerTx());
}
/**
* @notice Registers the arbitrator extra data at the arbitrable item level.
* @dev Should be called only by the arbitrable contract.
* @param _arbitrableItemID The ID of the arbitrable item on the arbitrable contract.
* @param _arbitratorExtraData The extra data for the arbitrator.
*/
function registerArbitratorExtraData(uint256 _arbitrableItemID, bytes calldata _arbitratorExtraData)
external
override
onlyIfInitialized
{
emit ArbitratorExtraDataRegistered(ICrossChainArbitrable(msg.sender), _arbitrableItemID, _arbitratorExtraData);
bytes4 methodSelector = IForeignBinaryArbitrationProxy(0).receiveArbitratorExtraData.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, msg.sender, _arbitrableItemID, _arbitratorExtraData);
amb.requireToPassMessage(foreignProxy, data, amb.maxGasPerTx());
}
/**
* @notice Receives a dispute request for an arbitrable item from the Foreign Chain.
* @dev Should only be called by the xDAI/ETH bridge.
* @param _arbitrable The address of the arbitrable contract. UNTRUSTED.
* @param _arbitrableItemID The ID of the arbitrable item on the arbitrable contract.
* @param _plaintiff The address of the dispute creator.
*/
function receiveDisputeRequest(
ICrossChainArbitrable _arbitrable,
uint256 _arbitrableItemID,
address _plaintiff
) external override onlyForeignProxy {
ArbitrableItem storage arbitrableItem = arbitrableItems[_arbitrable][_arbitrableItemID];
require(arbitrableItem.status == Status.None, "Dispute request already exists");
try _arbitrable.notifyDisputeRequest(_arbitrableItemID, _plaintiff) {
arbitrableItem.status = Status.Accepted;
emit DisputeAccepted(_arbitrable, _arbitrableItemID);
} catch (bytes memory reason) {
arbitrableItem.status = Status.Rejected;
emit DisputeRejected(_arbitrable, _arbitrableItemID);
}
}
/**
* @notice Relays to the Foreign Chain that a dispute has been accepted.
* @dev This will likely be called by an external 3rd-party (i.e.: a bot),
* since currently there cannot be a bi-directional cross-chain message.
* @param _arbitrable The address of the arbitrable contract. UNTRUSTED.
* @param _arbitrableItemID The ID of the arbitrable item on the arbitrable contract.
*/
function relayDisputeAccepted(ICrossChainArbitrable _arbitrable, uint256 _arbitrableItemID) external override {
ArbitrableItem storage arbitrableItem = arbitrableItems[_arbitrable][_arbitrableItemID];
require(arbitrableItem.status == Status.Accepted, "Dispute is not accepted");
bytes4 methodSelector = IForeignBinaryArbitrationProxy(0).receiveDisputeAccepted.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, address(_arbitrable), _arbitrableItemID);
amb.requireToPassMessage(foreignProxy, data, amb.maxGasPerTx());
}
/**
* @notice Relays to the Foreign Chain that a dispute has been rejected.
* This can happen either because the deadline has passed during the cross-chain
* message to notify of the dispute request being in course or if the arbitrable
* contract changed the state for the item and made it non-disputable.
* @dev This will likely be called by an external 3rd-party (i.e.: a bot),
* since currently there cannot be a bi-directional cross-chain message.
* @param _arbitrable The address of the arbitrable contract. UNTRUSTED.
* @param _arbitrableItemID The ID of the arbitrable item on the arbitrable contract.
*/
function relayDisputeRejected(ICrossChainArbitrable _arbitrable, uint256 _arbitrableItemID) external override {
ArbitrableItem storage arbitrableItem = arbitrableItems[_arbitrable][_arbitrableItemID];
require(arbitrableItem.status == Status.Rejected, "Dispute is not rejected");
delete arbitrableItems[_arbitrable][_arbitrableItemID].status;
bytes4 methodSelector = IForeignBinaryArbitrationProxy(0).receiveDisputeRejected.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, address(_arbitrable), _arbitrableItemID);
amb.requireToPassMessage(foreignProxy, data, amb.maxGasPerTx());
}
/**
* @notice Receives the dispute created on the Foreign Chain.
* @dev Should only be called by the xDAI/ETH bridge.
* @param _arbitrable The address of the arbitrable contract. UNTRUSTED.
* @param _arbitrableItemID The ID of the arbitrable item on the arbitrable contract.
* @param _arbitrator The address of the arbitrator in the home chain.
* @param _arbitratorDisputeID The dispute ID.
*/
function receiveDisputeCreated(
ICrossChainArbitrable _arbitrable,
uint256 _arbitrableItemID,
address _arbitrator,
uint256 _arbitratorDisputeID
) external override onlyForeignProxy {
ArbitrableItem storage arbitrableItem = arbitrableItems[_arbitrable][_arbitrableItemID];
require(arbitrableItem.status == Status.Accepted, "Dispute is not accepted");
arbitrableItem.arbitrator = _arbitrator;
arbitrableItem.arbitratorDisputeID = _arbitratorDisputeID;
emit DisputeCreated(_arbitrable, _arbitrableItemID, _arbitratorDisputeID);
}
/**
* @notice Receives the failed dispute creation on the Foreign Chain.
* @dev Should only be called by the xDAI/ETH bridge.
* @param _arbitrable The address of the arbitrable contract. UNTRUSTED.
* @param _arbitrableItemID The ID of the arbitrable item on the arbitrable contract.
*/
function receiveDisputeFailed(ICrossChainArbitrable _arbitrable, uint256 _arbitrableItemID)
external
override
onlyForeignProxy
{
ArbitrableItem storage arbitrableItem = arbitrableItems[_arbitrable][_arbitrableItemID];
require(arbitrableItem.status == Status.Accepted, "Dispute is not accepted");
delete arbitrableItems[_arbitrable][_arbitrableItemID].status;
_arbitrable.cancelDispute(_arbitrableItemID);
emit DisputeFailed(_arbitrable, _arbitrableItemID);
}
/**
* @notice Receives the ruling for a dispute from the Foreign Chain.
* @dev Should only be called by the xDAI/ETH bridge.
* @param _arbitrable The address of the arbitrable contract. UNTRUSTED.
* @param _arbitrableItemID The ID of the arbitrable item on the arbitrable contract.
* @param _ruling The ruling given by the arbitrator.
*/
function receiveRuling(
ICrossChainArbitrable _arbitrable,
uint256 _arbitrableItemID,
uint256 _ruling
) external override onlyForeignProxy {
ArbitrableItem storage arbitrableItem = arbitrableItems[_arbitrable][_arbitrableItemID];
// Allow receiving ruling if the dispute was accepted but not created.
// This can happen if the defendant fails to fund her side in time.
require(arbitrableItem.status == Status.Accepted, "Dispute cannot be ruled");
arbitrableItem.status = Status.Ruled;
arbitrableItem.ruling = _ruling;
_arbitrable.rule(_arbitrableItemID, _ruling);
emit DisputeRuled(_arbitrable, _arbitrableItemID, _ruling);
}
}
| Registers the meta evidence at the arbitrable item level. Should be called only by the arbitrable contract. _arbitrableItemID The ID of the arbitrable item on the arbitrable contract. _metaEvidence The MetaEvicence related to the arbitrable item./ | function registerMetaEvidence(uint256 _arbitrableItemID, string calldata _metaEvidence)
external
override
onlyIfInitialized
{
emit MetaEvidenceRegistered(ICrossChainArbitrable(msg.sender), _arbitrableItemID, _metaEvidence);
bytes4 methodSelector = IForeignBinaryArbitrationProxy(0).receiveMetaEvidence.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, msg.sender, _arbitrableItemID, _metaEvidence);
amb.requireToPassMessage(foreignProxy, data, amb.maxGasPerTx());
}
| 5,371,275 |
/**
*Submitted for verification at Etherscan.io on 2021-08-11
*/
// File: iface/IERC20.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface 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);
/**
* @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: ParassetERC20.sol
pragma solidity ^0.8.4;
/*
* @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;
}
}
contract ParassetERC20 is Context, IERC20 {
mapping(address => uint256) _balances;
mapping(address => mapping(address => uint256)) _allowances;
uint256 _totalSupply;
string _name;
string _symbol;
constructor() { }
/**
* @dev Returns the name of the token.
*/
function name() public view 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");
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);
}
/**
* @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);
}
}
// File: iface/IParassetGovernance.sol
pragma solidity ^0.8.4;
/// @dev This interface defines the governance methods
interface IParassetGovernance {
/// @dev Set governance authority
/// @param addr Destination address
/// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not
/// implemented in the current system, only the difference between authorized and unauthorized.
/// Here, a uint96 is used to represent the weight, which is only reserved for expansion
function setGovernance(address addr, uint flag) external;
/// @dev Get governance rights
/// @param addr Destination address
/// @return Weight. 0 means to delete the governance permission of the target address. Weight is not
/// implemented in the current system, only the difference between authorized and unauthorized.
/// Here, a uint96 is used to represent the weight, which is only reserved for expansion
function getGovernance(address addr) external view returns (uint);
/// @dev Check whether the target address has governance rights for the given target
/// @param addr Destination address
/// @param flag Permission weight. The permission of the target address must be greater than this weight to pass the check
/// @return True indicates permission
function checkGovernance(address addr, uint flag) external view returns (bool);
}
// File: ParassetBase.sol
pragma solidity ^0.8.4;
contract ParassetBase {
// Lock flag
uint256 _locked;
/// @dev To support open-zeppelin/upgrades
/// @param governance IParassetGovernance implementation contract address
function initialize(address governance) public virtual {
require(_governance == address(0), "Log:ParassetBase!initialize");
_governance = governance;
_locked = 0;
}
/// @dev IParassetGovernance implementation contract address
address public _governance;
/// @dev Rewritten in the implementation contract, for load other contract addresses. Call
/// super.update(newGovernance) when overriding, and override method without onlyGovernance
/// @param newGovernance IParassetGovernance implementation contract address
function update(address newGovernance) public virtual {
address governance = _governance;
require(governance == msg.sender || IParassetGovernance(governance).checkGovernance(msg.sender, 0), "Log:ParassetBase:!gov");
_governance = newGovernance;
}
/// @dev Uniform accuracy
/// @param inputToken Initial token
/// @param inputTokenAmount Amount of token
/// @param outputToken Converted token
/// @return stability Amount of outputToken
function getDecimalConversion(
address inputToken,
uint256 inputTokenAmount,
address outputToken
) public view returns(uint256) {
uint256 inputTokenDec = 18;
uint256 outputTokenDec = 18;
if (inputToken != address(0x0)) {
inputTokenDec = IERC20(inputToken).decimals();
}
if (outputToken != address(0x0)) {
outputTokenDec = IERC20(outputToken).decimals();
}
return inputTokenAmount * (10**outputTokenDec) / (10**inputTokenDec);
}
//---------modifier------------
modifier onlyGovernance() {
require(IParassetGovernance(_governance).checkGovernance(msg.sender, 0), "Log:ParassetBase:!gov");
_;
}
modifier nonReentrant() {
require(_locked == 0, "Log:ParassetBase:!_locked");
_locked = 1;
_;
_locked = 0;
}
}
// File: lib/TransferHelper.sol
pragma solidity ^0.8.4;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File: iface/ILPStakingMiningPool.sol
pragma solidity ^0.8.4;
interface ILPStakingMiningPool {
function getBlock(uint256 endBlock) external view returns(uint256);
function getBalance(address stakingToken, address account) external view returns(uint256);
function getChannelInfo(address stakingToken) external view returns(uint256 lastUpdateBlock, uint256 endBlock, uint256 rewardRate, uint256 rewardPerTokenStored, uint256 totalSupply);
function getAccountReward(address stakingToken, address account) external view returns(uint256);
function stake(uint256 amount, address stakingToken) external;
function withdraw(uint256 amount, address stakingToken) external;
function getReward(address stakingToken) external;
}
// File: iface/IParasset.sol
pragma solidity ^0.8.4;
interface IParasset {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function destroy(uint256 amount, address account) external;
function issuance(uint256 amount, address account) external;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: iface/IInsurancePool.sol
pragma solidity ^0.8.4;
interface IInsurancePool {
/// @dev Destroy ptoken, update negative ledger
/// @param amount quantity destroyed
function destroyPToken(uint256 amount) external;
/// @dev Clear negative books
function eliminate() external;
}
// File: InsurancePool.sol
pragma solidity ^0.8.4;
contract InsurancePool is ParassetBase, IInsurancePool, ParassetERC20 {
// negative account funds
uint256 public _insNegative;
// latest redemption time
uint256 public _latestTime;
// status
uint8 public _flag; // = 0: pause
// = 1: active
// = 2: redemption only
// user address => freeze LP data
mapping(address => Frozen) _frozenIns;
struct Frozen {
// frozen quantity
uint256 amount;
// freezing time
uint256 time;
}
// pToken address
address public _pTokenAddress;
// redemption cycle, 2 days
uint96 public _redemptionCycle;
// underlyingToken address
address public _underlyingTokenAddress;
// redemption duration, 7 days
uint96 public _waitCycle;
// mortgagePool address
address public _mortgagePool;
// rate(2/1000)
uint96 public _feeRate;
uint constant MINIMUM_LIQUIDITY = 1e9;
// staking address
ILPStakingMiningPool _lpStakingMiningPool;
event SubNegative(uint256 amount, uint256 allValue);
event AddNegative(uint256 amount, uint256 allValue);
function initialize(address governance) public override {
super.initialize(governance);
_redemptionCycle = 15 minutes;
_waitCycle = 30 minutes;
_feeRate = 2;
_totalSupply = 0;
}
//---------modifier---------
modifier onlyMortgagePool() {
require(msg.sender == address(_mortgagePool), "Log:InsurancePool:!mortgagePool");
_;
}
modifier whenActive() {
require(_flag == 1, "Log:InsurancePool:!active");
_;
}
modifier redemptionOnly() {
require(_flag != 0, "Log:InsurancePool:!0");
_;
}
//---------view---------
/// @dev View the lpStakingMiningPool address
/// @return lpStakingMiningPool address
function getLPStakingMiningPool() external view returns(address) {
return address(_lpStakingMiningPool);
}
/// @dev View the all lp
/// @return all lp
function getAllLP(address user) public view returns(uint256) {
return _balances[user] + _lpStakingMiningPool.getBalance(address(this), user);
}
/// @dev View redemption period, next time
/// @return startTime start time
/// @return endTime end time
function getRedemptionTime() external view returns(uint256 startTime, uint256 endTime) {
uint256 time = _latestTime;
if (block.timestamp > time) {
uint256 subTime = (block.timestamp - time) / uint256(_waitCycle);
endTime = time + (uint256(_waitCycle) * (1 + subTime));
} else {
endTime = time;
}
startTime = endTime - uint256(_redemptionCycle);
}
/// @dev View frozen LP and unfreeze time
/// @param add user address
/// @return frozen LP
/// @return unfreeze time
function getFrozenIns(address add) external view returns(uint256, uint256) {
Frozen memory frozenInfo = _frozenIns[add];
return (frozenInfo.amount, frozenInfo.time);
}
/// @dev View frozen LP and unfreeze time, real time
/// @param add user address
/// @return frozen LP
function getFrozenInsInTime(address add) external view returns(uint256) {
Frozen memory frozenInfo = _frozenIns[add];
if (block.timestamp > frozenInfo.time) {
return 0;
}
return frozenInfo.amount;
}
/// @dev View redeemable LP, real time
/// @param add user address
/// @return redeemable LP
function getRedemptionAmount(address add) external view returns (uint256) {
Frozen memory frozenInfo = _frozenIns[add];
uint256 balanceSelf = _balances[add];
if (block.timestamp > frozenInfo.time) {
return balanceSelf;
} else {
return balanceSelf - frozenInfo.amount;
}
}
//---------governance----------
/// @dev Set token name
/// @param name token name
/// @param symbol token symbol
function setTokenInfo(string memory name, string memory symbol) external onlyGovernance {
_name = name;
_symbol = symbol;
}
/// @dev Set contract status
/// @param num 0: pause, 1: active, 2: redemption only
function setFlag(uint8 num) external onlyGovernance {
_flag = num;
}
/// @dev Set mortgage pool address
function setMortgagePool(address add) external onlyGovernance {
_mortgagePool = add;
}
/// @dev Set the staking contract address
function setLPStakingMiningPool(address add) external onlyGovernance {
_lpStakingMiningPool = ILPStakingMiningPool(add);
}
/// @dev Set the latest redemption time
function setLatestTime(uint256 num) external onlyGovernance {
_latestTime = num;
}
/// @dev Set the rate
function setFeeRate(uint96 num) external onlyGovernance {
_feeRate = num;
}
/// @dev Set redemption cycle
function setRedemptionCycle(uint256 num) external onlyGovernance {
require(num > 0, "Log:InsurancePool:!zero");
_redemptionCycle = uint96(num * 1 days);
}
/// @dev Set redemption duration
function setWaitCycle(uint256 num) external onlyGovernance {
require(num > 0, "Log:InsurancePool:!zero");
_waitCycle = uint96(num * 1 days);
}
/// @dev Set the underlying asset and PToken mapping and
/// @param uToken underlying asset address
/// @param pToken PToken address
function setInfo(address uToken, address pToken) external onlyGovernance {
_underlyingTokenAddress = uToken;
_pTokenAddress = pToken;
}
function test_insNegative(uint256 amount) external onlyGovernance {
_insNegative = amount;
}
//---------transaction---------
/// @dev Exchange: PToken exchanges the underlying asset
/// @param amount amount of PToken
function exchangePTokenToUnderlying(uint256 amount) public redemptionOnly nonReentrant {
// amount > 0
require(amount > 0, "Log:InsurancePool:!amount");
// Calculate the fee
uint256 fee = amount * _feeRate / 1000;
// Transfer to the PToken
address pTokenAddress = _pTokenAddress;
TransferHelper.safeTransferFrom(pTokenAddress, msg.sender, address(this), amount);
// Calculate the amount of transferred underlying asset
uint256 uTokenAmount = getDecimalConversion(pTokenAddress, amount - fee, _underlyingTokenAddress);
require(uTokenAmount > 0, "Log:InsurancePool:!uTokenAmount");
// Transfer out underlying asset
if (_underlyingTokenAddress == address(0x0)) {
TransferHelper.safeTransferETH(msg.sender, uTokenAmount);
} else {
TransferHelper.safeTransfer(_underlyingTokenAddress, msg.sender, uTokenAmount);
}
// Eliminate negative ledger
eliminate();
}
/// @dev Exchange: underlying asset exchanges the PToken
/// @param amount amount of underlying asset
function exchangeUnderlyingToPToken(uint256 amount) public payable redemptionOnly nonReentrant {
// amount > 0
require(amount > 0, "Log:InsurancePool:!amount");
// Calculate the fee
uint256 fee = amount * _feeRate / 1000;
// Transfer to the underlying asset
if (_underlyingTokenAddress == address(0x0)) {
// The underlying asset is ETH
require(msg.value == amount, "Log:InsurancePool:!msg.value");
} else {
// The underlying asset is ERC20
require(msg.value == 0, "Log:InsurancePool:msg.value!=0");
TransferHelper.safeTransferFrom(_underlyingTokenAddress, msg.sender, address(this), amount);
}
// Calculate the amount of transferred PTokens
uint256 pTokenAmount = getDecimalConversion(_underlyingTokenAddress, amount - fee, address(0x0));
require(pTokenAmount > 0, "Log:InsurancePool:!pTokenAmount");
// Transfer out PToken
address pTokenAddress = _pTokenAddress;
uint256 pTokenBalance = IERC20(pTokenAddress).balanceOf(address(this));
if (pTokenBalance < pTokenAmount) {
// Insufficient PToken balance,
uint256 subNum = pTokenAmount - pTokenBalance;
_issuancePToken(subNum);
}
TransferHelper.safeTransfer(pTokenAddress, msg.sender, pTokenAmount);
}
/// @dev Subscribe for insurance
/// @param amount amount of underlying asset
function subscribeIns(uint256 amount) public payable whenActive nonReentrant {
// amount > 0
require(amount > 0, "Log:InsurancePool:!amount");
// Update redemption time
updateLatestTime();
// Thaw LP
Frozen storage frozenInfo = _frozenIns[msg.sender];
if (block.timestamp > frozenInfo.time) {
frozenInfo.amount = 0;
}
// PToken balance
uint256 pTokenBalance = IERC20(_pTokenAddress).balanceOf(address(this));
// underlying asset balance
uint256 tokenBalance;
if (_underlyingTokenAddress == address(0x0)) {
// The amount of ETH involved in the calculation does not include the transfer in this time
require(msg.value == amount, "Log:InsurancePool:!msg.value");
tokenBalance = address(this).balance - amount;
} else {
require(msg.value == 0, "Log:InsurancePool:msg.value!=0");
// Underlying asset conversion 18 decimals
tokenBalance = getDecimalConversion(_underlyingTokenAddress, IERC20(_underlyingTokenAddress).balanceOf(address(this)), address(0x0));
}
// Calculate LP
uint256 insAmount = 0;
uint256 insTotal = _totalSupply;
uint256 allBalance = tokenBalance + pTokenBalance;
if (insTotal != 0) {
// Insurance pool assets must be greater than 0
require(allBalance > _insNegative, "Log:InsurancePool:allBalanceNotEnough");
uint256 allValue = allBalance - _insNegative;
insAmount = getDecimalConversion(_underlyingTokenAddress, amount, address(0x0)) * insTotal / allValue;
} else {
// The initial net value is 1
insAmount = getDecimalConversion(_underlyingTokenAddress, amount, address(0x0)) - MINIMUM_LIQUIDITY;
_issuance(MINIMUM_LIQUIDITY, address(0x0));
}
// Transfer to the underlying asset(ERC20)
if (_underlyingTokenAddress != address(0x0)) {
require(msg.value == 0, "Log:InsurancePool:msg.value!=0");
TransferHelper.safeTransferFrom(_underlyingTokenAddress, msg.sender, address(this), amount);
}
// Additional LP issuance
_issuance(insAmount, msg.sender);
// Freeze insurance LP
frozenInfo.amount = frozenInfo.amount + insAmount;
frozenInfo.time = _latestTime;
}
/// @dev Redemption insurance
/// @param amount redemption LP
function redemptionIns(uint256 amount) public redemptionOnly nonReentrant {
// amount > 0
require(amount > 0, "Log:InsurancePool:!amount");
// Update redemption time
updateLatestTime();
// Judging the redemption time
uint256 tokenTime = _latestTime;
require(block.timestamp < tokenTime && block.timestamp > tokenTime - uint256(_redemptionCycle), "Log:InsurancePool:!time");
// Thaw LP
Frozen storage frozenInfo = _frozenIns[msg.sender];
if (block.timestamp > frozenInfo.time) {
frozenInfo.amount = 0;
}
// PToken balance
uint256 pTokenBalance = IERC20(_pTokenAddress).balanceOf(address(this));
// underlying asset balance
uint256 tokenBalance;
if (_underlyingTokenAddress == address(0x0)) {
tokenBalance = address(this).balance;
} else {
tokenBalance = getDecimalConversion(_underlyingTokenAddress, IERC20(_underlyingTokenAddress).balanceOf(address(this)), address(0x0));
}
// Insurance pool assets must be greater than 0
uint256 allBalance = tokenBalance + pTokenBalance;
require(allBalance > _insNegative, "Log:InsurancePool:allBalanceNotEnough");
// Calculated amount of assets
uint256 allValue = allBalance - _insNegative;
uint256 insTotal = _totalSupply;
uint256 underlyingAmount = amount * allValue / insTotal;
// Destroy LP
_destroy(amount, msg.sender);
// Judgment to freeze LP
require(getAllLP(msg.sender) >= frozenInfo.amount, "Log:InsurancePool:frozen");
// Transfer out assets, priority transfer of the underlying assets, if the underlying assets are insufficient, transfer ptoken
if (_underlyingTokenAddress == address(0x0)) {
// ETH
if (tokenBalance >= underlyingAmount) {
TransferHelper.safeTransferETH(msg.sender, underlyingAmount);
} else {
TransferHelper.safeTransferETH(msg.sender, tokenBalance);
TransferHelper.safeTransfer(_pTokenAddress, msg.sender, underlyingAmount - tokenBalance);
}
} else {
// ERC20
if (tokenBalance >= underlyingAmount) {
TransferHelper.safeTransfer(_underlyingTokenAddress, msg.sender, getDecimalConversion(_pTokenAddress, underlyingAmount, _underlyingTokenAddress));
} else {
TransferHelper.safeTransfer(_underlyingTokenAddress, msg.sender, getDecimalConversion(_pTokenAddress, tokenBalance, _underlyingTokenAddress));
TransferHelper.safeTransfer(_pTokenAddress, msg.sender, underlyingAmount - tokenBalance);
}
}
}
/// @dev Destroy PToken, update negative ledger
/// @param amount quantity destroyed
function destroyPToken(uint256 amount) public override onlyMortgagePool {
_insNegative = _insNegative + amount;
emit AddNegative(amount, _insNegative);
eliminate();
}
/// @dev Issuance PToken, update negative ledger
/// @param amount Additional issuance quantity
function _issuancePToken(uint256 amount) private {
IParasset(_pTokenAddress).issuance(amount, address(this));
_insNegative = _insNegative + amount;
emit AddNegative(amount, _insNegative);
}
/// @dev Clear negative books
function eliminate() override public {
IParasset pErc20 = IParasset(_pTokenAddress);
// negative ledger
uint256 negative = _insNegative;
// PToken balance
uint256 pTokenBalance = pErc20.balanceOf(address(this));
if (negative > 0 && pTokenBalance > 0) {
if (negative >= pTokenBalance) {
// Increase negative ledger
pErc20.destroy(pTokenBalance, address(this));
_insNegative = _insNegative - pTokenBalance;
emit SubNegative(pTokenBalance, _insNegative);
} else {
// negative ledger = 0
pErc20.destroy(negative, address(this));
_insNegative = 0;
emit SubNegative(negative, _insNegative);
}
}
}
/// @dev Update redemption time
function updateLatestTime() public {
uint256 time = _latestTime;
if (block.timestamp > time) {
uint256 subTime = (block.timestamp - time) / uint256(_waitCycle);
_latestTime = time + (uint256(_waitCycle) * (1 + subTime));
}
}
/// @dev Destroy LP
/// @param amount quantity destroyed
/// @param account destroy address
function _destroy(
uint256 amount,
address account
) private {
require(_balances[account] >= amount, "Log:InsurancePool:!destroy");
_balances[account] = _balances[account] - amount;
_totalSupply = _totalSupply - amount;
// emit Destroy(amount, account);
emit Transfer(account, address(0x0), amount);
}
/// @dev Additional LP issuance
/// @param amount additional issuance quantity
/// @param account additional issuance address
function _issuance(
uint256 amount,
address account
) private {
_balances[account] = _balances[account] + amount;
_totalSupply = _totalSupply + amount;
// emit Issuance(amount, account);
emit Transfer(address(0x0), account, amount);
}
/**
* @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 override {
// Update redemption time
updateLatestTime();
// Thaw LP
Frozen storage frozenInfo = _frozenIns[sender];
if (block.timestamp > frozenInfo.time) {
frozenInfo.amount = 0;
}
require(sender != address(0), "ERC20: transfer from 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);
if (recipient != address(_lpStakingMiningPool)) {
require(getAllLP(sender) >= frozenInfo.amount, "Log:InsurancePool:frozen");
}
}
/// The insurance pool penetrates the warehouse, and external assets are added to the insurance pool.
function addETH() external payable {}
} | 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");
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);
}
| 2,317,925 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../WrappedToken.sol";
import "../interfaces/IERC2612Permit.sol";
import "../interfaces/IRouter.sol";
import "../libraries/LibDiamond.sol";
import "../libraries/LibFeeCalculator.sol";
import "../libraries/LibRouter.sol";
import "../libraries/LibGovernance.sol";
contract RouterFacet is IRouter {
using SafeERC20 for IERC20;
/// @notice Constructs the Router contract instance
function initRouter() external override {
LibRouter.Storage storage rs = LibRouter.routerStorage();
require(!rs.initialized, "RouterFacet: already initialized");
rs.initialized = true;
}
/// @param _ethHash The ethereum signed message hash
/// @return Whether this hash has already been used for a mint/unlock transaction
function hashesUsed(bytes32 _ethHash)
external
view
override
returns (bool)
{
LibRouter.Storage storage rs = LibRouter.routerStorage();
return rs.hashesUsed[_ethHash];
}
/// @return The count of native tokens in the set
function nativeTokensCount() external view override returns (uint256) {
return LibRouter.nativeTokensCount();
}
/// @return The address of the native token at a given index
function nativeTokenAt(uint256 _index)
external
view
override
returns (address)
{
return LibRouter.nativeTokenAt(_index);
}
/// @notice Transfers `amount` native tokens to the router contract.
/// The router must be authorised to transfer the native token.
/// @param _targetChain The target chain for the bridging operation
/// @param _nativeToken The token to be bridged
/// @param _amount The amount of tokens to bridge
/// @param _receiver The address of the receiver on the target chain
function lock(
uint256 _targetChain,
address _nativeToken,
uint256 _amount,
bytes memory _receiver
) public override whenNotPaused onlyNativeToken(_nativeToken) {
IERC20(_nativeToken).safeTransferFrom(
msg.sender,
address(this),
_amount
);
uint256 serviceFee = LibFeeCalculator.distributeRewards(
_nativeToken,
_amount
);
emit Lock(_targetChain, _nativeToken, _receiver, _amount, serviceFee);
}
/// @notice Locks the provided amount of nativeToken using an EIP-2612 permit and initiates a bridging transaction
/// @param _targetChain The chain to bridge the tokens to
/// @param _nativeToken The native token to bridge
/// @param _amount The amount of nativeToken to lock and bridge
/// @param _deadline The deadline for the provided permit
/// @param _v The recovery id of the permit's ECDSA signature
/// @param _r The first output of the permit's ECDSA signature
/// @param _s The second output of the permit's ECDSA signature
function lockWithPermit(
uint256 _targetChain,
address _nativeToken,
uint256 _amount,
bytes memory _receiver,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external override {
IERC2612Permit(_nativeToken).permit(
msg.sender,
address(this),
_amount,
_deadline,
_v,
_r,
_s
);
lock(_targetChain, _nativeToken, _amount, _receiver);
}
/// @notice Transfers `amount` native tokens to the `receiver` address.
/// Must be authorised by the configured supermajority threshold of `signatures` from the `members` set.
/// @param _sourceChain The chainId of the chain that we're bridging from
/// @param _transactionId The transaction ID + log index in the source chain
/// @param _nativeToken The address of the native token
/// @param _amount The amount to transfer
/// @param _receiver The address reveiving the tokens
/// @param _signatures The array of signatures from the members, authorising the operation
function unlock(
uint256 _sourceChain,
bytes memory _transactionId,
address _nativeToken,
uint256 _amount,
address _receiver,
bytes[] calldata _signatures
) external override whenNotPaused onlyNativeToken(_nativeToken) {
LibGovernance.validateSignaturesLength(_signatures.length);
bytes32 ethHash = computeMessage(
_sourceChain,
block.chainid,
_transactionId,
_nativeToken,
_receiver,
_amount
);
LibRouter.Storage storage rs = LibRouter.routerStorage();
require(
!rs.hashesUsed[ethHash],
"RouterFacet: transaction already submitted"
);
validateAndStoreTx(ethHash, _signatures);
uint256 serviceFee = LibFeeCalculator.distributeRewards(
_nativeToken,
_amount
);
uint256 transferAmount = _amount - serviceFee;
IERC20(_nativeToken).safeTransfer(_receiver, transferAmount);
emit Unlock(
_sourceChain,
_transactionId,
_nativeToken,
transferAmount,
_receiver,
serviceFee
);
}
/// @notice Burns `amount` of `wrappedToken` initializes a bridging transaction to the target chain
/// @param _targetChain The target chain to which the wrapped asset will be transferred
/// @param _wrappedToken The address of the wrapped token
/// @param _amount The amount of `wrappedToken` to burn
/// @param _receiver The address of the receiver on the target chain
function burn(
uint256 _targetChain,
address _wrappedToken,
uint256 _amount,
bytes memory _receiver
) public override whenNotPaused {
WrappedToken(_wrappedToken).burnFrom(msg.sender, _amount);
emit Burn(_targetChain, _wrappedToken, _amount, _receiver);
}
/// @notice Burns `amount` of `wrappedToken` using an EIP-2612 permit and initializes a bridging transaction to the target chain
/// @param _targetChain The target chain to which the wrapped asset will be transferred
/// @param _wrappedToken The address of the wrapped token
/// @param _amount The amount of `wrappedToken` to burn
/// @param _receiver The address of the receiver on the target chain
/// @param _deadline The deadline of the provided permit
/// @param _v The recovery id of the permit's ECDSA signature
/// @param _r The first output of the permit's ECDSA signature
/// @param _s The second output of the permit's ECDSA signature
function burnWithPermit(
uint256 _targetChain,
address _wrappedToken,
uint256 _amount,
bytes memory _receiver,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external override {
WrappedToken(_wrappedToken).permit(
msg.sender,
address(this),
_amount,
_deadline,
_v,
_r,
_s
);
burn(_targetChain, _wrappedToken, _amount, _receiver);
}
/// @notice Mints `amount` wrapped tokens to the `receiver` address.
/// Must be authorised by the configured supermajority threshold of `signatures` from the `members` set.
/// @param _sourceChain ID of the source chain
/// @param _transactionId The source transaction ID + log index
/// @param _wrappedToken The address of the wrapped token on the current chain
/// @param _amount The desired minting amount
/// @param _receiver The address of the receiver on this chain
/// @param _signatures The array of signatures from the members, authorising the operation
function mint(
uint256 _sourceChain,
bytes memory _transactionId,
address _wrappedToken,
address _receiver,
uint256 _amount,
bytes[] calldata _signatures
) external override whenNotPaused {
LibGovernance.validateSignaturesLength(_signatures.length);
bytes32 ethHash = computeMessage(
_sourceChain,
block.chainid,
_transactionId,
_wrappedToken,
_receiver,
_amount
);
LibRouter.Storage storage rs = LibRouter.routerStorage();
require(
!rs.hashesUsed[ethHash],
"RouterFacet: transaction already submitted"
);
validateAndStoreTx(ethHash, _signatures);
WrappedToken(_wrappedToken).mint(_receiver, _amount);
emit Mint(
_sourceChain,
_transactionId,
_wrappedToken,
_amount,
_receiver
);
}
/// @notice Deploys a wrapped version of `nativeToken` to the current chain
/// @param _sourceChain The chain where `nativeToken` is originally deployed to
/// @param _nativeToken The address of the token
/// @param _tokenParams The name/symbol/decimals to use for the wrapped version of `nativeToken`
function deployWrappedToken(
uint256 _sourceChain,
bytes memory _nativeToken,
WrappedTokenParams memory _tokenParams
) external override {
require(
bytes(_tokenParams.name).length > 0,
"RouterFacet: empty wrapped token name"
);
require(
bytes(_tokenParams.symbol).length > 0,
"RouterFacet: empty wrapped token symbol"
);
require(
_tokenParams.decimals > 0,
"RouterFacet: invalid wrapped token decimals"
);
LibDiamond.enforceIsContractOwner();
WrappedToken t = new WrappedToken(
_tokenParams.name,
_tokenParams.symbol,
_tokenParams.decimals
);
emit WrappedTokenDeployed(_sourceChain, _nativeToken, address(t));
}
/// @notice Updates a native token, which will be used for lock/unlock.
/// @param _nativeToken The native token address
/// @param _serviceFee The amount of fee, which will be taken upon lock/unlock execution
/// @param _status Whether the token will be added or removed
function updateNativeToken(
address _nativeToken,
uint256 _serviceFee,
bool _status
) external override {
require(_nativeToken != address(0), "RouterFacet: zero address");
LibDiamond.enforceIsContractOwner();
LibRouter.updateNativeToken(_nativeToken, _status);
LibFeeCalculator.setServiceFee(_nativeToken, _serviceFee);
emit NativeTokenUpdated(_nativeToken, _serviceFee, _status);
}
/// @notice Validates the signatures and the data and saves the transaction
/// @param _ethHash The hashed data
/// @param _signatures The array of signatures from the members, authorising the operation
function validateAndStoreTx(bytes32 _ethHash, bytes[] calldata _signatures)
internal
{
LibRouter.Storage storage rs = LibRouter.routerStorage();
LibGovernance.validateSignatures(_ethHash, _signatures);
rs.hashesUsed[_ethHash] = true;
}
/// @notice Computes the bytes32 ethereum signed message hash for signatures
/// @param _sourceChain The chain where the bridge transaction was initiated from
/// @param _targetChain The target chain of the bridge transaction.
/// Should always be the current chainId.
/// @param _transactionId The transaction ID of the bridge transaction
/// @param _token The address of the token on this chain
/// @param _receiver The receiving address on the current chain
/// @param _amount The amount of `_token` that is being bridged
function computeMessage(
uint256 _sourceChain,
uint256 _targetChain,
bytes memory _transactionId,
address _token,
address _receiver,
uint256 _amount
) internal pure returns (bytes32) {
bytes32 hashedData = keccak256(
abi.encode(
_sourceChain,
_targetChain,
_transactionId,
_token,
_receiver,
_amount
)
);
return ECDSA.toEthSignedMessageHash(hashedData);
}
modifier onlyNativeToken(address _nativeToken) {
require(
LibRouter.containsNativeToken(_nativeToken),
"RouterFacet: native token not found"
);
_;
}
/// Modifier to make a function callable only when the contract is not paused
modifier whenNotPaused() {
LibGovernance.enforceNotPaused();
_;
}
}
// 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'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
contract WrappedToken is ERC20Permit, Pausable, Ownable {
uint8 private immutable _decimals;
/**
* @notice Construct a new WrappedToken contract
* @param _tokenName The EIP-20 token name
* @param _tokenSymbol The EIP-20 token symbol
* @param decimals_ The The EIP-20 decimals
*/
constructor(
string memory _tokenName,
string memory _tokenSymbol,
uint8 decimals_
) ERC20(_tokenName, _tokenSymbol) ERC20Permit(_tokenName) {
_decimals = decimals_;
}
/**
* @notice Mints `_amount` of tokens to the `_account` address
* @param _account The address to which the tokens will be minted
* @param _amount The _amount to be minted
*/
function mint(address _account, uint256 _amount) public onlyOwner {
super._mint(_account, _amount);
}
/**
* @notice Burns `_amount` of tokens from the `_account` address
* @param _account The address from which the tokens will be burned
* @param _amount The _amount to be burned
*/
function burnFrom(address _account, uint256 _amount) public onlyOwner {
uint256 currentAllowance = allowance(_account, _msgSender());
require(
currentAllowance >= _amount,
"ERC20: burn amount exceeds allowance"
);
unchecked {
_approve(_account, _msgSender(), currentAllowance - _amount);
}
_burn(_account, _amount);
}
/// @notice Pauses the contract
function pause() public onlyOwner {
super._pause();
}
/// @notice Unpauses the contract
function unpause() public onlyOwner {
super._unpause();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 _amount
) internal virtual override {
super._beforeTokenTransfer(from, to, _amount);
require(!paused(), "WrappedToken: token transfer while paused");
}
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
/**
* @dev Interface of the ERC2612 standard as defined in the EIP.
*
* Adds the {permit} method, which can be used to change one's
* {IERC20-allowance} without having to send a transaction, by signing a
* message. This allows users to spend tokens without having to hold Ether.
*
* See https://eips.ethereum.org/EIPS/eip-2612.
*/
interface IERC2612Permit {
/**
* @dev Sets `_amount` as the allowance of `_spender` over `_owner`'s tokens,
* given `_owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `_owner` cannot be the zero address.
* - `_spender` cannot be the zero address.
* - `_deadline` must be a timestamp in the future.
* - `_v`, `_r` and `_s` must be a valid `secp256k1` signature from `_owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``_owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address _owner,
address _spender,
uint256 _amount,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external;
/**
* @dev Returns the current ERC2612 nonce for `_owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``_owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address _owner) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "../libraries/LibRouter.sol";
struct WrappedTokenParams {
string name;
string symbol;
uint8 decimals;
}
interface IRouter {
/// @notice An event emitted once a Lock transaction is executed
event Lock(
uint256 targetChain,
address token,
bytes receiver,
uint256 amount,
uint256 serviceFee
);
/// @notice An event emitted once a Burn transaction is executed
event Burn(
uint256 targetChain,
address token,
uint256 amount,
bytes receiver
);
/// @notice An event emitted once an Unlock transaction is executed
event Unlock(
uint256 sourceChain,
bytes transactionId,
address token,
uint256 amount,
address receiver,
uint256 serviceFee
);
/// @notice An even emitted once a Mint transaction is executed
event Mint(
uint256 sourceChain,
bytes transactionId,
address token,
uint256 amount,
address receiver
);
/// @notice An event emitted once a new wrapped token is deployed by the contract
event WrappedTokenDeployed(
uint256 sourceChain,
bytes nativeToken,
address wrappedToken
);
/// @notice An event emitted once a native token is updated
event NativeTokenUpdated(address token, uint256 serviceFee, bool status);
function initRouter() external;
function hashesUsed(bytes32 _ethHash) external view returns (bool);
function nativeTokensCount() external view returns (uint256);
function nativeTokenAt(uint256 _index) external view returns (address);
function lock(
uint256 _targetChain,
address _nativeToken,
uint256 _amount,
bytes memory _receiver
) external;
function lockWithPermit(
uint256 _targetChain,
address _nativeToken,
uint256 _amount,
bytes memory _receiver,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external;
function unlock(
uint256 _sourceChain,
bytes memory _transactionId,
address _nativeToken,
uint256 _amount,
address _receiver,
bytes[] calldata _signatures
) external;
function burn(
uint256 _targetChain,
address _wrappedToken,
uint256 _amount,
bytes memory _receiver
) external;
function burnWithPermit(
uint256 _targetChain,
address _wrappedToken,
uint256 _amount,
bytes memory _receiver,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external;
function mint(
uint256 _sourceChain,
bytes memory _transactionId,
address _wrappedToken,
address _receiver,
uint256 _amount,
bytes[] calldata _signatures
) external;
function deployWrappedToken(
uint256 _sourceChain,
bytes memory _nativeToken,
WrappedTokenParams memory _tokenParams
) external;
function updateNativeToken(
address _nativeToken,
uint256 _serviceFee,
bool _status
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "../interfaces/IDiamondCut.sol";
library LibDiamond {
bytes32 constant DIAMOND_STORAGE_POSITION =
keccak256("diamond.standard.diamond.storage");
struct FacetAddressAndPosition {
address facetAddress;
uint16 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array
}
struct FacetFunctionSelectors {
bytes4[] functionSelectors;
uint16 facetAddressPosition; // position of facetAddress in facetAddresses array
}
struct DiamondStorage {
// maps function selector to the facet address and
// the position of the selector in the facetFunctionSelectors.selectors array
mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition;
// maps facet addresses to function selectors
mapping(address => FacetFunctionSelectors) facetFunctionSelectors;
// facet addresses
address[] facetAddresses;
// Used to query if a contract implements an interface.
// Used to implement ERC-165.
mapping(bytes4 => bool) supportedInterfaces;
// owner of the contract
address contractOwner;
}
function diamondStorage()
internal
pure
returns (DiamondStorage storage ds)
{
bytes32 position = DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
}
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
function setContractOwner(address _newOwner) internal {
DiamondStorage storage ds = diamondStorage();
address previousOwner = ds.contractOwner;
ds.contractOwner = _newOwner;
emit OwnershipTransferred(previousOwner, _newOwner);
}
function contractOwner() internal view returns (address contractOwner_) {
contractOwner_ = diamondStorage().contractOwner;
}
function enforceIsContractOwner() internal view {
require(
msg.sender == diamondStorage().contractOwner,
"LibDiamond: Must be contract owner"
);
}
event DiamondCut(
IDiamondCut.FacetCut[] _diamondCut,
address _init,
bytes _calldata
);
// Internal function version of diamondCut
function diamondCut(
IDiamondCut.FacetCut[] memory _diamondCut,
address _init,
bytes memory _calldata
) internal {
for (
uint256 facetIndex;
facetIndex < _diamondCut.length;
facetIndex++
) {
IDiamondCut.FacetCutAction action = _diamondCut[facetIndex].action;
if (action == IDiamondCut.FacetCutAction.Add) {
addFunctions(
_diamondCut[facetIndex].facetAddress,
_diamondCut[facetIndex].functionSelectors
);
} else if (action == IDiamondCut.FacetCutAction.Replace) {
replaceFunctions(
_diamondCut[facetIndex].facetAddress,
_diamondCut[facetIndex].functionSelectors
);
} else if (action == IDiamondCut.FacetCutAction.Remove) {
removeFunctions(
_diamondCut[facetIndex].facetAddress,
_diamondCut[facetIndex].functionSelectors
);
} else {
revert("LibDiamondCut: Incorrect FacetCutAction");
}
}
emit DiamondCut(_diamondCut, _init, _calldata);
initializeDiamondCut(_init, _calldata);
}
function addFunctions(
address _facetAddress,
bytes4[] memory _functionSelectors
) internal {
require(
_functionSelectors.length > 0,
"LibDiamondCut: No selectors in facet to cut"
);
DiamondStorage storage ds = diamondStorage();
// uint16 selectorCount = uint16(diamondStorage().selectors.length);
require(
_facetAddress != address(0),
"LibDiamondCut: Add facet can't be address(0)"
);
uint16 selectorPosition = uint16(
ds.facetFunctionSelectors[_facetAddress].functionSelectors.length
);
// add new facet address if it does not exist
if (selectorPosition == 0) {
enforceHasContractCode(
_facetAddress,
"LibDiamondCut: New facet has no code"
);
ds
.facetFunctionSelectors[_facetAddress]
.facetAddressPosition = uint16(ds.facetAddresses.length);
ds.facetAddresses.push(_facetAddress);
}
for (
uint256 selectorIndex;
selectorIndex < _functionSelectors.length;
selectorIndex++
) {
bytes4 selector = _functionSelectors[selectorIndex];
address oldFacetAddress = ds
.selectorToFacetAndPosition[selector]
.facetAddress;
require(
oldFacetAddress == address(0),
"LibDiamondCut: Can't add function that already exists"
);
addFunction(ds, selector, selectorPosition, _facetAddress);
selectorPosition++;
}
}
function replaceFunctions(
address _facetAddress,
bytes4[] memory _functionSelectors
) internal {
require(
_functionSelectors.length > 0,
"LibDiamondCut: No selectors in facet to cut"
);
DiamondStorage storage ds = diamondStorage();
require(
_facetAddress != address(0),
"LibDiamondCut: Add facet can't be address(0)"
);
uint16 selectorPosition = uint16(
ds.facetFunctionSelectors[_facetAddress].functionSelectors.length
);
// add new facet address if it does not exist
if (selectorPosition == 0) {
enforceHasContractCode(
_facetAddress,
"LibDiamondCut: New facet has no code"
);
ds
.facetFunctionSelectors[_facetAddress]
.facetAddressPosition = uint16(ds.facetAddresses.length);
ds.facetAddresses.push(_facetAddress);
}
for (
uint256 selectorIndex;
selectorIndex < _functionSelectors.length;
selectorIndex++
) {
bytes4 selector = _functionSelectors[selectorIndex];
address oldFacetAddress = ds
.selectorToFacetAndPosition[selector]
.facetAddress;
require(
oldFacetAddress != _facetAddress,
"LibDiamondCut: Can't replace function with same function"
);
removeFunction(ds, oldFacetAddress, selector);
// add function
addFunction(ds, selector, selectorPosition, _facetAddress);
selectorPosition++;
}
}
function removeFunctions(
address _facetAddress,
bytes4[] memory _functionSelectors
) internal {
require(
_functionSelectors.length > 0,
"LibDiamondCut: No selectors in facet to cut"
);
DiamondStorage storage ds = diamondStorage();
// if function does not exist then do nothing and return
require(
_facetAddress == address(0),
"LibDiamondCut: Remove facet address must be address(0)"
);
for (
uint256 selectorIndex;
selectorIndex < _functionSelectors.length;
selectorIndex++
) {
bytes4 selector = _functionSelectors[selectorIndex];
address oldFacetAddress = ds
.selectorToFacetAndPosition[selector]
.facetAddress;
removeFunction(ds, oldFacetAddress, selector);
}
}
function addFunction(
DiamondStorage storage ds,
bytes4 _selector,
uint16 _selectorPosition,
address _facetAddress
) internal {
ds
.selectorToFacetAndPosition[_selector]
.functionSelectorPosition = _selectorPosition;
ds.facetFunctionSelectors[_facetAddress].functionSelectors.push(
_selector
);
ds.selectorToFacetAndPosition[_selector].facetAddress = _facetAddress;
}
function removeFunction(
DiamondStorage storage ds,
address _facetAddress,
bytes4 _selector
) internal {
require(
_facetAddress != address(0),
"LibDiamondCut: Can't remove function that doesn't exist"
);
// an immutable function is a function defined directly in a diamond
require(
_facetAddress != address(this),
"LibDiamondCut: Can't remove immutable function"
);
// replace selector with last selector, then delete last selector
uint256 selectorPosition = ds
.selectorToFacetAndPosition[_selector]
.functionSelectorPosition;
uint256 lastSelectorPosition = ds
.facetFunctionSelectors[_facetAddress]
.functionSelectors
.length - 1;
// if not the same then replace _selector with lastSelector
if (selectorPosition != lastSelectorPosition) {
bytes4 lastSelector = ds
.facetFunctionSelectors[_facetAddress]
.functionSelectors[lastSelectorPosition];
ds.facetFunctionSelectors[_facetAddress].functionSelectors[
selectorPosition
] = lastSelector;
ds
.selectorToFacetAndPosition[lastSelector]
.functionSelectorPosition = uint16(selectorPosition);
}
// delete the last selector
ds.facetFunctionSelectors[_facetAddress].functionSelectors.pop();
delete ds.selectorToFacetAndPosition[_selector];
// if no more selectors for facet address then delete the facet address
if (lastSelectorPosition == 0) {
// replace facet address with last facet address and delete last facet address
uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1;
uint256 facetAddressPosition = ds
.facetFunctionSelectors[_facetAddress]
.facetAddressPosition;
if (facetAddressPosition != lastFacetAddressPosition) {
address lastFacetAddress = ds.facetAddresses[
lastFacetAddressPosition
];
ds.facetAddresses[facetAddressPosition] = lastFacetAddress;
ds
.facetFunctionSelectors[lastFacetAddress]
.facetAddressPosition = uint16(facetAddressPosition);
}
ds.facetAddresses.pop();
delete ds
.facetFunctionSelectors[_facetAddress]
.facetAddressPosition;
}
}
function initializeDiamondCut(address _init, bytes memory _calldata)
internal
{
if (_init == address(0)) {
require(
_calldata.length == 0,
"LibDiamondCut: _init is address(0) but_calldata is not empty"
);
} else {
require(
_calldata.length > 0,
"LibDiamondCut: _calldata is empty but _init is not address(0)"
);
if (_init != address(this)) {
enforceHasContractCode(
_init,
"LibDiamondCut: _init address has no code"
);
}
(bool success, bytes memory error) = _init.delegatecall(_calldata);
if (!success) {
if (error.length > 0) {
// bubble up the error
revert(string(error));
} else {
revert("LibDiamondCut: _init function reverted");
}
}
}
}
function enforceHasContractCode(
address _contract,
string memory _errorMessage
) internal view {
uint256 contractSize;
assembly {
contractSize := extcodesize(_contract)
}
require(contractSize > 0, _errorMessage);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./LibGovernance.sol";
library LibFeeCalculator {
bytes32 constant STORAGE_POSITION = keccak256("fee.calculator.storage");
/// @notice Represents a fee calculator per token
struct FeeCalculator {
// The current service fee in percentage. Range is between 0 and Storage.precision
uint256 serviceFeePercentage;
// Total fees accrued since contract deployment
uint256 feesAccrued;
// Total fees accrued up to the last point a member claimed rewards
uint256 previousAccrued;
// Accumulates rewards on a per-member basis
uint256 accumulator;
// Total rewards claimed per member
mapping(address => uint256) claimedRewardsPerAccount;
}
struct Storage {
bool initialized;
// Precision for every calculator's fee percentage.
uint256 precision;
// A mapping consisting of all token fee calculators
mapping(address => FeeCalculator) nativeTokenFeeCalculators;
}
function feeCalculatorStorage() internal pure returns (Storage storage ds) {
bytes32 position = STORAGE_POSITION;
assembly {
ds.slot := position
}
}
/// @return The current precision for service fee calculations of tokens
function precision() internal view returns (uint256) {
LibFeeCalculator.Storage storage fcs = feeCalculatorStorage();
return fcs.precision;
}
/// @notice Sets the initial claimed rewards for new members for a given token
/// @param _account The address of the new member
/// @param _token The list of tokens
function addNewMember(address _account, address _token) internal {
LibFeeCalculator.Storage storage fcs = feeCalculatorStorage();
FeeCalculator storage fc = fcs.nativeTokenFeeCalculators[_token];
accrue(fc);
fc.claimedRewardsPerAccount[_account] = fc.accumulator;
}
/// @notice Accumulate fees for token and claim reward for claimer
/// @param _claimer The address of the claimer
/// @param _token The target token
/// @return The claimable amount
function claimReward(address _claimer, address _token)
internal
returns (uint256)
{
LibFeeCalculator.Storage storage fcs = feeCalculatorStorage();
FeeCalculator storage fc = fcs.nativeTokenFeeCalculators[_token];
accrue(fc);
uint256 claimableAmount = fc.accumulator -
fc.claimedRewardsPerAccount[_claimer];
fc.claimedRewardsPerAccount[_claimer] = fc.accumulator;
return claimableAmount;
}
/// @notice Distributes service fee for given token
/// @param _token The target token
/// @param _amount The amount to which the service fee will be calculated
/// @return serviceFee The calculated service fee
function distributeRewards(address _token, uint256 _amount)
internal
returns (uint256)
{
LibFeeCalculator.Storage storage fcs = feeCalculatorStorage();
FeeCalculator storage fc = fcs.nativeTokenFeeCalculators[_token];
uint256 serviceFee = (_amount * fc.serviceFeePercentage) /
fcs.precision;
fc.feesAccrued = fc.feesAccrued + serviceFee;
return serviceFee;
}
/// @notice Sets service fee for a token
/// @param _token The target token
/// @param _serviceFeePercentage The service fee percentage to be set
function setServiceFee(address _token, uint256 _serviceFeePercentage)
internal
{
LibFeeCalculator.Storage storage fcs = feeCalculatorStorage();
require(
_serviceFeePercentage < fcs.precision,
"LibFeeCalculator: service fee percentage exceeds or equal to precision"
);
FeeCalculator storage ntfc = fcs.nativeTokenFeeCalculators[_token];
ntfc.serviceFeePercentage = _serviceFeePercentage;
}
/// @notice Accrues fees to a fee calculator
/// @param _fc The fee calculator
/// @return The updated accumulator
function accrue(FeeCalculator storage _fc) internal returns (uint256) {
uint256 members = LibGovernance.membersCount();
uint256 amount = (_fc.feesAccrued - _fc.previousAccrued) / members;
_fc.previousAccrued += amount * members;
_fc.accumulator = _fc.accumulator + amount;
return _fc.accumulator;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
library LibRouter {
using EnumerableSet for EnumerableSet.AddressSet;
bytes32 constant STORAGE_POSITION = keccak256("router.storage");
struct Storage {
bool initialized;
// Storage for usability of given ethereum signed messages.
// ethereumSignedMessage => true/false
mapping(bytes32 => bool) hashesUsed;
// Stores all supported native Tokens on this chain
EnumerableSet.AddressSet nativeTokens;
}
function routerStorage() internal pure returns (Storage storage ds) {
bytes32 position = STORAGE_POSITION;
assembly {
ds.slot := position
}
}
function updateNativeToken(address _nativeToken, bool _status) internal {
Storage storage rs = routerStorage();
if (_status) {
require(
rs.nativeTokens.add(_nativeToken),
"LibRouter: native token already added"
);
} else {
require(
rs.nativeTokens.remove(_nativeToken),
"LibRouter: native token not found"
);
}
}
/// @notice Returns the count of native token
function nativeTokensCount() internal view returns (uint256) {
Storage storage rs = routerStorage();
return rs.nativeTokens.length();
}
/// @notice Returns the address of the native token at a given index
function nativeTokenAt(uint256 _index) internal view returns (address) {
Storage storage rs = routerStorage();
return rs.nativeTokens.at(_index);
}
/// @notice Returns true/false depending on whether a given native token is found
function containsNativeToken(address _nativeToken)
internal
view
returns (bool)
{
Storage storage rs = routerStorage();
return rs.nativeTokens.contains(_nativeToken);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
library LibGovernance {
using EnumerableSet for EnumerableSet.AddressSet;
bytes32 constant STORAGE_POSITION = keccak256("governance.storage");
struct Storage {
bool initialized;
// Set of active validators
EnumerableSet.AddressSet membersSet;
// A 1:1 map of active validators -> validator admin
mapping(address => address) membersAdmins;
// Precision for calculation of minimum amount of members signatures required
uint256 precision;
// Percentage for minimum amount of members signatures required
uint256 percentage;
// Admin of the contract
address admin;
// used to restrict certain functionality in case of an emergency stop
bool paused;
}
function governanceStorage() internal pure returns (Storage storage gs) {
bytes32 position = STORAGE_POSITION;
assembly {
gs.slot := position
}
}
/// @return Returns the admin
function admin() internal view returns (address) {
return governanceStorage().admin;
}
/// @return Returns true if the contract is paused, and false otherwise
function paused() internal view returns (bool) {
return governanceStorage().paused;
}
/// @return The current percentage for minimum amount of members signatures
function percentage() internal view returns (uint256) {
Storage storage gs = governanceStorage();
return gs.percentage;
}
/// @return The current precision for minimum amount of members signatures
function precision() internal view returns (uint256) {
Storage storage gs = governanceStorage();
return gs.precision;
}
function enforceNotPaused() internal view {
require(!governanceStorage().paused, "LibGovernance: paused");
}
function enforcePaused() internal view {
require(governanceStorage().paused, "LibGovernance: not paused");
}
function updateAdmin(address _newAdmin) internal {
Storage storage ds = governanceStorage();
ds.admin = _newAdmin;
}
function pause() internal {
enforceNotPaused();
Storage storage ds = governanceStorage();
ds.paused = true;
}
function unpause() internal {
enforcePaused();
Storage storage ds = governanceStorage();
ds.paused = false;
}
function updateMembersPercentage(uint256 _newPercentage) internal {
Storage storage gs = governanceStorage();
require(_newPercentage != 0, "LibGovernance: percentage must not be 0");
require(
_newPercentage < gs.precision,
"LibGovernance: percentage must be less than precision"
);
gs.percentage = _newPercentage;
}
/// @notice Adds/removes a validator from the member set
function updateMember(address _account, bool _status) internal {
Storage storage gs = governanceStorage();
if (_status) {
require(
gs.membersSet.add(_account),
"LibGovernance: Account already added"
);
} else if (!_status) {
require(
LibGovernance.membersCount() > 1,
"LibGovernance: contract would become memberless"
);
require(
gs.membersSet.remove(_account),
"LibGovernance: Account is not a member"
);
}
}
function updateMemberAdmin(address _account, address _admin) internal {
governanceStorage().membersAdmins[_account] = _admin;
}
/// @notice Returns true/false depending on whether a given address is member or not
function isMember(address _member) internal view returns (bool) {
Storage storage gs = governanceStorage();
return gs.membersSet.contains(_member);
}
/// @notice Returns the count of the members
function membersCount() internal view returns (uint256) {
Storage storage gs = governanceStorage();
return gs.membersSet.length();
}
/// @notice Returns the address of a member at a given index
function memberAt(uint256 _index) internal view returns (address) {
Storage storage gs = governanceStorage();
return gs.membersSet.at(_index);
}
/// @notice Returns the admin of the member
function memberAdmin(address _account) internal view returns (address) {
Storage storage gs = governanceStorage();
return gs.membersAdmins[_account];
}
/// @notice Checks if the provided amount of signatures is enough for submission
function hasValidSignaturesLength(uint256 _n) internal view returns (bool) {
Storage storage gs = governanceStorage();
uint256 members = gs.membersSet.length();
if (_n > members) {
return false;
}
uint256 mulMembersPercentage = members * gs.percentage;
uint256 requiredSignaturesLength = mulMembersPercentage / gs.precision;
if (mulMembersPercentage % gs.precision != 0) {
requiredSignaturesLength++;
}
return _n >= requiredSignaturesLength;
}
/// @notice Validates the provided signatures length
function validateSignaturesLength(uint256 _n) internal view {
require(
hasValidSignaturesLength(_n),
"LibGovernance: Invalid number of signatures"
);
}
/// @notice Validates the provided signatures against the member set
function validateSignatures(bytes32 _ethHash, bytes[] calldata _signatures)
internal
view
{
address[] memory signers = new address[](_signatures.length);
for (uint256 i = 0; i < _signatures.length; i++) {
address signer = ECDSA.recover(_ethHash, _signatures[i]);
require(isMember(signer), "LibGovernance: invalid signer");
for (uint256 j = 0; j < i; j++) {
require(
signer != signers[j],
"LibGovernance: duplicate signatures"
);
}
signers[i] = signer;
}
}
}
// 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;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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 "./draft-IERC20Permit.sol";
import "../ERC20.sol";
import "../../../utils/cryptography/draft-EIP712.sol";
import "../../../utils/cryptography/ECDSA.sol";
import "../../../utils/Counters.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// 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 default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
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 {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return recover(hash, r, vs);
} else {
revert("ECDSA: invalid signature length");
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`, `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(
uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"ECDSA: invalid signature 's' value"
);
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
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
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;
/**
* @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];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IDiamondCut {
enum FacetCutAction {
Add,
Replace,
Remove
}
// Add=0, Replace=1, Remove=2
struct FacetCut {
address facetAddress;
FacetCutAction action;
bytes4[] functionSelectors;
}
/// @notice Add/replace/remove any number of functions and optionally execute
/// a function with delegatecall
/// @param _diamondCut Contains the facet addresses and function selectors
/// @param _init The address of the contract or facet to execute _calldata
/// @param _calldata A function call, including function selector and arguments
/// _calldata is executed with delegatecall on _init
function diamondCut(
FacetCut[] calldata _diamondCut,
address _init,
bytes calldata _calldata
) external;
event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);
} | return Returns true if the contract is paused, and false otherwise | function paused() internal view returns (bool) {
return governanceStorage().paused;
}
| 1,525,994 |
./full_match/80001/0x32eB355270230643321561E84f04A6d7Cc022b03/sources/project_/contracts/ApedToken.sol | Burn some LVRJ token and return reserve token based on current curve price _amount Number of LVRJ token to convert to reserve tokens/ | function burn(uint256 _amount) public returns (uint256) {
uint256 reserveAmount = _continuousBurn(_amount);
return reserveAmount;
}
| 840,858 |
/**
*Submitted for verification at Etherscan.io on 2021-07-28
*/
// File: @pancakeswap/pancake-swap-lib/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.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;
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// File: @pancakeswap/pancake-swap-lib/contracts/token/BEP20/IBEP20.sol
pragma solidity >=0.4.0;
interface IBEP20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the bep token owner.
*/
function getOwner() external view returns (address);
/**
* @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: @pancakeswap/pancake-swap-lib/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, 'Address: insufficient balance');
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}('');
require(success, 'Address: unable to send value, recipient may have reverted');
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, 'Address: low-level call failed');
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, 'Address: low-level call with value failed');
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, 'Address: insufficient balance for call');
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), 'Address: call to non-contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: weiValue}(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @pancakeswap/pancake-swap-lib/contracts/token/BEP20/SafeBEP20.sol
pragma solidity ^0.6.0;
/**
* @title SafeBEP20
* @dev Wrappers around BEP20 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 SafeBEP20 for IBEP20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeBEP20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(
IBEP20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IBEP20 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
* {IBEP20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IBEP20 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),
'SafeBEP20: approve from non-zero to non-zero allowance'
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IBEP20 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(
IBEP20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(
value,
'SafeBEP20: 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(IBEP20 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, 'SafeBEP20: low-level call failed');
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), 'SafeBEP20: BEP20 operation did not succeed');
}
}
}
// File: @pancakeswap/pancake-swap-lib/contracts/GSN/Context.sol
pragma solidity >=0.4.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor() internal {}
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @pancakeswap/pancake-swap-lib/contracts/access/Ownable.sol
pragma solidity >=0.4.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _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 onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), 'Ownable: new owner is the zero address');
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @pancakeswap/pancake-swap-lib/contracts/token/BEP20/BEP20.sol
pragma solidity >=0.4.0;
/**
* @dev Implementation of the {IBEP20} 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 {BEP20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-BEP20-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 BEP20 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 {IBEP20-approve}.
*/
contract BEP20 is Context, IBEP20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the bep token owner.
*/
function getOwner() external override view returns (address) {
return owner();
}
/**
* @dev Returns the token name.
*/
function name() public override view returns (string memory) {
return _name;
}
/**
* @dev Returns the token decimals.
*/
function decimals() public override view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the token symbol.
*/
function symbol() public override view returns (string memory) {
return _symbol;
}
/**
* @dev See {BEP20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {BEP20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {BEP20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {BEP20-allowance}.
*/
function allowance(address owner, address spender) public override view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {BEP20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {BEP20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {BEP20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(amount, 'BEP20: 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 {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, 'BEP20: decreased allowance below zero')
);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing
* the total supply.
*
* Requirements
*
* - `msg.sender` must be the token owner
*/
function mint(uint256 amount) public onlyOwner returns (bool) {
_mint(_msgSender(), amount);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), 'BEP20: transfer from the zero address');
require(recipient != address(0), 'BEP20: transfer to the zero address');
_balances[sender] = _balances[sender].sub(amount, 'BEP20: transfer amount exceeds balance');
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), 'BEP20: mint to the zero address');
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), 'BEP20: burn from the zero address');
_balances[account] = _balances[account].sub(amount, 'BEP20: burn amount exceeds balance');
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal {
require(owner != address(0), 'BEP20: approve from the zero address');
require(spender != address(0), 'BEP20: approve to the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(
account,
_msgSender(),
_allowances[account][_msgSender()].sub(amount, 'BEP20: burn amount exceeds allowance')
);
}
}
// File: contracts/Token.sol
pragma solidity 0.6.12;
// Token with Governance
contract Token is BEP20 {
uint256 public maxSupply;
constructor(string memory _name, string memory _symbol, uint256 _maxSupply, uint256 _initialSupply, address _holder)
BEP20(_name, _symbol)
public
{
require(_initialSupply <= _maxSupply, "Token: cap exceeded");
maxSupply = _maxSupply;
_mint(_holder, _initialSupply);
}
/// @dev Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount)
public
onlyOwner
{
require(totalSupply() + _amount <= maxSupply, "Token: cap exceeded");
_mint(_to, _amount);
}
}
// File: contracts/MasterChef.sol
pragma solidity 0.6.12;
// MasterChef is the master of Token. He can make Token and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once TOKEN is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeBEP20 for IBEP20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of TOKENs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accTokenPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accTokenPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IBEP20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. TOKENs to distribute per block.
uint256 lastRewardBlock; // Last block number that TOKENs distribution occurs.
uint256 accTokenPerShare; // Accumulated TOKENs per share, times 1e12. See below.
uint16 depositFeeBP; // Deposit fee in basis points
uint256 totalRewardTokens;
uint256 totalMaxRewardTokens;
uint256 totalDeposit;
}
// The TOKEN
Token public token;
// TOKEN tokens created per block.
uint256 public tokenPerBlock;
// Bonus muliplier for early token makers.
uint256 public constant BONUS_MULTIPLIER = 1;
// Deposit Fee address
address public feeAddress;
// 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 TOKEN mining starts.
uint256 public startBlock;
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(Token _token, address _feeAddress, uint256 _tokenPerBlock, uint256 _startBlock)
public
{
token = _token;
feeAddress = _feeAddress;
tokenPerBlock = _tokenPerBlock;
startBlock = _startBlock;
}
function poolLength()
external
view
returns (uint256)
{
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, uint256 totalMaxRewardToken, bool _withUpdate)
public
onlyOwner
{
require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accTokenPerShare: 0,
depositFeeBP: _depositFeeBP,
totalRewardTokens: 0,
totalMaxRewardTokens: totalMaxRewardToken,
totalDeposit: 0
}));
}
// Update the given pool's TOKEN allocation point and deposit fee. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, uint256 totalMaxRewardToken, bool _withUpdate)
public
onlyOwner
{
require(_depositFeeBP <= 10000, "set: invalid deposit fee basis points");
if (_withUpdate) {
massUpdatePools();
}
require(poolInfo[_pid].totalRewardTokens <= totalMaxRewardToken, "set: totalMaxRewardToken is invalid");
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].depositFeeBP = _depositFeeBP;
poolInfo[_pid].totalMaxRewardTokens = totalMaxRewardToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to)
public
pure
returns (uint256)
{
return _to.sub(_from).mul(BONUS_MULTIPLIER);
}
// View function to see pending TOKENs on frontend.
function pendingToken(uint256 _pid, address _user)
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accTokenPerShare = pool.accTokenPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 tokenReward = multiplier.mul(tokenPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
uint256 remainingTokens = pool.totalMaxRewardTokens - pool.totalRewardTokens;
if (tokenReward > remainingTokens) {
tokenReward = remainingTokens;
}
accTokenPerShare = accTokenPerShare.add(tokenReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accTokenPerShare).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);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid)
public
{
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0 || pool.allocPoint == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 tokenReward = multiplier.mul(tokenPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
uint256 remainingTokens = pool.totalMaxRewardTokens - pool.totalRewardTokens;
if (tokenReward > remainingTokens) {
tokenReward = remainingTokens;
}
if (tokenReward == 0) {
pool.lastRewardBlock = block.number;
return;
}
token.mint(address(this), tokenReward);
pool.accTokenPerShare = pool.accTokenPerShare.add(tokenReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
pool.totalRewardTokens = pool.totalRewardTokens.add(tokenReward);
}
// Deposit LP tokens to MasterChef for TOKEN 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.accTokenPerShare).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
safeTokenTransfer(msg.sender, pending);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if (pool.depositFeeBP > 0) {
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
pool.totalDeposit = pool.totalDeposit.add(_amount).sub(depositFee);
} else {
user.amount = user.amount.add(_amount);
pool.totalDeposit = pool.totalDeposit.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount)
public
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accTokenPerShare).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
safeTokenTransfer(msg.sender, pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.totalDeposit = pool.totalDeposit.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e12);
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];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe token transfer function, just in case if rounding error causes pool to not have enough TOKENs.
function safeTokenTransfer(address _to, uint256 _amount)
internal
{
uint256 tokenBal = token.balanceOf(address(this));
if (_amount > tokenBal) {
token.transfer(_to, tokenBal);
} else {
token.transfer(_to, _amount);
}
}
function setFeeAddress(address _feeAddress)
public
{
require(msg.sender == feeAddress, "setFeeAddress: FORBIDDEN");
feeAddress = _feeAddress;
}
//Pancake has to add hidden dummy pools inorder to alter the emission, here we make it simple and transparent to all.
function updateEmissionRate(uint256 _tokenPerBlock)
public
onlyOwner
{
massUpdatePools();
tokenPerBlock = _tokenPerBlock;
}
function withdrawAllReward(address _receiver)
public
onlyOwner
{
require(_receiver != address(0), "address is invalid");
uint256 remaining = token.maxSupply() - token.totalSupply();
if (remaining > 0) {
token.mint(_receiver, remaining);
}
uint256 balance = token.balanceOf(address(this));
if (balance > 0) {
token.transfer(_receiver, balance);
}
}
} | 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);
}
}
| 6,771,054 |
/**
*Submitted for verification at Etherscan.io on 2022-05-02
*/
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts/utils/Counters.sol
// 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;
}
}
// 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/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(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);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// 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: NFT.sol
pragma solidity >=0.7.0 <0.9.0;
pragma experimental ABIEncoderV2;
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
contract NFT is ERC721, Ownable {
using SafeMath for mapping(address => uint);
using SafeMath for uint16;
using SafeMath for uint256;
using Strings for uint256;
bool public isActive = false;
bool public isPresaleActive = false;
bool public reveal = false;
uint8 public constant WHITELIST_MAX_MINT = 2;
uint8 public MAX_MINT = 5;
uint16 public MAX_NFT = 100;
uint16 private LIMIT_NFT_PRESALE = 0;
uint16 public totalSupply = 0;
address public proxyRegistryAddress;
address public OWNER_WALLET = msg.sender;
uint256 public NFT_PRICE = 125000000000000000; // 0.125 ETH //
uint256 public NFT_LOW_PRICE = 100000000000000000; // 0.10 ETH //
string private baseURI;
string private waitingURI;
mapping(address => uint) public whiteList;
mapping(address => uint) public oglist;
constructor(address _proxyRegistryAddress)
ERC721("Meta Football League", "MFL")
{
proxyRegistryAddress = _proxyRegistryAddress;
}
/*
* Check sale is active
*/
modifier onlyActive(){
require(isActive == true, "The Sale is not currently Active");
_;
}
/*
* Check presale is active
*/
modifier onlyPresaleActive(){
require(isPresaleActive == true, "The presale is not currently active");
_;
}
/*
* Check that user is in white list
*/
modifier onWhiteList(){
require(whiteList[msg.sender] > 0, "User not on whiteList or has already mint enough");
_;
}
/*
* Check user on Og list
*/
modifier onlyOG(){
require(oglist[msg.sender] > 0, "User not on OG list");
_;
}
/*
* Switch safe mode. Allow for urgent close.
*/
function switchActive() external onlyOwner{ //
isActive = !isActive;
}
/*
* Switch presale mode
*/
function switchPresale() external onlyOwner{
isPresaleActive = !isPresaleActive;
}
/** activate reveal */
function switchReveal() external onlyOwner {
reveal = !reveal;
}
/**
Set the Max of Nft to be sold during the presale
*/
function setPresaleMAX(uint16 PresaleMax) external onlyOwner {
LIMIT_NFT_PRESALE = PresaleMax;
}
/**
Set base uri to display the NFT image
*/
function setBaseURI(string memory _baseURI) external onlyOwner {
baseURI = _baseURI;
}
/**
Set URI to display until the reveal
*/
function setWaitingURI(string memory _waitingURI) external onlyOwner {
waitingURI = _waitingURI;
}
/**
return the URI of NFT depending on reveal
*/
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
if (!reveal) {
return string(abi.encodePacked(waitingURI));
} else {
return string(abi.encodePacked(baseURI, _tokenId.toString()));
}
}
/*
* Withdraw balance from contract
*/
function withdraw() external onlyOwner {
uint balance = address(this).balance;
payable(address(OWNER_WALLET)).transfer(balance);
}
/*
* Add user to white list
*/
function addOnWhiteList(address[] memory _addresses) external onlyOwner { //
for (uint256 i = 0; i < _addresses.length; i++) {
whiteList[_addresses[i]] = WHITELIST_MAX_MINT;
}
}
/*
* Add user on OG List
*/
function addOnOGList(address[] memory _addresses) external onlyOwner{
for (uint256 i = 0; i< _addresses.length; i++){
oglist[_addresses[i]] = 1;
}
}
/*
* Remove user on OG List
*/
function removeOnOGList(address[] memory _addresses) external onlyOwner{
for (uint256 i = 0; i< _addresses.length; i++){
oglist[_addresses[i]] = 0;
}
}
/*
* Sub function to mint `_numOfTokens` NFTs to `_to`
*/
function _mintNFT(address _to, uint16 _numOfTokens) private {
require(totalSupply + _numOfTokens <= MAX_NFT,"Minting would exceed number of existing NFTS");
for(uint i = 0; i < _numOfTokens; i++){
_safeMint(_to, totalSupply + i);
}
totalSupply += _numOfTokens;
}
/*
* Check for required conditions before calling sub function _mint
*/
function mintNFT(uint16 _numOfTokens) external payable onlyActive { //
require(NFT_PRICE.mul(_numOfTokens) == msg.value, "Ether value sent is not correct");
_mintNFT(msg.sender, _numOfTokens);
}
/*
* mint for OGs, Get OG role on our discord !
*/
function mintOG(uint16 _numOfTokens) external payable onlyActive onlyOG {
require(NFT_LOW_PRICE.mul(_numOfTokens) == msg.value, "Ether value is not correct");
_mintNFT(msg.sender, _numOfTokens);
}
/*
* Check `msg.sender` is on white list then call sub function _mint
*/
function mintWhiteList(uint16 _numOfTokens) external payable onWhiteList { //
require(NFT_PRICE.mul(_numOfTokens) == msg.value, "Ether value sent is not correct");
require(whiteList[msg.sender] - _numOfTokens >= 0, "Cannot mint more than limited");
whiteList[msg.sender] -= _numOfTokens;
_mintNFT(msg.sender, _numOfTokens);
}
/*
* Send free NFTs to give away winner
*/
function mintForGiveAway(address _to, uint16 _numOfTokens) external onlyOwner { //
_mintNFT(_to, _numOfTokens);
}
/*
* Function to mint new NFTs during the presale
*/
function mintNFTDuringPresale(uint16 _numOfTokens) external payable onlyPresaleActive {
require(NFT_LOW_PRICE.mul(_numOfTokens) == msg.value, "Ether value sent is not correct");
require(_numOfTokens + totalSupply <= LIMIT_NFT_PRESALE, "Number of token to be minted exceed allowed");
_mintNFT(msg.sender, _numOfTokens);
}
function isApprovedForAll(address _owner, address operator) override public view returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == operator) return true;
return super.isApprovedForAll(_owner, operator);
}
/*
* Standard functions to be overridden in ERC721Enumerable
*/
function supportsInterface( bytes4 _interfaceId ) public view override (ERC721) returns (bool)
{
return super.supportsInterface(_interfaceId);
}
function _beforeTokenTransfer(address _from, address _to, uint256 _tokenId) internal override(ERC721) {
super._beforeTokenTransfer(_from, _to, _tokenId);
}
} | Function to mint new NFTs during the presale/ | function mintNFTDuringPresale(uint16 _numOfTokens) external payable onlyPresaleActive {
require(NFT_LOW_PRICE.mul(_numOfTokens) == msg.value, "Ether value sent is not correct");
require(_numOfTokens + totalSupply <= LIMIT_NFT_PRESALE, "Number of token to be minted exceed allowed");
_mintNFT(msg.sender, _numOfTokens);
require(NFT_PRICE.mul(_numOfTokens) == msg.value, "Ether value sent is not correct");
_mintNFT(_to, _numOfTokens);
}
| 6,723,989 |
./full_match/4/0x6003CeE35E9D1faBa51C24B65D1B0aD6Ef0a4DDb/sources/contracts/scam.sol | Unpauses transfers on the token./ | function unpause() public onlyOwner {
require(paused(), "CoinToken: Contract is not paused");
_unpause();
}
| 796,127 |
./full_match/1/0xc3f2C8F9d5F0705De706b1302B7a039e1e11aC88/sources/contracts/logic/RailgunLogic.sol | Verifies transaction validity return valid, reason/ Gas price of eth transaction should be equal or greater than railgun transaction specified min gas price This will only work correctly for type 0 transactions, set to 0 for EIP-1559 transactions Adapt contract must either equal 0 or msg.sender ChainID should match the current EVM chainID Merkle root must be a seen historical root Loop through each nullifier If nullifier has been seen before return false Ensure ciphertext length matches the commitments length (minus 1 for unshield output) Check unshield preimage hash is correct If redirect is allowed unshield MUST be submitted by original recipient | function validateTransaction(Transaction calldata _transaction)
public
view
returns (bool, string memory)
{
if (tx.gasprice < _transaction.boundParams.minGasPrice) return (false, "Gas price too low");
if (
_transaction.boundParams.adaptContract != address(0) &&
_transaction.boundParams.adaptContract != msg.sender
) return (false, "Invalid Adapt Contract as Sender");
if (_transaction.boundParams.chainID != block.chainid) return (false, "ChainID mismatch");
if (!Commitments.rootHistory[_transaction.boundParams.treeNumber][_transaction.merkleRoot])
return (false, "Invalid Merkle Root");
for (
uint256 nullifierIter = 0;
nullifierIter < _transaction.nullifiers.length;
nullifierIter += 1
) {
if (
Commitments.nullifiers[_transaction.boundParams.treeNumber][
_transaction.nullifiers[nullifierIter]
]
) return (false, "Note already spent");
}
if (_transaction.boundParams.unshield != UnshieldType.NONE) {
if (
_transaction.boundParams.commitmentCiphertext.length != _transaction.commitments.length - 1
) return (false, "Invalid Note Ciphertext Array Length");
bytes32 hash;
if (_transaction.boundParams.unshield == UnshieldType.REDIRECT) {
hash = hashCommitment(
CommitmentPreimage({
npk: bytes32(uint256(uint160(msg.sender))),
token: _transaction.unshieldPreimage.token,
value: _transaction.unshieldPreimage.value
})
);
hash = hashCommitment(_transaction.unshieldPreimage);
}
return (false, "Invalid Withdraw Note");
return (false, "Invalid Note Ciphertext Array Length");
}
return (true, "");
}
| 17,076,243 |
pragma solidity ^0.4.24;
import "zeppelin/token/ERC20/SafeERC20.sol";
import "zeppelin/math/SafeMath.sol";
import "zeppelin/math/Math.sol";
import "./lib/AdditionalMath.sol";
import "contracts/MinersEscrow.sol";
import "contracts/NuCypherToken.sol";
import "contracts/proxy/Upgradeable.sol";
/**
* @notice Contract holds policy data and locks fees
**/
contract PolicyManager is Upgradeable {
using SafeERC20 for NuCypherToken;
using SafeMath for uint256;
using AdditionalMath for uint256;
using AdditionalMath for int256;
using AdditionalMath for uint16;
event PolicyCreated(
bytes16 indexed policyId,
address indexed client
);
event PolicyRevoked(
bytes16 indexed policyId,
address indexed client,
uint256 value
);
event ArrangementRevoked(
bytes16 indexed policyId,
address indexed client,
address indexed node,
uint256 value
);
event Withdrawn(
address indexed node,
address indexed recipient,
uint256 value
);
event RefundForArrangement(
bytes16 indexed policyId,
address indexed client,
address indexed node,
uint256 value
);
event RefundForPolicy(
bytes16 indexed policyId,
address indexed client,
uint256 value
);
struct ArrangementInfo {
address node;
uint256 indexOfDowntimePeriods;
uint16 lastRefundedPeriod;
}
struct Policy {
address client;
// policy for activity periods
uint256 rewardRate;
uint256 firstPartialReward;
uint16 startPeriod;
uint16 lastPeriod;
bool disabled;
ArrangementInfo[] arrangements;
}
struct NodeInfo {
uint256 reward;
uint256 rewardRate;
uint16 lastMinedPeriod;
mapping (uint16 => int256) rewardDelta;
uint256 minRewardRate;
}
bytes16 constant RESERVED_POLICY_ID = bytes16(0);
address constant RESERVED_NODE = 0x0;
MinersEscrow public escrow;
uint32 public secondsPerPeriod;
mapping (bytes16 => Policy) public policies;
mapping (address => NodeInfo) public nodes;
/**
* @notice Constructor sets address of the escrow contract
* @param _escrow Escrow contract
**/
constructor(MinersEscrow _escrow) public {
require(address(_escrow) != 0x0);
escrow = _escrow;
secondsPerPeriod = escrow.secondsPerPeriod();
}
/**
* @dev Checks that sender is the MinersEscrow contract
**/
modifier onlyEscrowContract()
{
require(msg.sender == address(escrow));
_;
}
/**
* @return Number of current period
**/
function getCurrentPeriod() public view returns (uint16) {
return uint16(block.timestamp / secondsPerPeriod);
}
/**
* @notice Register a node
* @param _node Node address
* @param _period Initial period
**/
function register(address _node, uint16 _period) external onlyEscrowContract {
NodeInfo storage nodeInfo = nodes[_node];
require(nodeInfo.lastMinedPeriod == 0);
nodeInfo.lastMinedPeriod = _period;
}
/**
* @notice Set the minimum reward that the node will take
**/
function setMinRewardRate(uint256 _minRewardRate) public {
NodeInfo storage node = nodes[msg.sender];
node.minRewardRate = _minRewardRate;
}
/**
* @notice Create policy by client
* @dev Generate policy id before creation.
* @dev Formula for reward calculation: numberOfNodes * (firstPartialReward + rewardRate * numberOfPeriods)
* @param _policyId Policy id
* @param _numberOfPeriods Duration of the policy in periods except first period
* @param _firstPartialReward Partial reward for first/current period
* @param _nodes Nodes that will handle policy
**/
function createPolicy(
bytes16 _policyId,
uint16 _numberOfPeriods,
uint256 _firstPartialReward,
address[] _nodes
)
public payable
{
require(
_policyId != RESERVED_POLICY_ID &&
policies[_policyId].rewardRate == 0 &&
_numberOfPeriods != 0 &&
msg.value > 0
);
Policy storage policy = policies[_policyId];
policy.client = msg.sender;
uint16 currentPeriod = getCurrentPeriod();
policy.startPeriod = currentPeriod.add16(1);
policy.lastPeriod = currentPeriod.add16(_numberOfPeriods);
policy.rewardRate = msg.value.div(_nodes.length).sub(_firstPartialReward).div(_numberOfPeriods);
policy.firstPartialReward = _firstPartialReward;
require(policy.rewardRate > _firstPartialReward &&
(_firstPartialReward + policy.rewardRate * _numberOfPeriods) * _nodes.length == msg.value);
uint16 endPeriod = policy.lastPeriod.add16(1);
uint256 startReward = policy.rewardRate - _firstPartialReward;
for (uint256 i = 0; i < _nodes.length; i++) {
address node = _nodes[i];
require(node != RESERVED_NODE);
NodeInfo storage nodeInfo = nodes[node];
require(nodeInfo.lastMinedPeriod != 0 && policy.rewardRate >= nodeInfo.minRewardRate);
nodeInfo.rewardDelta[currentPeriod] = nodeInfo.rewardDelta[currentPeriod].add(_firstPartialReward);
nodeInfo.rewardDelta[policy.startPeriod] = nodeInfo.rewardDelta[policy.startPeriod]
.add(startReward);
nodeInfo.rewardDelta[endPeriod] = nodeInfo.rewardDelta[endPeriod].sub(policy.rewardRate);
policy.arrangements.push(ArrangementInfo(node, escrow.getPastDowntimeLength(node), 0));
}
emit PolicyCreated(_policyId, msg.sender);
}
/**
* @notice Update node reward
* @param _node Node address
* @param _period Processed period
**/
function updateReward(address _node, uint16 _period) external onlyEscrowContract {
NodeInfo storage node = nodes[_node];
if (node.lastMinedPeriod == 0 || _period <= node.lastMinedPeriod) {
return;
}
for (uint16 i = node.lastMinedPeriod + 1; i <= _period; i++) {
node.rewardRate = node.rewardRate.add(node.rewardDelta[i]);
}
node.lastMinedPeriod = _period;
node.reward = node.reward.add(node.rewardRate);
}
/**
* @notice Withdraw reward by node
**/
function withdraw() public returns (uint256) {
return withdraw(msg.sender);
}
/**
* @notice Withdraw reward by node
* @param _recipient Recipient of the reward
**/
function withdraw(address _recipient) public returns (uint256) {
NodeInfo storage node = nodes[msg.sender];
uint256 reward = node.reward;
require(reward != 0);
node.reward = 0;
_recipient.transfer(reward);
emit Withdrawn(msg.sender, _recipient, reward);
return reward;
}
/**
* @notice Calculate amount of refund
* @param _policy Policy
* @param _arrangement Arrangement
**/
function calculateRefundValue(Policy storage _policy, ArrangementInfo storage _arrangement)
internal view returns (uint256 refundValue, uint256 indexOfDowntimePeriods, uint16 lastRefundedPeriod)
{
uint16 maxPeriod = AdditionalMath.min16(getCurrentPeriod(), _policy.lastPeriod);
uint16 minPeriod = AdditionalMath.max16(_policy.startPeriod, _arrangement.lastRefundedPeriod);
uint16 downtimePeriods = 0;
uint256 length = escrow.getPastDowntimeLength(_arrangement.node);
for (indexOfDowntimePeriods = _arrangement.indexOfDowntimePeriods;
indexOfDowntimePeriods < length;
indexOfDowntimePeriods++)
{
(uint16 startPeriod, uint16 endPeriod) =
escrow.getPastDowntime(_arrangement.node, indexOfDowntimePeriods);
if (startPeriod > maxPeriod) {
break;
} else if (endPeriod < minPeriod) {
continue;
}
downtimePeriods = downtimePeriods.add16(
AdditionalMath.min16(maxPeriod, endPeriod)
.sub16(AdditionalMath.max16(minPeriod, startPeriod))
.add16(1));
if (maxPeriod <= endPeriod) {
break;
}
}
uint16 lastActivePeriod = escrow.getLastActivePeriod(_arrangement.node);
if (indexOfDowntimePeriods == length && lastActivePeriod < maxPeriod) {
downtimePeriods = downtimePeriods.add16(
maxPeriod.sub16(AdditionalMath.max16(
minPeriod.sub16(1), lastActivePeriod)));
}
// check activity for the first period
if (_arrangement.lastRefundedPeriod == 0) {
if (lastActivePeriod < _policy.startPeriod - 1) {
refundValue = _policy.firstPartialReward;
} else if (_arrangement.indexOfDowntimePeriods < length) {
(startPeriod, endPeriod) = escrow.getPastDowntime(
_arrangement.node, _arrangement.indexOfDowntimePeriods);
if (_policy.startPeriod > startPeriod && _policy.startPeriod - 1 <= endPeriod) {
refundValue = _policy.firstPartialReward;
}
}
}
refundValue = refundValue.add(_policy.rewardRate.mul(downtimePeriods));
lastRefundedPeriod = maxPeriod.add16(1);
}
/**
* @notice Revoke/refund arrangement/policy by the client
* @param _policyId Policy id
* @param _node Node that will be excluded or RESERVED_NODE if full policy should be used
( @param _forceRevoke Force revoke arrangement/policy
**/
function refundInternal(bytes16 _policyId, address _node, bool _forceRevoke)
internal returns (uint256 refundValue)
{
Policy storage policy = policies[_policyId];
require(policy.client == msg.sender && !policy.disabled);
uint16 endPeriod = policy.lastPeriod.add16(1);
uint256 numberOfActive = policy.arrangements.length;
for (uint256 i = 0; i < policy.arrangements.length; i++) {
ArrangementInfo storage arrangement = policy.arrangements[i];
address node = arrangement.node;
if (node == RESERVED_NODE || _node != RESERVED_NODE && _node != node) {
numberOfActive--;
continue;
}
uint256 nodeRefundValue;
(nodeRefundValue, arrangement.indexOfDowntimePeriods, arrangement.lastRefundedPeriod) =
calculateRefundValue(policy, arrangement);
if (_forceRevoke) {
NodeInfo storage nodeInfo = nodes[node];
nodeInfo.rewardDelta[arrangement.lastRefundedPeriod] =
nodeInfo.rewardDelta[arrangement.lastRefundedPeriod].sub(policy.rewardRate);
nodeInfo.rewardDelta[endPeriod] = nodeInfo.rewardDelta[endPeriod].add(policy.rewardRate);
nodeRefundValue = nodeRefundValue.add(
uint256(endPeriod.sub16(arrangement.lastRefundedPeriod)).mul(policy.rewardRate));
}
if (_forceRevoke || arrangement.lastRefundedPeriod > policy.lastPeriod) {
arrangement.node = RESERVED_NODE;
numberOfActive--;
emit ArrangementRevoked(_policyId, msg.sender, node, nodeRefundValue);
} else {
emit RefundForArrangement(_policyId, msg.sender, node, nodeRefundValue);
}
refundValue = refundValue.add(nodeRefundValue);
if (_node != RESERVED_NODE) {
break;
}
}
if (refundValue > 0) {
msg.sender.transfer(refundValue);
}
if (_node == RESERVED_NODE) {
if (numberOfActive == 0) {
policy.disabled = true;
emit PolicyRevoked(_policyId, msg.sender, refundValue);
} else {
emit RefundForPolicy(_policyId, msg.sender, refundValue);
}
} else {
// arrangement not found
require(i < policy.arrangements.length);
}
}
/**
* @notice Calculate amount of refund
* @param _policyId Policy id
* @param _node Node or RESERVED_NODE if all nodes should be used
**/
function calculateRefundValueInternal(bytes16 _policyId, address _node)
internal view returns (uint256 refundValue)
{
Policy storage policy = policies[_policyId];
require(msg.sender == policy.client && !policy.disabled);
for (uint256 i = 0; i < policy.arrangements.length; i++) {
ArrangementInfo storage arrangement = policy.arrangements[i];
if (arrangement.node == RESERVED_NODE || _node != RESERVED_NODE && _node != arrangement.node) {
continue;
}
(uint256 nodeRefundValue,,) = calculateRefundValue(policy, arrangement);
refundValue = refundValue.add(nodeRefundValue);
if (_node != RESERVED_NODE) {
break;
}
}
if (_node != RESERVED_NODE) {
// arrangement not found
require(i < policy.arrangements.length);
}
}
/**
* @notice Revoke policy by client
* @param _policyId Policy id
**/
function revokePolicy(bytes16 _policyId) public {
refundInternal(_policyId, RESERVED_NODE, true);
}
/**
* @notice Revoke arrangement by client
* @param _policyId Policy id
* @param _node Node that will be excluded
**/
function revokeArrangement(bytes16 _policyId, address _node)
public returns (uint256 refundValue)
{
require(_node != RESERVED_NODE);
return refundInternal(_policyId, _node, true);
}
/**
* @notice Refund part of fee by client
* @param _policyId Policy id
**/
function refund(bytes16 _policyId) public {
refundInternal(_policyId, RESERVED_NODE, false);
}
/**
* @notice Refund part of one node's fee by client
* @param _policyId Policy id
* @param _node Node address
**/
function refund(bytes16 _policyId, address _node)
public returns (uint256 refundValue)
{
require(_node != RESERVED_NODE);
return refundInternal(_policyId, _node, false);
}
/**
* @notice Calculate amount of refund
* @param _policyId Policy id
**/
function calculateRefundValue(bytes16 _policyId)
external view returns (uint256 refundValue)
{
return calculateRefundValueInternal(_policyId, RESERVED_NODE);
}
/**
* @notice Calculate amount of refund
* @param _policyId Policy id
* @param _node Node
**/
function calculateRefundValue(bytes16 _policyId, address _node)
external view returns (uint256 refundValue)
{
require(_node != RESERVED_NODE);
return calculateRefundValueInternal(_policyId, _node);
}
/**
* @notice Get number of arrangements in the policy
* @param _policyId Policy id
**/
function getArrangementsLength(bytes16 _policyId)
public view returns (uint256)
{
return policies[_policyId].arrangements.length;
}
/**
* @notice Get information about node reward
* @param _node Address of node
* @param _period Period to get reward delta
**/
function getNodeRewardDelta(address _node, uint16 _period)
public view returns (int256)
{
return nodes[_node].rewardDelta[_period];
}
/**
* @notice Return the information about arrangement
**/
function getArrangementInfo(bytes16 _policyId, uint256 _index)
// TODO change to structure when ABIEncoderV2 is released
// public view returns (ArrangementInfo)
public view returns (address node, uint256 indexOfDowntimePeriods, uint16 lastRefundedPeriod)
{
ArrangementInfo storage info = policies[_policyId].arrangements[_index];
node = info.node;
indexOfDowntimePeriods = info.indexOfDowntimePeriods;
lastRefundedPeriod = info.lastRefundedPeriod;
}
/**
* @dev Get Policy structure by delegatecall
**/
function delegateGetPolicy(address _target, bytes16 _policyId)
internal returns (Policy memory result)
{
bytes32 memoryAddress = delegateGetData(_target, "policies(bytes16)", 1, bytes32(_policyId), 0);
assembly {
result := memoryAddress
}
}
/**
* @dev Get ArrangementInfo structure by delegatecall
**/
function delegateGetArrangementInfo(address _target, bytes16 _policyId, uint256 _index)
internal returns (ArrangementInfo memory result)
{
bytes32 memoryAddress = delegateGetData(
_target, "getArrangementInfo(bytes16,uint256)", 2, bytes32(_policyId), bytes32(_index));
assembly {
result := memoryAddress
}
}
/**
* @dev Get NodeInfo structure by delegatecall
**/
function delegateGetNodeInfo(address _target, address _node)
internal returns (NodeInfo memory result)
{
bytes32 memoryAddress = delegateGetData(_target, "nodes(address)", 1, bytes32(_node), 0);
assembly {
result := memoryAddress
}
}
function verifyState(address _testTarget) public onlyOwner {
require(address(delegateGet(_testTarget, "escrow()")) == address(escrow));
require(uint32(delegateGet(_testTarget, "secondsPerPeriod()")) == secondsPerPeriod);
Policy storage policy = policies[RESERVED_POLICY_ID];
Policy memory policyToCheck = delegateGetPolicy(_testTarget, RESERVED_POLICY_ID);
require(policyToCheck.client == policy.client &&
policyToCheck.rewardRate == policy.rewardRate &&
policyToCheck.firstPartialReward == policy.firstPartialReward &&
policyToCheck.startPeriod == policy.startPeriod &&
policyToCheck.lastPeriod == policy.lastPeriod &&
policyToCheck.disabled == policy.disabled);
require(uint256(delegateGet(_testTarget, "getArrangementsLength(bytes16)",
RESERVED_POLICY_ID)) == policy.arrangements.length);
ArrangementInfo storage arrangement = policy.arrangements[0];
ArrangementInfo memory arrangementToCheck = delegateGetArrangementInfo(
_testTarget, RESERVED_POLICY_ID, 0);
require(arrangementToCheck.node == arrangement.node &&
arrangementToCheck.indexOfDowntimePeriods == arrangement.indexOfDowntimePeriods &&
arrangementToCheck.lastRefundedPeriod == arrangement.lastRefundedPeriod);
NodeInfo storage nodeInfo = nodes[RESERVED_NODE];
NodeInfo memory nodeInfoToCheck = delegateGetNodeInfo(_testTarget, RESERVED_NODE);
require(nodeInfoToCheck.reward == nodeInfo.reward &&
nodeInfoToCheck.rewardRate == nodeInfo.rewardRate &&
nodeInfoToCheck.lastMinedPeriod == nodeInfo.lastMinedPeriod &&
nodeInfoToCheck.minRewardRate == nodeInfo.minRewardRate);
require(int256(delegateGet(_testTarget, "getNodeRewardDelta(address,uint16)",
bytes32(RESERVED_NODE), 11)) == nodeInfo.rewardDelta[11]);
}
function finishUpgrade(address _target) public onlyOwner {
PolicyManager policyManager = PolicyManager(_target);
escrow = policyManager.escrow();
secondsPerPeriod = policyManager.secondsPerPeriod();
// Create fake Policy and NodeInfo to use them in verifyState(address)
Policy storage policy = policies[RESERVED_POLICY_ID];
policy.client = owner;
policy.startPeriod = 1;
policy.lastPeriod = 2;
policy.rewardRate = 3;
policy.firstPartialReward = 4;
policy.disabled = true;
policy.arrangements.push(ArrangementInfo(RESERVED_NODE, 11, 22));
NodeInfo storage nodeInfo = nodes[RESERVED_NODE];
nodeInfo.reward = 100;
nodeInfo.rewardRate = 33;
nodeInfo.lastMinedPeriod = 44;
nodeInfo.rewardDelta[11] = 55;
nodeInfo.minRewardRate = 777;
}
} | Calculate amount of refund _policyId Policy id _node Node/ | function calculateRefundValue(bytes16 _policyId, address _node)
external view returns (uint256 refundValue)
{
require(_node != RESERVED_NODE);
return calculateRefundValueInternal(_policyId, _node);
}
| 889,802 |
//! The Secret Store service contract intefaces.
//!
//! Copyright 2017 Svyatoslav Nikolsky, Parity Technologies Ltd.
//!
//! Licensed under the Apache License, Version 2.0 (the "License");
//! you may not use this file except in compliance with the License.
//! You may obtain a copy of the License at
//!
//! http://www.apache.org/licenses/LICENSE-2.0
//!
//! Unless required by applicable law or agreed to in writing, software
//! distributed under the License is distributed on an "AS IS" BASIS,
//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//! See the License for the specific language governing permissions and
//! limitations under the License.
pragma solidity >0.4.99 <0.6.0;
import "./Owned.sol";
import "./KeyServerSet.sol";
/// Base contract for all Secret Store services.
contract SecretStoreServiceBase is Owned {
/// Response support.
enum ResponseSupport { Confirmed, Unconfirmed, Impossible }
/// Single service request responses.
struct RequestResponses {
/// Number of block when servers set has been changed last time.
/// This whole structure is valid when this value stays the same.
/// Once this changes, all previous responses are erased.
uint256 keyServerSetChangeBlock;
/// We only support up to 256 key servers. If bit is set, this means that key server
/// has already voted for some confirmation (we do not care about exact response).
uint256 respondedKeyServersMask;
/// Number of key servers that have responded to request (number of ones in respondedKeyServersMask).
uint8 respondedKeyServersCount;
/// Response => number of supporting key servers.
mapping (bytes32 => uint8) responsesSupport;
/// Maximal support of single response.
uint8 maxResponseSupport;
/// All responses that are in responsesSupport. In ideal world, when all
/// key servers are working correctly, there'll be 1 response. Max 256 responses.
bytes32[] responses;
}
/// Only pass when fee is paid.
modifier whenFeePaid(uint256 amount) {
require(msg.value >= amount, "Not enough value");
_;
}
/// Only pass when 'valid' public is passed.
modifier validPublic(bytes memory publicKey) {
require(publicKey.length == 64, "Invalid length");
_;
}
/// Constructor.
constructor(address keyServerSetAddressInit) internal {
keyServerSetAddress = keyServerSetAddressInit;
}
/// Return number of key servers.
function keyServersCount() public view returns (uint8) {
return KeyServerSet(keyServerSetAddress).getCurrentKeyServersCount();
}
/// Return index of key server at given address.
function requireKeyServer(address keyServer) public view returns (uint8) {
return KeyServerSet(keyServerSetAddress).getCurrentKeyServerIndex(keyServer);
}
/// Drain balance of sender key server.
function drain() public {
uint256 balance = balances[msg.sender];
require(balance != 0, "Should not 0");
balances[msg.sender] = 0;
msg.sender.transfer(balance);
}
/// Deposit equal share of amount to each of key servers.
function deposit() internal {
uint8 count = keyServersCount();
uint256 amount = msg.value;
uint256 share = amount / count;
for (uint8 i = 0; i < count - 1; i++) {
address keyServer = KeyServerSet(keyServerSetAddress).getCurrentKeyServer(i);
balances[keyServer] += share;
amount = amount - share;
}
address lastKeyServer = KeyServerSet(keyServerSetAddress).getCurrentKeyServer(count - 1);
balances[lastKeyServer] += amount;
}
/// Returns true if response from given keyServer is required.
function isResponseRequired(RequestResponses storage responses, uint8 keyServerIndex) internal view returns (bool) {
// if servers set has changed, new response is definitely required
uint256 keyServerSetChangeBlock = KeyServerSet(keyServerSetAddress).getCurrentLastChange();
if (keyServerSetChangeBlock != responses.keyServerSetChangeBlock) {
return true;
}
// only require response when server has not responded before
uint256 keyServerMask = (uint256(1) << keyServerIndex);
return ((responses.respondedKeyServersMask & keyServerMask) == 0);
}
/// Insert key server confirmation.
function insertResponse(
RequestResponses storage responses,
uint8 keyServerIndex,
uint8 threshold,
bytes32 response) internal returns (ResponseSupport)
{
// check that servers set is still the same (and all previous responses are valid)
uint256 keyServerSetChangeBlock = KeyServerSet(keyServerSetAddress).getCurrentLastChange();
if (responses.respondedKeyServersCount == 0) {
responses.keyServerSetChangeBlock = keyServerSetChangeBlock;
} else if (responses.keyServerSetChangeBlock != keyServerSetChangeBlock) {
resetResponses(responses, keyServerSetChangeBlock);
}
// check if key server has already responded
uint256 keyServerMask = (uint256(1) << keyServerIndex);
if ((responses.respondedKeyServersMask & keyServerMask) != 0) {
return ResponseSupport.Unconfirmed;
}
// insert response
uint8 responseSupport = responses.responsesSupport[response] + 1;
responses.respondedKeyServersMask |= keyServerMask;
responses.respondedKeyServersCount += 1;
responses.responsesSupport[response] = responseSupport;
if (responseSupport == 1) {
responses.responses.push(response);
}
if (responseSupport >= responses.maxResponseSupport) {
responses.maxResponseSupport = responseSupport;
// check if passed response has received enough support
if (threshold <= responseSupport - 1) {
return ResponseSupport.Confirmed;
}
}
// check if max confirmation CAN receive enough support
uint8 keyServersLeft = keyServersCount() - responses.respondedKeyServersCount;
if (threshold > responses.maxResponseSupport + keyServersLeft - 1) {
return ResponseSupport.Impossible;
}
return ResponseSupport.Unconfirmed;
}
/// Clear responses before removal.
function clearResponses(RequestResponses storage responses) internal {
for (uint256 i = 0; i < responses.responses.length; ++i) {
delete responses.responsesSupport[responses.responses[i]];
}
}
/// Remove request id from array.
function removeRequestKey(bytes32[] storage requests, bytes32 request) internal {
for (uint i = 0; i < requests.length; ++i) {
if (requests[i] == request) {
requests[i] = requests[requests.length - 1];
requests.length = requests.length - 1;
break;
}
}
}
/// Reset responses.
function resetResponses(RequestResponses storage responses, uint256 keyServerSetChangeBlock) private {
clearResponses(responses);
responses.keyServerSetChangeBlock = keyServerSetChangeBlock;
responses.respondedKeyServersMask = 0;
responses.respondedKeyServersCount = 0;
responses.maxResponseSupport = 0;
responses.responses.length = 0;
}
/// Address of KeyServerSet contract.
address private keyServerSetAddress;
/// Balances of key servers.
mapping (address => uint256) private balances;
/// Active requests.
mapping (bytes32 => RequestResponses) private requests;
}
| Return index of key server at given address. | function requireKeyServer(address keyServer) public view returns (uint8) {
return KeyServerSet(keyServerSetAddress).getCurrentKeyServerIndex(keyServer);
}
| 7,281,860 |
./full_match/80001/0x954933B3a3a47F888bfdb178950A8dbe3CB34065/sources/ampersand721.sol | Create a new role identifiers | {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
mapping(uint256 => string) private _ampersandURI;
bytes32 public constant CREATORS_MANAGER_ROLE =
keccak256("CREATORS_MANAGER_ROLE");
bytes32 public constant CREATOR_ROLE = keccak256("CREATOR_ROLE");
pragma solidity ^0.8.10;
constructor() ERC721("Ampersand NFT", "ANFT") {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(CREATORS_MANAGER_ROLE, _msgSender());
_setupRole(CREATOR_ROLE, _msgSender());
_setRoleAdmin(CREATOR_ROLE, CREATORS_MANAGER_ROLE);
}
function createAmpersand(address reciever, string memory _ampersandURI)
public
onlyRole(CREATOR_ROLE)
returns (uint256)
{
uint256 newTokenId = _tokenIds.current();
_tokenIds.increment();
_safeMint(reciever, newTokenId);
_setTokenURI(newTokenId, _ampersandURI);
return newTokenId;
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public override onlyRole(CREATOR_ROLE) {
super.transferFrom(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override onlyRole(CREATOR_ROLE) {
super.safeTransferFrom(from, to, tokenId);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint256 tokenId)
internal
override(ERC721, ERC721URIStorage)
{
super._burn(tokenId);
if (bytes(_ampersandURI[tokenId]).length != 0) {
delete _ampersandURI[tokenId];
}
}
function _burn(uint256 tokenId)
internal
override(ERC721, ERC721URIStorage)
{
super._burn(tokenId);
if (bytes(_ampersandURI[tokenId]).length != 0) {
delete _ampersandURI[tokenId];
}
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable, AccessControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
| 5,625,417 |
./partial_match/1/0x43c6eE9D5B2369C5484f69E2Eb3361466855beDd/sources/FabricaToken.sol | `mintBatch` allows users to mint in bulk/ | function mintBatch(
address[] memory recipients,
uint256[] memory sessionIds,
uint256[] memory amounts,
string[] memory definitions,
string[] memory operatingAgreements,
string[] memory configurations,
address[] memory validators
) public whenNotPaused returns (uint256[] memory ids) {
uint256 supply = 0;
for (uint256 i = 0; i < amounts.length; i++) {
uint256 amount = amounts[i];
require(amount > 0, 'Each amount must be greater than zero');
supply += amount;
}
uint256 size = sessionIds.length;
Property[] memory properties = new Property[](size);
for (uint256 i = 0; i < size; i++) {
properties[i].supply = supply;
properties[i].operatingAgreement = operatingAgreements[i];
properties[i].definition = definitions[i];
properties[i].configuration = configurations[i];
properties[i].validator = validators[i];
}
ids = _mintBatch(recipients, sessionIds, amounts, properties, "");
}
| 2,672,106 |
/*
* Copyright 2020, NTT Communications Corp.
*
* 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.
*/
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.8.0 <0.9.0;
import "@openzeppelin/contracts/token/ERC777/IERC777.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts/utils/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts/utils/introspection/ERC1820Implementer.sol";
import "./MetemcyberUtil.sol";
import {CTIToken, CTIToken_ContractId} from "./CTIToken.sol";
string constant CTIOperator_ContractId = "CTIOperator.sol:CTIOperator";
contract CTIOperator is IERC777Recipient, ERC1820Implementer {
event TokensReceivedCalled(
address from,
bytes data,
address token,
uint256 taskId
);
event TaskAccepted(
address operator,
uint256 taskId,
address token
);
event TaskFinished(
address operator,
uint256 taskId,
address token
);
enum TaskState { Pending, Accepted, Finished, Cancelled }
struct Task {
uint256 taskId;
address token;
address solver;
address seeker;
TaskState state;
}
string public constant contractId = CTIOperator_ContractId;
uint256 public constant contractVersion = 2;
IERC1820Registry private _erc1820 =
IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH =
keccak256("ERC777TokensRecipient");
Task[] private _tasks;
bytes[] private _userData;
mapping (address => address[]) private _tokens; // solver => tokens
function tokensReceived(
address /*operator*/,
address from,
address /*to*/,
uint256 /*amount*/,
bytes calldata userData,
bytes calldata /*operatorData*/
) external override {
IERC777 token = IERC777(msg.sender);
// prepare for accepted().
uint256 taskId = _tasks.length; // zero-based taskId.
_tasks.push(Task({
taskId: taskId,
token: address(token),
solver: address(0),
seeker: from,
state: TaskState.Pending
})
);
_userData.push(userData);
assert(_tasks.length == taskId + 1);
assert(_userData.length == taskId + 1);
emit TokensReceivedCalled(
from,
userData,
address(token),
taskId
);
}
function reemitPendingTasks(address[] memory tokens) public {
for (uint i=0; i<_tasks.length; i++) {
if (_tasks[i].state != TaskState.Pending)
continue;
for (uint j=0; j<tokens.length; j++) {
if (_tasks[i].token == tokens[j]) {
emit TokensReceivedCalled(
_tasks[i].seeker,
_userData[i],
_tasks[i].token,
_tasks[i].taskId
);
break;
}
}
}
}
function recipientFor(address account) public {
_registerInterfaceForAddress(
_TOKENS_RECIPIENT_INTERFACE_HASH, account);
address self = address(this);
if (account == self) {
registerRecipient(self);
}
}
function registerRecipient(address recipient) public {
_erc1820.setInterfaceImplementer(
address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, recipient);
}
function _isRegistered(
address token,
address solver
) internal view returns (bool) {
for (uint i = 0; i < _tokens[solver].length; i++) {
if (_tokens[solver][i] == token)
return true;
}
return false;
}
function listRegistered(address solver) public view returns(address[] memory) {
uint count = 0;
for (uint i = 0; i < _tokens[solver].length; i++) {
if (_tokens[solver][i] != address(0))
count += 1;
}
address[] memory result = new address[](count);
uint j = 0;
for (uint i = 0; i < _tokens[solver].length; i++) {
if (_tokens[solver][i] != address(0))
result[j++] = _tokens[solver][i];
}
return result;
}
function register(address[] memory tokens) public {
if (tokens.length == 0)
return;
for (uint i = 0; i < tokens.length; i++) {
CTIToken token = CTIToken(tokens[i]);
require(
MetemcyberUtil.isSameStrings(
token.contractId(), CTIToken_ContractId),
"not a token address"
);
require(
token.isOperatorFor(msg.sender, token.publisher()),
"not authorized"
);
if (!_isRegistered(tokens[i], msg.sender)) {
uint j = 0;
for (j = 0; j < _tokens[msg.sender].length; j++) {
if (_tokens[msg.sender][j] == address(0)) {
_tokens[msg.sender][j] = tokens[i];
break;
}
}
if (j == _tokens[msg.sender].length)
_tokens[msg.sender].push(tokens[i]);
}
}
}
function unregister(address[] memory tokens) public {
if (tokens.length == 0)
return;
for (uint i = 0; i < tokens.length; i++) {
for (uint j = 0; j < _tokens[msg.sender].length; j++) {
if (_tokens[msg.sender][j] == tokens[i]) {
delete _tokens[msg.sender][j];
break;
}
}
}
}
function checkRegistered(
address[] memory tokens
) public view returns (bool[] memory) {
bool[] memory result = new bool[](tokens.length);
for (uint i = 0; i < tokens.length; i++) {
for (uint j = 0; j < _tokens[msg.sender].length; j++) {
if (_tokens[msg.sender][j] == tokens[i]) {
result[i] = true;
break;
}
}
}
return result;
}
function accepted(uint256 taskId) public {
require(_tasks.length > taskId, "Invalid taskId.");
require(_tasks[taskId].taskId == taskId, "Invalid taskId.");
require(_tasks[taskId].solver == address(0), "Already accepted.");
require(
_isRegistered(_tasks[taskId].token, msg.sender),
"Not registered."
);
CTIToken token = CTIToken(_tasks[taskId].token);
require(
token.isOperatorFor(msg.sender, token.publisher()),
"not authorized"
);
_tasks[taskId].solver = msg.sender;
_tasks[taskId].state = TaskState.Accepted;
emit TaskAccepted(
address(this),
taskId,
_tasks[taskId].token
);
}
function finish(uint256 taskId, string memory data) public {
require(_tasks.length > taskId, "Invalid taskId");
require(_tasks[taskId].solver == msg.sender, "not task's solver");
// send token back to seeker
IERC777 token = IERC777(_tasks[taskId].token);
assert(token.balanceOf(address(this)) > 0);
_tasks[taskId].state = TaskState.Finished;
token.send(_tasks[taskId].seeker, 1, bytes(data));
delete _userData[taskId];
emit TaskFinished(
address(this),
taskId,
_tasks[taskId].token
);
}
function cancelTask(uint256 taskId) public {
require(_tasks.length > taskId, "Invalid taskId");
require(_tasks[taskId].seeker == msg.sender, "Not token sender");
require(_tasks[taskId].state == TaskState.Pending, "Not pending");
IERC777 token = IERC777(_tasks[taskId].token);
assert(token.balanceOf(address(this)) > 0);
_tasks[taskId].state = TaskState.Cancelled;
token.send(_tasks[taskId].seeker, 1, "");
delete _userData[taskId];
emit TaskFinished(
address(this),
taskId,
_tasks[taskId].token
);
}
function latest() external view returns (Task memory) {
require(_tasks.length > 0, "No tasks");
return _tasks[_tasks.length-1];
}
function history(
address token,
address seeker,
uint limit,
uint offset
) external view returns (Task[] memory) {
require(limit > 0, "Specify more than 1");
if (_tasks.length == 0)
return new Task[](0);
// Use new keyword to create dynamic length array
Task[] memory matchTasks = new Task[](limit);
uint count = 0;
for (uint i = _tasks.length; i > 0 && count < limit; i--) {
if ((seeker == address(0) || _tasks[i - 1].seeker == seeker) &&
(token == address(0) || _tasks[i - 1].token == token)) {
if (offset > 0) {
offset--;
continue;
}
matchTasks[count] = _tasks[i - 1];
count++;
}
}
if (count < limit){
Task[] memory sliceTasks = new Task[](count);
for (uint i = 0; i < count; i++) {
sliceTasks[i] = matchTasks[i];
}
return sliceTasks;
} else {
return matchTasks;
}
}
}
| Use new keyword to create dynamic length array | function history(
address token,
address seeker,
uint limit,
uint offset
) external view returns (Task[] memory) {
require(limit > 0, "Specify more than 1");
if (_tasks.length == 0)
return new Task[](0);
Task[] memory matchTasks = new Task[](limit);
uint count = 0;
for (uint i = _tasks.length; i > 0 && count < limit; i--) {
if ((seeker == address(0) || _tasks[i - 1].seeker == seeker) &&
(token == address(0) || _tasks[i - 1].token == token)) {
if (offset > 0) {
offset--;
continue;
}
matchTasks[count] = _tasks[i - 1];
count++;
}
}
if (count < limit){
Task[] memory sliceTasks = new Task[](count);
for (uint i = 0; i < count; i++) {
sliceTasks[i] = matchTasks[i];
}
return sliceTasks;
return matchTasks;
}
}
| 15,847,503 |
/**
*Submitted for verification at Etherscan.io on 2021-07-28
*/
/**
*Submitted for verification at Etherscan.io on 2021-07-13
*/
pragma solidity ^0.7.4;
// SPDX-License-Identifier: MIT
/*
* @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, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
/**
* @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;
}
}
/*
Proxy registry; keeps a mapping of AuthenticatedProxy contracts and mapping of contracts authorized to access them.
Abstracted away from the Exchange (a) to reduce Exchange attack surface and (b) so that the Exchange contract can be upgraded without users needing to transfer assets to new proxies.
*/
contract ProxyRegistry is Ownable {
/* DelegateProxy implementation contract. Must be initialized. */
address public delegateProxyImplementation;
/* Authenticated proxies by user. */
mapping(address => OwnableDelegateProxy) public proxies;
/* Contracts pending access. */
mapping(address => uint) public pending;
/* Contracts allowed to call those proxies. */
mapping(address => bool) public contracts;
/* Delay period for adding an authenticated contract.
This mitigates a particular class of potential attack on the Erax DAO (which owns this registry) - if at any point the value of assets held by proxy contracts exceeded the value of half the WYV supply (votes in the DAO),
a malicious but rational attacker could buy half the Erax and grant themselves access to all the proxy contracts. A delay period renders this attack nonthreatening - given two weeks, if that happened, users would have
plenty of time to notice and transfer their assets.
*/
uint public DELAY_PERIOD = 2 weeks;
/**
* Start the process to enable access for specified contract. Subject to delay period.
*
* @dev ProxyRegistry owner only
* @param addr Address to which to grant permissions
*/
function startGrantAuthentication (address addr)
public
onlyOwner
{
require(!contracts[addr] && pending[addr] == 0,"31");
pending[addr] = block.timestamp;
}
/**
* End the process to nable access for specified contract after delay period has passed.
*
* @dev ProxyRegistry owner only
* @param addr Address to which to grant permissions
*/
function endGrantAuthentication (address addr)
public
onlyOwner
{
require(!contracts[addr] && pending[addr] != 0 && ((pending[addr] + DELAY_PERIOD) < block.timestamp),"32");
pending[addr] = 0;
contracts[addr] = true;
}
/**
* Revoke access for specified contract. Can be done instantly.
*
* @dev ProxyRegistry owner only
* @param addr Address of which to revoke permissions
*/
function revokeAuthentication (address addr)
public
onlyOwner
{
contracts[addr] = false;
}
/**
Joe add
**/
function grantAuthentication (address addr)
public
onlyOwner
{
require(!contracts[addr],"33");
contracts[addr] = true;
}
/**
* Register a proxy contract with this registry
*
* @dev Must be called by the user which the proxy is for, creates a new AuthenticatedProxy
* @return proxy New AuthenticatedProxy contract
*/
function registerProxy()
public
returns (OwnableDelegateProxy proxy)
{
require(address(proxies[msg.sender]) == address(0),"34");
proxy = new OwnableDelegateProxy(msg.sender, delegateProxyImplementation, abi.encodeWithSignature("initialize(address,address)", msg.sender, address(this)));
proxies[msg.sender] = proxy;
return proxy;
}
}
/*
Token recipient. Modified very slightly from the example on http://ethereum.org/dao (just to index log parameters).
*/
/**
* @title TokenRecipient
* @author Project Erax Developers
*/
contract TokenRecipient {
event ReceivedEther(address indexed sender, uint amount);
event ReceivedTokens(address indexed from, uint256 value, address indexed token, bytes extraData);
/**
* @dev Receive tokens and generate a log event
* @param from Address from which to transfer tokens
* @param value Amount of tokens to transfer
* @param token Address of token
* @param extraData Additional data to log
*/
function receiveApproval(address from, uint256 value, address token, bytes memory extraData) public {
ERC20 t = ERC20(token);
require(t.transferFrom(from, address(this), value),"4");
emit ReceivedTokens(from, value, token, extraData);
}
/**
* @dev Receive Ether and generate a log event
*/
receive() payable external {
emit ReceivedEther(msg.sender, msg.value);
}
}
/**
* @title Proxy
* @dev Gives the possibility to delegate any call to a foreign implementation.
*/
abstract contract Proxy {
/**
* @dev Tells the address of the implementation where every call will be delegated.
* @return address of the implementation to which it will be delegated
*/
function implementation() public virtual view returns (address);
/**
* @dev Tells the type of proxy (EIP 897)
* @return proxyTypeId Type of proxy, 2 for upgradeable proxy
*/
function proxyType() public virtual pure returns (uint256 proxyTypeId);
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
fallback () payable external {
address _impl = implementation();
require(_impl != address(0),"40");
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
/**
* @title OwnedUpgradeabilityStorage
* @dev This contract keeps track of the upgradeability owner
*/
contract OwnedUpgradeabilityStorage is Proxy{
// Current implementation
address internal _implementation;
// Owner of the contract
address private _upgradeabilityOwner;
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function upgradeabilityOwner() public view returns (address) {
return _upgradeabilityOwner;
}
/**
* @dev Sets the address of the owner
*/
function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal {
_upgradeabilityOwner = newUpgradeabilityOwner;
}
/**
* @dev Tells the address of the current implementation
* @return address of the current implementation
*/
function implementation() public override view returns (address) {
return _implementation;
}
/**
* @dev Tells the proxy type (EIP 897)
* @return proxyTypeId Proxy type, 2 for forwarding proxy
*/
function proxyType() public override pure returns (uint256 proxyTypeId) {
return 2;
}
}
/*
Proxy contract to hold access to assets on behalf of a user (e.g. ERC20 approve) and execute calls under particular conditions.
*/
/**
* @title AuthenticatedProxy
* @author Project Erax Developers
*/
contract AuthenticatedProxy is TokenRecipient, OwnedUpgradeabilityStorage {
/* Whether initialized. */
bool initialized = false;
/* Address which owns this proxy. */
address public user;
/* Associated registry with contract authentication information. */
ProxyRegistry public registry;
/* Whether access has been revoked. */
bool public revoked;
/* Delegate call could be used to atomically transfer multiple assets owned by the proxy contract with one order. */
enum HowToCall { Call, DelegateCall }
/* Event fired when the proxy access is revoked or unrevoked. */
event Revoked(bool revoked);
/**
* Initialize an AuthenticatedProxy
*
* @param addrUser Address of user on whose behalf this proxy will act
* @param addrRegistry Address of ProxyRegistry contract which will manage this proxy
*/
function initialize (address addrUser, ProxyRegistry addrRegistry)
public
{
require(!initialized,"26");
initialized = true;
user = addrUser;
registry = addrRegistry;
}
/**
* Set the revoked flag (allows a user to revoke ProxyRegistry access)
*
* @dev Can be called by the user only
* @param revoke Whether or not to revoke access
*/
function setRevoke(bool revoke)
public
{
require(msg.sender == user,"27");
revoked = revoke;
emit Revoked(revoke);
}
/**
* Execute a message call from the proxy contract
*
* @dev Can be called by the user, or by a contract authorized by the registry as long as the user has not revoked access
* @param dest Address to which the call will be sent
* @param howToCall Which kind of call to make
* @param callData Calldata to send
* @return result Result of the call (success or failure)
*/
function proxy(address dest, HowToCall howToCall, bytes memory callData)
public
returns (bool result)
{
require(msg.sender == user || (!revoked && registry.contracts(msg.sender)),"28");
if (howToCall == HowToCall.Call) {
(result, ) = dest.call(callData);
} else if (howToCall == HowToCall.DelegateCall) {
(result, ) = dest.delegatecall(callData);
}
return result;
}
/**
* Execute a message call and assert success
*
* @dev Same functionality as `proxy`, just asserts the return value
* @param dest Address to which the call will be sent
* @param howToCall What kind of call to make
* @param callData Calldata to send
*/
function proxyAssert(address dest, HowToCall howToCall, bytes memory callData)
public
{
require(proxy(dest, howToCall, callData),"29");
}
}
/**
* @title OwnedUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with basic authorization control functionalities
*/
contract OwnedUpgradeabilityProxy is OwnedUpgradeabilityStorage {
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event ProxyOwnershipTransferred(address previousOwner, address newOwner);
/**
* @dev This event will be emitted every time the implementation gets upgraded
* @param implementation representing the address of the upgraded implementation
*/
event Upgraded(address indexed implementation);
/**
* @dev Upgrades the implementation address
* @param implementation representing the address of the new implementation to be set
*/
function _upgradeTo(address implementation) internal {
require(_implementation != implementation,"36");
_implementation = implementation;
emit Upgraded(implementation);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyProxyOwner() {
require(msg.sender == proxyOwner(),"37");
_;
}
/**
* @dev Tells the address of the proxy owner
* @return the address of the proxy owner
*/
function proxyOwner() public view returns (address) {
return upgradeabilityOwner();
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferProxyOwnership(address newOwner) public onlyProxyOwner {
require(newOwner != address(0),"38");
emit ProxyOwnershipTransferred(proxyOwner(), newOwner);
setUpgradeabilityOwner(newOwner);
}
/**
* @dev Allows the upgradeability owner to upgrade the current implementation of the proxy.
* @param implementation representing the address of the new implementation to be set.
*/
function upgradeTo(address implementation) public onlyProxyOwner {
_upgradeTo(implementation);
}
/**
* @dev Allows the upgradeability owner to upgrade the current implementation of the proxy
* and delegatecall the new implementation for initialization.
* @param implementation representing the address of the new implementation to be set.
* @param data represents the msg.data to bet sent in the low level call. This parameter may include the function
* signature of the implementation to be called with the needed payload
*/
function upgradeToAndCall(address implementation, bytes memory data) payable public onlyProxyOwner {
upgradeTo(implementation);
(bool result, ) = address(this).delegatecall(data);
require(result,"39");
}
}
/*
EraxOwnableDelegateProxy
*/
contract OwnableDelegateProxy is OwnedUpgradeabilityProxy {
constructor(address owner, address initialImplementation, bytes memory callData)
{
setUpgradeabilityOwner(owner);
_upgradeTo(initialImplementation);
(bool result, ) = initialImplementation.delegatecall(callData);
require(result,"30");
}
}
/*
Token transfer proxy. Uses the authentication table of a ProxyRegistry contract to grant ERC20 `transferFrom` access.
This means that users only need to authorize the proxy contract once for all future protocol versions.
*/
contract TokenTransferProxy {
/* Authentication registry. */
ProxyRegistry public registry;
/**
* Call ERC20 `transferFrom`
*
* @dev Authenticated contract only
* @param token ERC20 token address
* @param from From address
* @param to To address
* @param amount Transfer amount
*/
function transferFrom(address token, address from, address to, uint amount)
public
returns (bool)
{
require(registry.contracts(msg.sender),"35");
return ERC20(token).transferFrom(from, to, amount);
}
}
/*
Various functions for manipulating arrays in Solidity.
This library is completely inlined and does not need to be deployed or linked.
*/
/**
* @title ArrayUtils
* @author Project Erax Developers
*/
library ArrayUtils {
/**
* Replace bytes in an array with bytes in another array, guarded by a bitmask
* Efficiency of this function is a bit unpredictable because of the EVM's word-specific model (arrays under 32 bytes will be slower)
*
* @dev Mask must be the size of the byte array. A nonzero byte means the byte array can be changed.
* @param array The original array
* @param desired The target array
* @param mask The mask specifying which bits can be changed
* return The updated byte array (the parameter will be modified inplace)
*/
function guardedArrayReplace(bytes memory array, bytes memory desired, bytes memory mask)
internal
pure
{
require(array.length == desired.length,"2");
require(array.length == mask.length,"3");
uint words = array.length / 0x20;
uint index = words * 0x20;
assert(index / 0x20 == words);
uint i;
for (i = 0; i < words; i++) {
/* Conceptually: array[i] = (!mask[i] && array[i]) || (mask[i] && desired[i]), bitwise in word chunks. */
assembly {
let commonIndex := mul(0x20, add(1, i))
let maskValue := mload(add(mask, commonIndex))
mstore(add(array, commonIndex), or(and(not(maskValue), mload(add(array, commonIndex))), and(maskValue, mload(add(desired, commonIndex)))))
}
}
/* Deal with the last section of the byte array. */
if (words > 0) {
/* This overlaps with bytes already set but is still more efficient than iterating through each of the remaining bytes individually. */
i = words;
assembly {
let commonIndex := mul(0x20, add(1, i))
let maskValue := mload(add(mask, commonIndex))
mstore(add(array, commonIndex), or(and(not(maskValue), mload(add(array, commonIndex))), and(maskValue, mload(add(desired, commonIndex)))))
}
} else {
/* If the byte array is shorter than a word, we must unfortunately do the whole thing bytewise.
(bounds checks could still probably be optimized away in assembly, but this is a rare case) */
for (i = index; i < array.length; i++) {
array[i] = ((mask[i] ^ 0xff) & array[i]) | (mask[i] & desired[i]);
}
}
}
/**
* Test if two arrays are equal
* Source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
*
* @dev Arrays must be of equal length, otherwise will return false
* @param a First array
* @param b Second array
* @return Whether or not all bytes in the arrays are equal
*/
function arrayEq(bytes memory a, bytes memory b)
internal
pure
returns (bool)
{
bool success = true;
assembly {
let length := mload(a)
// if lengths don't match the arrays are not equal
switch eq(length, mload(b))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(a, 0x20)
let end := add(mc, length)
for {
let cc := add(b, 0x20)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
} eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
/**
* Unsafe write byte array into a memory location
*
* @param index Memory location
* @param source Byte array to write
* @return End memory index
*/
function unsafeWriteBytes(uint index, bytes memory source)
internal
pure
returns (uint)
{
if (source.length > 0) {
assembly {
let length := mload(source)
let end := add(source, add(0x20, length))
let arrIndex := add(source, 0x20)
let tempIndex := index
for { } eq(lt(arrIndex, end), 1) {
arrIndex := add(arrIndex, 0x20)
tempIndex := add(tempIndex, 0x20)
} {
mstore(tempIndex, mload(arrIndex))
}
index := add(index, length)
}
}
return index;
}
/**
* Unsafe write address into a memory location
*
* @param index Memory location
* @param source Address to write
* @return End memory index
*/
function unsafeWriteAddress(uint index, address source)
internal
pure
returns (uint)
{
//0.8.3
//uint256 conv = uint256(uint160((source))) << 0x60;
uint256 conv = uint256(source) << 0x60;
assembly {
mstore(index, conv)
index := add(index, 0x14)
}
return index;
}
/**
* Unsafe write uint into a memory location
*
* @param index Memory location
* @param source uint to write
* @return End memory index
*/
function unsafeWriteUint(uint index, uint source)
internal
pure
returns (uint)
{
assembly {
mstore(index, source)
index := add(index, 0x20)
}
return index;
}
/**
* Unsafe write uint8 into a memory location
*
* @param index Memory location
* @param source uint8 to write
* @return End memory index
*/
function unsafeWriteUint8(uint index, uint8 source)
internal
pure
returns (uint)
{
assembly {
mstore8(index, source)
index := add(index, 0x1)
}
return index;
}
}
/*
Simple contract extension to provide a contract-global reentrancy guard on functions.
*/
/**
* @title ReentrancyGuarded
* @author Project Erax Developers
*/
contract ReentrancyGuarded {
bool reentrancyLock = false;
/* Prevent a contract function from being reentrant-called. */
modifier reentrancyGuard {
if (reentrancyLock) {
revert();
}
reentrancyLock = true;
_;
reentrancyLock = false;
}
}
/*
Abstract over fixed-price sales and Dutch auctions, with the intent of easily supporting additional methods of sale later.
Separated into a library for convenience, all the functions are inlined.
*/
//import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @title SaleKindInterface
* @author Project Erax Developers
*/
library SaleKindInterface {
/**
* Side: buy or sell.
*/
enum Side { Buy, Sell }
/**
* Currently supported kinds of sale: fixed price, Dutch auction.
* English auctions cannot be supported without stronger escrow guarantees.
* Future interesting options: Vickrey auction, nonlinear Dutch auctions.
*/
enum SaleKind { FixedPrice, DutchAuction }
/**
* @dev Check whether the parameters of a sale are valid
* @param saleKind Kind of sale
* @param expirationTime Order expiration time
* @return Whether the parameters were valid
*/
function validateParameters(SaleKind saleKind, uint expirationTime)
pure
internal
returns (bool)
{
/* Auctions must have a set expiration date. */
return (saleKind == SaleKind.FixedPrice || expirationTime > 0);
}
/**
* @dev Return whether or not an order can be settled
* @dev Precondition: parameters have passed validateParameters
* @param listingTime Order listing time
* @param expirationTime Order expiration time
*/
function canSettleOrder(uint listingTime, uint expirationTime)
view
internal
returns (bool)
{
return (listingTime < block.timestamp) && (expirationTime == 0 || block.timestamp < expirationTime);
}
/**
* @dev Calculate the settlement price of an order
* @dev Precondition: parameters have passed validateParameters.
* @param side Order side
* @param saleKind Method of sale
* @param basePrice Order base price
* @param extra Order extra price data
* @param listingTime Order listing time
* @param expirationTime Order expiration time
*/
function calculateFinalPrice(Side side, SaleKind saleKind, uint basePrice, uint extra, uint listingTime, uint expirationTime)
view
internal
returns (uint finalPrice)
{
if (saleKind == SaleKind.FixedPrice) {
return basePrice;
} else if (saleKind == SaleKind.DutchAuction) {
uint diff = SafeMath.div(SafeMath.mul(extra, SafeMath.sub(block.timestamp, listingTime)), SafeMath.sub(expirationTime, listingTime));
if (side == Side.Sell) {
/* Sell-side - start price: basePrice. End price: basePrice - extra. */
return SafeMath.sub(basePrice, diff);
} else {
/* Buy-side - start price: basePrice. End price: basePrice + extra. */
return SafeMath.add(basePrice, diff);
}
}
}
}
/**
* @title ExchangeCore
* @author Project Erax Developers
*/
contract ExchangeCore is ReentrancyGuarded, Ownable {
/* User registry. */
ProxyRegistry public registry;
/* Token transfer proxy. */
TokenTransferProxy public tokenTransferProxy;
/* Cancelled / finalized orders, by hash. */
mapping(bytes32 => bool) public cancelledOrFinalized;
/* The asset contract which use standard version. */
mapping(address => bool) public sharedProxyAddresses;
uint public maximumOriginatorFee = 0x3e8;
uint public maximumAgentFee = 0xfa0;
/* Fee method: protocol fee or split fee. */
enum FeeMethod { ProtocolFee, SplitFee }
/* Inverse basis point. */
uint public constant INVERSE_BASIS_POINT = 10000;
/* An ECDSA signature. */
struct Sig {
/* v parameter */
uint8 v;
/* r parameter */
bytes32 r;
/* s parameter */
bytes32 s;
}
/* An order on the exchange. */
struct Order {
/* Exchange address, intended as a versioning mechanism. */
address exchange;
/* Order maker address. */
address maker;
/* Order taker address, if specified. */
address taker;
/* Maker relayer fee of the order, unused for taker order. */
uint makerRelayerFee;
/* Taker relayer fee of the order, or maximum taker fee for a taker order. */
uint takerRelayerFee;
/* Maker protocol fee of the order, unused for taker order. */
uint makerProtocolFee;
/* Taker protocol fee of the order, or maximum taker fee for a taker order. */
uint takerProtocolFee;
/* Order fee recipient or zero address for taker order. */
address feeRecipient;
/* Fee method (protocol token or split fee). */
FeeMethod feeMethod;
/* Side (buy/sell). */
SaleKindInterface.Side side;
/* Kind of sale. */
SaleKindInterface.SaleKind saleKind;
/* Target. */
address target;
/* HowToCall. */
AuthenticatedProxy.HowToCall howToCall;
/* Calldata. */
bytes callData;
/* Calldata replacement pattern, or an empty byte array for no replacement. */
bytes replacementPattern;
/* Agent who can help sell the good. */
address agent;
/* Agent fee nee to be charged. */
uint agentFee;
/* Token used to pay for the order, or the zero-address as a sentinel value for Ether. */
address paymentToken;
/* Base price of the order (in paymentTokens). */
uint basePrice;
/* Auction extra parameter - minimum bid increment for English auctions, starting/ending price difference. */
uint extra;
/* Listing timestamp. */
uint listingTime;
/* Expiration timestamp - 0 for no expiry. */
uint expirationTime;
/* Order salt, used to prevent duplicate hashes. */
uint salt;
}
event OrderCancelled (bytes32 indexed hash);
event OrdersMatched (bytes32 buyHash, bytes32 sellHash, address indexed maker, address indexed taker, uint price, bytes32 indexed metadata);
/**
* @dev Allows owner to add a shared proxy address
*/
function addSharedProxyAddress(address _address) public onlyOwner {
sharedProxyAddresses[_address] = true;
}
/**
* @dev Allows owner to remove a shared proxy address
*/
function removeSharedProxyAddress(address _address) public onlyOwner {
delete sharedProxyAddresses[_address];
}
/**
* @dev Change the maximum originator fee paid to originator (owner only)
* @param _maximumOriginatorFee New fee to set in basis points
*/
function changeMaximumOriginatorFee(uint _maximumOriginatorFee)
public
onlyOwner
{
maximumOriginatorFee = _maximumOriginatorFee;
}
/**
* @dev Change the maximum agent fee paid to the agent (owner only)
* @param _maximumAgentFee New fee to set in basis points
*/
function changeMaximumAgentFee(uint _maximumAgentFee)
public
onlyOwner
{
maximumAgentFee = _maximumAgentFee;
}
/**
* @dev Transfer tokens
* @param token Token to transfer
* @param from Address to charge fees
* @param to Address to receive fees
* @param amount Amount of protocol tokens to charge
*/
function transferTokens(address token, address from, address to, uint amount)
internal
{
if (amount > 0) {
require(tokenTransferProxy.transferFrom(token, from, to, amount),"5");
}
}
/**
* Calculate size of an order struct when tightly packed
*
* @param order Order to calculate size of
* @return Size in bytes
*/
function sizeOf(Order memory order)
internal
pure
returns (uint)
{
return ((0x14 * 7) + (0x20 * 10) + 4 + order.callData.length + order.replacementPattern.length);
}
/**
* @dev Hash an order, returning the canonical order hash, without the message prefix
* @param order Order to hash
* @return hash Hash of order
*/
function hashOrder(Order memory order)
internal
pure
returns (bytes32 hash)
{
/* Unfortunately abi.encodePacked doesn't work here, stack size constraints. */
uint size = sizeOf(order);
bytes memory array = new bytes(size);
uint index;
assembly {
index := add(array, 0x20)
}
index = ArrayUtils.unsafeWriteAddress(index, order.exchange);
index = ArrayUtils.unsafeWriteAddress(index, order.maker);
index = ArrayUtils.unsafeWriteAddress(index, order.taker);
index = ArrayUtils.unsafeWriteUint(index, order.makerRelayerFee);
index = ArrayUtils.unsafeWriteUint(index, order.takerRelayerFee);
index = ArrayUtils.unsafeWriteUint(index, order.makerProtocolFee);
index = ArrayUtils.unsafeWriteUint(index, order.takerProtocolFee);
index = ArrayUtils.unsafeWriteAddress(index, order.feeRecipient);
index = ArrayUtils.unsafeWriteUint8(index, uint8(order.feeMethod));
index = ArrayUtils.unsafeWriteUint8(index, uint8(order.side));
index = ArrayUtils.unsafeWriteUint8(index, uint8(order.saleKind));
index = ArrayUtils.unsafeWriteAddress(index, order.target);
index = ArrayUtils.unsafeWriteUint8(index, uint8(order.howToCall));
index = ArrayUtils.unsafeWriteBytes(index, order.callData);
index = ArrayUtils.unsafeWriteBytes(index, order.replacementPattern);
index = ArrayUtils.unsafeWriteAddress(index, order.agent);
index = ArrayUtils.unsafeWriteUint(index, order.agentFee);
index = ArrayUtils.unsafeWriteAddress(index, order.paymentToken);
index = ArrayUtils.unsafeWriteUint(index, order.basePrice);
index = ArrayUtils.unsafeWriteUint(index, order.extra);
index = ArrayUtils.unsafeWriteUint(index, order.listingTime);
index = ArrayUtils.unsafeWriteUint(index, order.expirationTime);
index = ArrayUtils.unsafeWriteUint(index, order.salt);
assembly {
hash := keccak256(add(array, 0x20), size)
}
return hash;
}
/**
* @dev Hash an order, returning the hash that a client must sign, including the standard message prefix
* @param order Order to hash
* @return Hash of message prefix and order hash per Ethereum format
*/
function hashToSign(Order memory order)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hashOrder(order)));
}
/**
* @dev Assert an order is valid and return its hash
* @param order Order to validate
* @param sig ECDSA signature
*/
function requireValidOrder(Order memory order, Sig memory sig)
internal
view
returns (bytes32)
{
bytes32 hash = hashToSign(order);
require(validateOrder(hash, order, sig),"6");
return hash;
}
/**
* @dev Validate order parameters (does *not* check signature validity)
* @param order Order to validate
*/
function validateOrderParameters(Order memory order)
internal
view
returns (bool)
{
/* Order must be targeted at this protocol version (this Exchange contract). */
if (order.exchange != address(this)) {
return false;
}
/* Order must possess valid sale kind parameter combination. */
if (!SaleKindInterface.validateParameters(order.saleKind, order.expirationTime)) {
return false;
}
return true;
}
/**
* @dev Validate a provided previously approved / signed order, hash, and signature.
* @param hash Order hash (already calculated, passed to avoid recalculation)
* @param order Order to validate
* @param sig ECDSA signature
*/
function validateOrder(bytes32 hash, Order memory order, Sig memory sig)
internal
view
returns (bool)
{
/* Not done in an if-conditional to prevent unnecessary ecrecover evaluation, which seems to happen even though it should short-circuit. */
/* Order must have valid parameters. */
if (!validateOrderParameters(order)) {
return false;
}
/* Order must have not been canceled or already filled. */
if (cancelledOrFinalized[hash]) {
return false;
}
/* or (b) ECDSA-signed by maker. */
if (ecrecover(hash, sig.v, sig.r, sig.s) == order.maker) {
return true;
}
return false;
}
/**
* @dev Cancel an order, preventing it from being matched. Must be called by the maker of the order
* @param order Order to cancel
* @param sig ECDSA signature
*/
function cancelOrder(Order memory order, Sig memory sig)
internal
{
/* CHECKS */
/* Calculate order hash. */
bytes32 hash = requireValidOrder(order, sig);
/* Assert sender is authorized to cancel order. */
require(msg.sender == order.maker,"9");
/* EFFECTS */
/* Mark order as cancelled, preventing it from being matched. */
cancelledOrFinalized[hash] = true;
/* Log cancel event. */
emit OrderCancelled(hash);
}
/**
* @dev Calculate the current price of an order (convenience function)
* @param order Order to calculate the price of
* @return The current price of the order
*/
function calculateCurrentPrice (Order memory order)
internal
view
returns (uint)
{
return SaleKindInterface.calculateFinalPrice(order.side, order.saleKind, order.basePrice, order.extra, order.listingTime, order.expirationTime);
}
/**
* @dev Calculate the price two orders would match at, if in fact they would match (otherwise fail)
* @param buy Buy-side order
* @param sell Sell-side order
* @return Match price
*/
function calculateMatchPrice(Order memory buy, Order memory sell)
view
internal
returns (uint)
{
/* Calculate sell price. */
uint sellPrice = SaleKindInterface.calculateFinalPrice(sell.side, sell.saleKind, sell.basePrice, sell.extra, sell.listingTime, sell.expirationTime);
/* Calculate buy price. */
uint buyPrice = SaleKindInterface.calculateFinalPrice(buy.side, buy.saleKind, buy.basePrice, buy.extra, buy.listingTime, buy.expirationTime);
/* Require price cross. */
require(buyPrice >= sellPrice,"10");
/* Maker/taker priority. */
return sell.feeRecipient != address(0) ? sellPrice : buyPrice;
}
function getOriginator(bytes memory _callData)
internal
returns (address)
{
uint originator;
assembly {
originator := mload(add(_callData, 0x64))
}
return address(originator >> 96);
}
function getOriginatorFee(bytes memory _callData)
internal
returns (uint)
{
uint originatorFee;
assembly {
originatorFee := mload(add(_callData, 0x78))
}
return originatorFee >> 232;
}
/**
* @dev Execute all ERC20 token / Ether transfers associated with an order match (fees and buyer => seller transfer)
* @param buy Buy-side order
* @param sell Sell-side order
*/
function executeFundsTransfer(Order memory buy, Order memory sell)
internal
returns (uint)
{
/* Only payable in the special case of unwrapped Ether. */
if (sell.paymentToken != address(0)) {
require(msg.value == 0,"11");
}
/* Calculate match price. */
uint price = calculateMatchPrice(buy, sell);
require(price > 0, "40");
/* If paying using a token (not Ether), transfer tokens. This is done prior to fee payments to that a seller will have tokens before being charged fees. */
if (sell.paymentToken != address(0)) {
transferTokens(sell.paymentToken, buy.maker, sell.maker, price);
}else{
/* Special-case Ether, order must be matched by buyer. */
require(msg.value >= price,"17");
}
/* We need seller to pay the fee */
require (sell.feeRecipient != address(0),"12");
require (sell.makerRelayerFee >= 0,"13");
uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT);
uint fee = makerRelayerFee;
uint agentFee;
uint originatorFee;
address originator;
if(sell.agent!= address(0) && sell.agentFee > 0){
require(sell.agentFee <= maximumAgentFee, "43");
agentFee = SafeMath.div(SafeMath.mul(sell.agentFee, price), INVERSE_BASIS_POINT);
fee = SafeMath.add(fee, agentFee);
}
if (sharedProxyAddresses[sell.target]) {
originatorFee = getOriginatorFee(sell.callData);
if(originatorFee > 0){
require(originatorFee <= maximumOriginatorFee, "41");
originator = getOriginator(sell.callData);
originatorFee = SafeMath.div(SafeMath.mul(originatorFee, price), INVERSE_BASIS_POINT);
fee = SafeMath.add(fee, originatorFee);
}
}
/*The seller received must be greater than 0*/
require (price > fee,"46");
if (sell.paymentToken == address(0)) {
/* charge fee */
payable(sell.feeRecipient).transfer(makerRelayerFee);
if(agentFee>0){
payable(sell.agent).transfer(agentFee);
}
if(originatorFee>0){
payable(originator).transfer(originatorFee);
}
/* safe math will ensure price > fee*/
payable(sell.maker).transfer(SafeMath.sub(price, fee));
/* Allow overshoot for variable-price auctions, refund difference. */
uint diff = SafeMath.sub(msg.value, price);
if (diff > 0) {
payable(buy.maker).transfer(diff);
}
}else{
/* charge fee */
transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee);
if(agentFee>0){
transferTokens(sell.paymentToken, sell.maker, payable(sell.agent), agentFee);
}
if(originatorFee>0){
transferTokens(sell.paymentToken, sell.maker, originator, originatorFee);
}
}
/* This contract should never hold Ether, however, we cannot assert this, since it is impossible to prevent anyone from sending Ether e.g. with selfdestruct. */
return price;
}
/**
* @dev Return whether or not two orders can be matched with each other by basic parameters (does not check order signatures / calldata or perform static calls)
* @param buy Buy-side order
* @param sell Sell-side order
* @return Whether or not the two orders can be matched
*/
function ordersCanMatch(Order memory buy, Order memory sell)
internal
view
returns (bool)
{
return (
/* Must be opposite-side. */
(buy.side == SaleKindInterface.Side.Buy && sell.side == SaleKindInterface.Side.Sell) &&
/* Must use same fee method. */
(buy.feeMethod == sell.feeMethod) &&
/* Must use same payment token. */
(buy.paymentToken == sell.paymentToken) &&
/* Must match maker/taker addresses. */
(sell.taker == address(0) || sell.taker == buy.maker) &&
(buy.taker == address(0) || buy.taker == sell.maker) &&
/* One must be maker and the other must be taker (no bool XOR in Solidity). */
((sell.feeRecipient == address(0) && buy.feeRecipient != address(0)) || (sell.feeRecipient != address(0) && buy.feeRecipient == address(0))) &&
/* Must match target. */
(buy.target == sell.target) &&
/* Must match howToCall. */
(buy.howToCall == sell.howToCall) &&
/* Buy-side order must be settleable. */
SaleKindInterface.canSettleOrder(buy.listingTime, buy.expirationTime) &&
/* Sell-side order must be settleable. */
SaleKindInterface.canSettleOrder(sell.listingTime, sell.expirationTime)
);
}
/**
* @dev Atomically match two orders, ensuring validity of the match, and execute all associated state transitions. Protected against reentrancy by a contract-global lock.
* @param buy Buy-side order
* @param buySig Buy-side order signature
* @param sell Sell-side order
* @param sellSig Sell-side order signature
*/
function atomicMatch(Order memory buy, Sig memory buySig, Order memory sell, Sig memory sellSig, bytes32 metadata)
internal
reentrancyGuard
{
/* CHECKS */
/* Ensure buy order validity and calculate hash if necessary. */
bytes32 buyHash;
if (buy.maker == msg.sender) {
require(validateOrderParameters(buy),"18");
} else {
buyHash = requireValidOrder(buy, buySig);
}
/* Ensure sell order validity and calculate hash if necessary. */
bytes32 sellHash;
if (sell.maker == msg.sender) {
require(validateOrderParameters(sell),"19");
} else {
sellHash = requireValidOrder(sell, sellSig);
}
/* Must be matchable. */
require(ordersCanMatch(buy, sell),"20");
/* Target must exist (prevent malicious selfdestructs just prior to order settlement). */
uint size;
address target = sell.target;
assembly {
size := extcodesize(target)
}
require(size > 0,"21");
/* Must match calldata after replacement, if specified. */
if (buy.replacementPattern.length > 0) {
ArrayUtils.guardedArrayReplace(buy.callData, sell.callData, buy.replacementPattern);
}
if (sell.replacementPattern.length > 0) {
ArrayUtils.guardedArrayReplace(sell.callData, buy.callData, sell.replacementPattern);
}
require(ArrayUtils.arrayEq(buy.callData, sell.callData),"22");
/* Retrieve delegateProxy contract. */
OwnableDelegateProxy delegateProxy = registry.proxies(sell.maker);
/* Proxy must exist. */
require(address(delegateProxy) != address(0),"23");
/* Assert implementation. */
require(delegateProxy.implementation() == registry.delegateProxyImplementation(),"24");
/* Access the passthrough AuthenticatedProxy. */
AuthenticatedProxy proxy = AuthenticatedProxy(payable(delegateProxy));
/* EFFECTS */
/* Mark previously signed or approved orders as finalized. */
if (msg.sender != buy.maker) {
cancelledOrFinalized[buyHash] = true;
}
if (msg.sender != sell.maker) {
cancelledOrFinalized[sellHash] = true;
}
/* INTERACTIONS */
/* Execute funds transfer and pay fees. */
uint price = executeFundsTransfer(buy, sell);
/* Execute specified call through proxy. */
require(proxy.proxy(sell.target, sell.howToCall, sell.callData),"25");
/* Log match event. */
emit OrdersMatched(buyHash, sellHash, sell.feeRecipient != address(0) ? sell.maker : buy.maker, sell.feeRecipient != address(0) ? buy.maker : sell.maker, price, metadata);
}
}
/*
Exchange contract. This is an outer contract with public or convenience functions and includes no state-modifying functions.
*/
/**
* @title Exchange
* @author Project Erax Developers
*/
contract Exchange is ExchangeCore {
/**
* @dev Call hashOrder - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function hashOrder_(
address[7] memory addrs,
uint[10] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern)
public
pure
returns (bytes32)
{
return hashOrder(
Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], uints[9], addrs[6], uints[4], uints[5], uints[6], uints[7], uints[8])
);
}
/**
* @dev Call validateOrderParameters - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function validateOrderParameters_ (
address[7] memory addrs,
uint[10] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern)
view
public
returns (bool)
{
Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], uints[9], addrs[6], uints[4], uints[5], uints[6], uints[7], uints[8]);
return validateOrderParameters(
order
);
}
/**
* @dev Call cancelOrder - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function cancelOrder_(
address[7] memory addrs,
uint[10] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern,
uint8 v,
bytes32 r,
bytes32 s)
public
{
return cancelOrder(
Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], uints[9], addrs[6], uints[4], uints[5], uints[6], uints[7], uints[8]),
Sig(v, r, s)
);
}
/**
* @dev Call atomicMatch - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function atomicMatch_(
address[14] memory addrs,
uint[20] memory uints,
uint8[8] memory feeMethodsSidesKindsHowToCalls,
bytes memory calldataBuy,
bytes memory calldataSell,
bytes memory replacementPatternBuy,
bytes memory replacementPatternSell,
uint8[2] memory vs,
bytes32[5] memory rssMetadata)
public
payable
{
return atomicMatch(
Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], uints[2], uints[3], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], uints[9], addrs[6], uints[4], uints[5], uints[6], uints[7], uints[8]),
Sig(vs[0], rssMetadata[0], rssMetadata[1]),
Order(addrs[7], addrs[8], addrs[9], uints[10], uints[11], uints[12], uints[13], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], uints[19], addrs[13], uints[14], uints[15], uints[16], uints[17], uints[18]),
Sig(vs[1], rssMetadata[2], rssMetadata[3]),
rssMetadata[4]
);
}
}
/*
<< Project Erax Exchange >>
*/
/**
* @title EraxExchange
* @author Project Erax Developers
*/
contract EraxExchange is Exchange {
string public constant name = "Erax";
string public constant version = "1.0.0";
string public constant codename = "Init";
/**
* @dev Initialize a EraxExchange instance
* @param registryAddress Address of the registry instance which this Exchange instance will use
*/
constructor (ProxyRegistry registryAddress, TokenTransferProxy tokenTransferProxyAddress) {
registry = registryAddress;
tokenTransferProxy = tokenTransferProxyAddress;
}
} | Allows the current owner to transfer control of the contract to a newOwner. newOwner The address to transfer ownership to./ | function transferProxyOwnership(address newOwner) public onlyProxyOwner {
require(newOwner != address(0),"38");
emit ProxyOwnershipTransferred(proxyOwner(), newOwner);
setUpgradeabilityOwner(newOwner);
}
| 6,508,932 |
./partial_match/42/0x495cDCD6ae32B697Ab6d66b3ad077D570133E86e/sources/ExampleTokenCrowdsale.sol | low level token purchase DO NOT OVERRIDE _beneficiary Address performing the token purchase/ payable view returns(address,uint256,address,address) return(_beneficiary,weiAmount,address(0),address(this)); calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); | function buyTokens(address _beneficiary) public payable{
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
}
| 8,906,059 |
./full_match/1/0x92E79B2779460acd23548Af27a175467b32561b0/sources/ERC20.sol | Returns the current nonce for `owner`. This value is used to compute the signature for EIP-2612 permit. @solidity memory-safe-assembly Compute the nonce slot and load its value. | function nonces(
address owner
) public view virtual returns (uint256 result) {
assembly {
mstore(0x0c, _NONCES_SLOT_SEED)
mstore(0x00, owner)
result := sload(keccak256(0x0c, 0x20))
}
}
| 3,876,029 |
./full_match/1/0x4838099e16FC56bFdD8a76B7Fb9f338513Dd1575/sources/contracts/CrashTrading.sol | 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./ Clear approvals from the previous owner | 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);
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
| 3,103,471 |
pragma solidity ^0.4.13;
contract Ownable {
address internal 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 returns (bool) {
require(newOwner != address(0x0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
return true;
}
}
contract BitNauticWhitelist is Ownable {
using SafeMath for uint256;
uint256 public usdPerEth;
constructor(uint256 _usdPerEth) public {
usdPerEth = _usdPerEth;
}
mapping(address => bool) public AMLWhitelisted;
mapping(address => uint256) public contributionCap;
/**
* @dev add an address to the whitelist
* @param addr address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function setKYCLevel(address addr, uint8 level) onlyOwner public returns (bool) {
if (level >= 3) {
contributionCap[addr] = 50000 ether; // crowdsale hard cap
} else if (level == 2) {
contributionCap[addr] = SafeMath.div(500000 * 10 ** 18, usdPerEth); // KYC Tier 2 - 500k USD
} else if (level == 1) {
contributionCap[addr] = SafeMath.div(3000 * 10 ** 18, usdPerEth); // KYC Tier 1 - 3k USD
} else {
contributionCap[addr] = 0;
}
return true;
}
/**
* @dev add addresses to the whitelist
* @param addrs addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function setKYCLevelsBulk(address[] addrs, uint8[] levels) onlyOwner external returns (bool success) {
require(addrs.length == levels.length);
for (uint256 i = 0; i < addrs.length; i++) {
assert(setKYCLevel(addrs[i], levels[i]));
}
return true;
}
function setAMLWhitelisted(address addr, bool whitelisted) onlyOwner public returns (bool) {
AMLWhitelisted[addr] = whitelisted;
return true;
}
function setAMLWhitelistedBulk(address[] addrs, bool[] whitelisted) onlyOwner external returns (bool) {
require(addrs.length == whitelisted.length);
for (uint256 i = 0; i < addrs.length; i++) {
assert(setAMLWhitelisted(addrs[i], whitelisted[i]));
}
return true;
}
}
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();
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Crowdsale is Ownable, Pausable {
using SafeMath for uint256;
// The token being sold
MintableToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public ICOStartTime;
uint256 public ICOEndTime;
// wallet address where funds will be saved
address internal wallet;
// amount of raised money in wei
uint256 public weiRaised; // internal
// Public Supply
uint256 public publicSupply;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
// BitNautic Crowdsale constructor
constructor(MintableToken _token, uint256 _publicSupply, uint256 _startTime, uint256 _endTime, address _wallet) public {
require(_endTime >= _startTime);
require(_wallet != 0x0);
// BitNautic token creation
token = _token;
// total supply of token for the crowdsale
publicSupply = _publicSupply;
// Pre-ICO start Time
ICOStartTime = _startTime;
// ICO end Time
ICOEndTime = _endTime;
// wallet where funds will be saved
wallet = _wallet;
}
// fallback function can be used to buy tokens
function() public payable {
buyTokens(msg.sender);
}
// High level token purchase function
function buyTokens(address beneficiary) whenNotPaused public payable {
require(beneficiary != 0x0);
require(validPurchase());
// minimum investment should be 0.05 ETH
uint256 lowerPurchaseLimit = 0.05 ether;
require(msg.value >= lowerPurchaseLimit);
assert(_tokenPurchased(msg.sender, beneficiary, msg.value));
// update state
weiRaised = weiRaised.add(msg.value);
forwardFunds();
}
function _tokenPurchased(address /* buyer */, address /* beneficiary */, uint256 /* weiAmount */) internal returns (bool) {
// TO BE OVERLOADED IN SUBCLASSES
return true;
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = ICOStartTime <= now && now <= ICOEndTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
return now > ICOEndTime;
}
bool public checkBurnTokens = false;
function burnTokens() onlyOwner public returns (bool) {
require(hasEnded());
require(!checkBurnTokens);
token.mint(0x0, publicSupply);
token.burnTokens(publicSupply);
publicSupply = 0;
checkBurnTokens = true;
return true;
}
function getTokenAddress() onlyOwner public view returns (address) {
return address(token);
}
}
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 internal cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
// overriding Crowdsale#validPurchase to add extra cap logic
// @return true if investors can buy at the moment
function validPurchase() internal constant returns (bool) {
bool withinCap = weiRaised.add(msg.value) <= cap;
return super.validPurchase() && withinCap;
}
// overriding Crowdsale#hasEnded to add cap logic
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
bool capReached = weiRaised >= cap;
return super.hasEnded() || capReached;
}
}
contract FinalizableCrowdsale is Crowdsale {
using SafeMath for uint256;
bool isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalizeCrowdsale() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
emit Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
contract RefundVault is Ownable {
using SafeMath for uint256;
enum State { Active, Refunding, Closed }
mapping (address => uint256) public deposited;
address public wallet;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
constructor(address _wallet) public {
require(_wallet != 0x0);
wallet = _wallet;
state = State.Active;
}
function deposit(address investor) onlyOwner public payable {
require(state == State.Active);
deposited[investor] = deposited[investor].add(msg.value);
}
function close() onlyOwner public {
require(state == State.Active);
state = State.Closed;
emit Closed();
wallet.transfer(address(this).balance);
}
function enableRefunds() onlyOwner public {
require(state == State.Active);
state = State.Refunding;
emit RefundsEnabled();
}
function refund(address investor) public {
require(state == State.Refunding);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
emit Refunded(investor, depositedValue);
}
}
contract RefundableCrowdsale is FinalizableCrowdsale {
using SafeMath for uint256;
// minimum amount of funds to be raised in weis
uint256 internal goal;
bool internal _goalReached = false;
// refund vault used to hold funds while crowdsale is running
RefundVault private vault;
constructor(uint256 _goal) public {
require(_goal > 0);
vault = new RefundVault(wallet);
goal = _goal;
}
// We're overriding the fund forwarding from Crowdsale.
// In addition to sending the funds, we want to call
// the RefundVault deposit function
function forwardFunds() internal {
vault.deposit.value(msg.value)(msg.sender);
}
// if crowdsale is unsuccessful, investors can claim refunds here
function claimRefund() public {
require(isFinalized);
require(!goalReached());
vault.refund(msg.sender);
}
// vault finalization task, called when owner calls finalize()
function finalization() internal {
if (goalReached()) {
vault.close();
} else {
vault.enableRefunds();
}
super.finalization();
}
function goalReached() public returns (bool) {
if (weiRaised >= goal) {
_goalReached = true;
}
return _goalReached;
}
// function updateGoalCheck() onlyOwner public {
// _goalReached = true;
// }
function getVaultAddress() onlyOwner public view returns (address) {
return vault;
}
}
contract BitNauticCrowdsale is CappedCrowdsale, RefundableCrowdsale {
uint256 constant public crowdsaleInitialSupply = 35000000 * 10 ** 18; // 70% of token cap
// uint256 constant public crowdsaleSoftCap = 2 ether;
// uint256 constant public crowdsaleHardCap = 10 ether;
uint256 constant public crowdsaleSoftCap = 5000 ether;
uint256 constant public crowdsaleHardCap = 50000 ether;
uint256 constant public preICOStartTime = 1525132800; // 2018-05-01 00:00 GMT+0
uint256 constant public mainICOStartTime = 1527811200; // 2018-06-01 00:00 GMT+0
uint256 constant public mainICOFirstWeekEndTime = 1528416000; // 2018-06-08 00:00 GMT+0
uint256 constant public mainICOSecondWeekEndTime = 1529020800; // 2018-06-15 00:00 GMT+0
uint256 constant public mainICOThirdWeekEndTime = 1529625600; // 2018-06-22 00:00 GMT+0
uint256 constant public mainICOFourthWeekEndTime = 1530403200; // 2018-07-01 00:00 GMT+0
uint256 constant public mainICOEndTime = 1532995200; // 2018-07-31 00:00 GMT+0
// uint256 public preICOStartTime = now; // 2018-05-01 00:00 GMT+0
// uint256 constant public mainICOStartTime = preICOStartTime; // 2018-06-01 00:00 GMT+0
// uint256 constant public mainICOFirstWeekEndTime = mainICOStartTime; // 2018-06-08 00:00 GMT+0
// uint256 constant public mainICOSecondWeekEndTime = mainICOFirstWeekEndTime; // 2018-06-15 00:00 GMT+0
// uint256 constant public mainICOThirdWeekEndTime = mainICOSecondWeekEndTime; // 2018-06-22 00:00 GMT+0
// uint256 constant public mainICOFourthWeekEndTime = mainICOThirdWeekEndTime; // 2018-07-01 00:00 GMT+0
// uint256 constant public mainICOEndTime = mainICOFourthWeekEndTime + 5 minutes; // 2018-07-30 00:00 GMT+0
uint256 constant public tokenBaseRate = 500; // 1 ETH = 500 BTNT
// bonuses in percentage
uint256 constant public preICOBonus = 30;
uint256 constant public firstWeekBonus = 20;
uint256 constant public secondWeekBonus = 15;
uint256 constant public thirdWeekBonus = 10;
uint256 constant public fourthWeekBonus = 5;
uint256 public teamSupply = 3000000 * 10 ** 18; // 6% of token cap
uint256 public bountySupply = 2500000 * 10 ** 18; // 5% of token cap
uint256 public reserveSupply = 5000000 * 10 ** 18; // 10% of token cap
uint256 public advisorSupply = 2500000 * 10 ** 18; // 5% of token cap
uint256 public founderSupply = 2000000 * 10 ** 18; // 4% of token cap
// amount of tokens each address will receive at the end of the crowdsale
mapping (address => uint256) public creditOf;
mapping (address => uint256) public weiInvestedBy;
BitNauticWhitelist public whitelist;
/** Constructor BitNauticICO */
constructor(BitNauticToken _token, BitNauticWhitelist _whitelist, address _wallet)
CappedCrowdsale(crowdsaleHardCap)
FinalizableCrowdsale()
RefundableCrowdsale(crowdsaleSoftCap)
Crowdsale(_token, crowdsaleInitialSupply, preICOStartTime, mainICOEndTime, _wallet) public
{
whitelist = _whitelist;
}
function _tokenPurchased(address buyer, address beneficiary, uint256 weiAmount) internal returns (bool) {
require(SafeMath.add(weiInvestedBy[buyer], weiAmount) <= whitelist.contributionCap(buyer));
uint256 tokens = SafeMath.mul(weiAmount, tokenBaseRate);
tokens = tokens.add(SafeMath.mul(tokens, getCurrentBonus()).div(100));
require(publicSupply >= tokens);
publicSupply = publicSupply.sub(tokens);
creditOf[beneficiary] = creditOf[beneficiary].add(tokens);
weiInvestedBy[buyer] = SafeMath.add(weiInvestedBy[buyer], weiAmount);
emit TokenPurchase(buyer, beneficiary, weiAmount, tokens);
return true;
}
address constant public privateSaleWallet = 0x5A01D561AE864006c6B733f21f8D4311d1E1B42a;
function goalReached() public returns (bool) {
if (weiRaised + privateSaleWallet.balance >= goal) {
_goalReached = true;
}
return _goalReached;
}
function getCurrentBonus() public view returns (uint256) {
if (now < mainICOStartTime) {
return preICOBonus;
} else if (now < mainICOFirstWeekEndTime) {
return firstWeekBonus;
} else if (now < mainICOSecondWeekEndTime) {
return secondWeekBonus;
} else if (now < mainICOThirdWeekEndTime) {
return thirdWeekBonus;
} else if (now < mainICOFourthWeekEndTime) {
return fourthWeekBonus;
} else {
return 0;
}
}
function claimBitNauticTokens() public returns (bool) {
return grantInvestorTokens(msg.sender);
}
function grantInvestorTokens(address investor) public returns (bool) {
require(creditOf[investor] > 0);
require(now > mainICOEndTime && whitelist.AMLWhitelisted(investor));
require(goalReached());
assert(token.mint(investor, creditOf[investor]));
creditOf[investor] = 0;
return true;
}
function grantInvestorsTokens(address[] investors) public returns (bool) {
require(now > mainICOEndTime);
require(goalReached());
for (uint256 i = 0; i < investors.length; i++) {
if (creditOf[investors[i]] > 0 && whitelist.AMLWhitelisted(investors[i])) {
token.mint(investors[i], creditOf[investors[i]]);
creditOf[investors[i]] = 0;
}
}
return true;
}
function bountyDrop(address[] recipients, uint256[] values) onlyOwner public returns (bool) {
require(now > mainICOEndTime);
require(goalReached());
require(recipients.length == values.length);
for (uint256 i = 0; i < recipients.length; i++) {
values[i] = SafeMath.mul(values[i], 1 ether);
if (bountySupply >= values[i]) {
return false;
}
bountySupply = SafeMath.sub(bountySupply, values[i]);
token.mint(recipients[i], values[i]);
}
return true;
}
uint256 public teamTimeLock = mainICOEndTime;
uint256 public founderTimeLock = mainICOEndTime + 365 days;
uint256 public advisorTimeLock = mainICOEndTime + 180 days;
uint256 public reserveTimeLock = mainICOEndTime;
function grantAdvisorTokens(address advisorAddress) onlyOwner public {
require((advisorSupply > 0) && (advisorTimeLock < now));
require(goalReached());
token.mint(advisorAddress, advisorSupply);
advisorSupply = 0;
}
uint256 public teamVestingCounter = 0; // months of vesting
function grantTeamTokens(address teamAddress) onlyOwner public {
require((teamVestingCounter < 12) && (teamTimeLock < now));
require(goalReached());
teamTimeLock = SafeMath.add(teamTimeLock, 4 weeks);
token.mint(teamAddress, SafeMath.div(teamSupply, 12));
teamVestingCounter = SafeMath.add(teamVestingCounter, 1);
}
function grantFounderTokens(address founderAddress) onlyOwner public {
require((founderSupply > 0) && (founderTimeLock < now));
require(goalReached());
token.mint(founderAddress, founderSupply);
founderSupply = 0;
}
function grantReserveTokens(address beneficiary) onlyOwner public {
require((reserveSupply > 0) && (now > reserveTimeLock));
require(goalReached());
token.mint(beneficiary, reserveSupply);
reserveSupply = 0;
}
function transferTokenOwnership(address newTokenOwner) onlyOwner public returns (bool) {
return token.transferOwnership(newTokenOwner);
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
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 constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
uint256 _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
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 constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = SafeMath.add(totalSupply, _amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(0x0, _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
// function finishMinting() onlyOwner public returns (bool) {
// mintingFinished = true;
// emit MintFinished();
// return true;
// }
function burnTokens(uint256 _unsoldTokens) onlyOwner canMint public returns (bool) {
totalSupply = SafeMath.sub(totalSupply, _unsoldTokens);
}
}
contract CappedToken is MintableToken {
uint256 public cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
require(totalSupply.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
contract BitNauticToken is CappedToken {
string public constant name = "BitNautic Token";
string public constant symbol = "BTNT";
uint8 public constant decimals = 18;
uint256 public totalSupply = 0;
constructor()
CappedToken(50000000 * 10 ** uint256(decimals)) public
{
}
} | Function to mint tokens _to The address that will receive the minted tokens. _amount The amount of tokens to mint. return A boolean that indicates if the operation was successful./ | function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
require(totalSupply.add(_amount) <= cap);
return super.mint(_to, _amount);
}
| 6,476,982 |
./full_match/5/0x6e41fbb72Cf866c1Bb0356cBb22e6792D9245e2e/sources/contracts/Contract.sol | require(products[_id].quantity == 0, "The product is out of stock"); | function buyProductsID(uint256 _id)
external
payable
returns (uint256 quantity)
{
products[_id].quantity = products[_id].quantity - 1;
ownedProducts.push(
Product({
id: _id,
name: products[_id].name,
price: products[_id].price,
quantity: 1,
blockNumber: block.number,
owner: payable(msg.sender)
})
);
viewOwnedProducts.push(_id);
allPurchases[payable(msg.sender)].productId = _id;
allPurchases[payable(msg.sender)].productName = products[_id].name;
emit BuyProductLog(
_id,
products[_id].name,
products[_id].price,
1,
products[_id].blockNumber,
msg.sender
);
return products[_id].quantity;
}
| 1,956,169 |
// File: contracts/interfaces/IMarketHandler.sol
pragma solidity 0.6.12;
/**
* @title BiFi's market handler interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IMarketHandler {
function setCircuitBreaker(bool _emergency) external returns (bool);
function setCircuitBreakWithOwner(bool _emergency) external returns (bool);
function getTokenName() external view returns (string memory);
function ownershipTransfer(address payable newOwner) external returns (bool);
function deposit(uint256 unifiedTokenAmount, bool allFlag) external payable returns (bool);
function withdraw(uint256 unifiedTokenAmount, bool allFlag) external returns (bool);
function borrow(uint256 unifiedTokenAmount, bool allFlag) external returns (bool);
function repay(uint256 unifiedTokenAmount, bool allFlag) external payable returns (bool);
function executeFlashloan(
address receiverAddress,
uint256 amount
) external returns (bool);
function depositFlashloanFee(
uint256 amount
) external returns (bool);
function convertUnifiedToUnderlying(uint256 unifiedTokenAmount) external view returns (uint256);
function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 rewardHandlerID) external returns (uint256, uint256, uint256);
function partialLiquidationUserReward(address payable delinquentBorrower, uint256 liquidationAmountWithReward, address payable liquidator) external returns (uint256);
function getTokenHandlerLimit() external view returns (uint256, uint256);
function getTokenHandlerBorrowLimit() external view returns (uint256);
function getTokenHandlerMarginCallLimit() external view returns (uint256);
function setTokenHandlerBorrowLimit(uint256 borrowLimit) external returns (bool);
function setTokenHandlerMarginCallLimit(uint256 marginCallLimit) external returns (bool);
function getTokenLiquidityAmountWithInterest(address payable userAddr) external view returns (uint256);
function getUserAmountWithInterest(address payable userAddr) external view returns (uint256, uint256);
function getUserAmount(address payable userAddr) external view returns (uint256, uint256);
function getUserMaxBorrowAmount(address payable userAddr) external view returns (uint256);
function getUserMaxWithdrawAmount(address payable userAddr) external view returns (uint256);
function getUserMaxRepayAmount(address payable userAddr) external view returns (uint256);
function checkFirstAction() external returns (bool);
function applyInterest(address payable userAddr) external returns (uint256, uint256);
function reserveDeposit(uint256 unifiedTokenAmount) external payable returns (bool);
function reserveWithdraw(uint256 unifiedTokenAmount) external returns (bool);
function withdrawFlashloanFee(uint256 unifiedTokenAmount) external returns (bool);
function getDepositTotalAmount() external view returns (uint256);
function getBorrowTotalAmount() external view returns (uint256);
function getSIRandBIR() external view returns (uint256, uint256);
function getERC20Addr() external view returns (address);
}
// File: contracts/interfaces/IMarketHandlerDataStorage.sol
pragma solidity 0.6.12;
/**
* @title BiFi's market handler data storage interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IMarketHandlerDataStorage {
function setCircuitBreaker(bool _emergency) external returns (bool);
function setNewCustomer(address payable userAddr) external returns (bool);
function getUserAccessed(address payable userAddr) external view returns (bool);
function setUserAccessed(address payable userAddr, bool _accessed) external returns (bool);
function getReservedAddr() external view returns (address payable);
function setReservedAddr(address payable reservedAddress) external returns (bool);
function getReservedAmount() external view returns (int256);
function addReservedAmount(uint256 amount) external returns (int256);
function subReservedAmount(uint256 amount) external returns (int256);
function updateSignedReservedAmount(int256 amount) external returns (int256);
function setTokenHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool);
function setCoinHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool);
function getDepositTotalAmount() external view returns (uint256);
function addDepositTotalAmount(uint256 amount) external returns (uint256);
function subDepositTotalAmount(uint256 amount) external returns (uint256);
function getBorrowTotalAmount() external view returns (uint256);
function addBorrowTotalAmount(uint256 amount) external returns (uint256);
function subBorrowTotalAmount(uint256 amount) external returns (uint256);
function getUserIntraDepositAmount(address payable userAddr) external view returns (uint256);
function addUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256);
function subUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256);
function getUserIntraBorrowAmount(address payable userAddr) external view returns (uint256);
function addUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256);
function subUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256);
function addDepositAmount(address payable userAddr, uint256 amount) external returns (bool);
function subDepositAmount(address payable userAddr, uint256 amount) external returns (bool);
function addBorrowAmount(address payable userAddr, uint256 amount) external returns (bool);
function subBorrowAmount(address payable userAddr, uint256 amount) external returns (bool);
function getUserAmount(address payable userAddr) external view returns (uint256, uint256);
function getHandlerAmount() external view returns (uint256, uint256);
function getAmount(address payable userAddr) external view returns (uint256, uint256, uint256, uint256);
function setAmount(address payable userAddr, uint256 depositTotalAmount, uint256 borrowTotalAmount, uint256 depositAmount, uint256 borrowAmount) external returns (uint256);
function setBlocks(uint256 lastUpdatedBlock, uint256 inactiveActionDelta) external returns (bool);
function getLastUpdatedBlock() external view returns (uint256);
function setLastUpdatedBlock(uint256 _lastUpdatedBlock) external returns (bool);
function getInactiveActionDelta() external view returns (uint256);
function setInactiveActionDelta(uint256 inactiveActionDelta) external returns (bool);
function syncActionEXR() external returns (bool);
function getActionEXR() external view returns (uint256, uint256);
function setActionEXR(uint256 actionDepositExRate, uint256 actionBorrowExRate) external returns (bool);
function getGlobalDepositEXR() external view returns (uint256);
function getGlobalBorrowEXR() external view returns (uint256);
function setEXR(address payable userAddr, uint256 globalDepositEXR, uint256 globalBorrowEXR) external returns (bool);
function getUserEXR(address payable userAddr) external view returns (uint256, uint256);
function setUserEXR(address payable userAddr, uint256 depositEXR, uint256 borrowEXR) external returns (bool);
function getGlobalEXR() external view returns (uint256, uint256);
function getMarketHandlerAddr() external view returns (address);
function setMarketHandlerAddr(address marketHandlerAddr) external returns (bool);
function getInterestModelAddr() external view returns (address);
function setInterestModelAddr(address interestModelAddr) external returns (bool);
function getMinimumInterestRate() external view returns (uint256);
function setMinimumInterestRate(uint256 _minimumInterestRate) external returns (bool);
function getLiquiditySensitivity() external view returns (uint256);
function setLiquiditySensitivity(uint256 _liquiditySensitivity) external returns (bool);
function getLimit() external view returns (uint256, uint256);
function getBorrowLimit() external view returns (uint256);
function setBorrowLimit(uint256 _borrowLimit) external returns (bool);
function getMarginCallLimit() external view returns (uint256);
function setMarginCallLimit(uint256 _marginCallLimit) external returns (bool);
function getLimitOfAction() external view returns (uint256);
function setLimitOfAction(uint256 limitOfAction) external returns (bool);
function getLiquidityLimit() external view returns (uint256);
function setLiquidityLimit(uint256 liquidityLimit) external returns (bool);
}
// File: contracts/interfaces/IMarketManager.sol
pragma solidity 0.6.12;
/**
* @title BiFi's market manager interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IMarketManager {
function setBreakerTable(address _target, bool _status) external returns (bool);
function getCircuitBreaker() external view returns (bool);
function setCircuitBreaker(bool _emergency) external returns (bool);
function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address, string memory);
function handlerRegister(uint256 handlerID, address tokenHandlerAddr, uint256 flashFeeRate) external returns (bool);
function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256, uint256, uint256, uint256);
function getTokenHandlerPrice(uint256 handlerID) external view returns (uint256);
function getTokenHandlerBorrowLimit(uint256 handlerID) external view returns (uint256);
function getTokenHandlerSupport(uint256 handlerID) external view returns (bool);
function getTokenHandlersLength() external view returns (uint256);
function setTokenHandlersLength(uint256 _tokenHandlerLength) external returns (bool);
function getTokenHandlerID(uint256 index) external view returns (uint256);
function getTokenHandlerMarginCallLimit(uint256 handlerID) external view returns (uint256);
function getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) external view returns (uint256, uint256);
function getUserTotalIntraCreditAsset(address payable userAddr) external view returns (uint256, uint256);
function getUserLimitIntraAsset(address payable userAddr) external view returns (uint256, uint256);
function getUserCollateralizableAmount(address payable userAddr, uint256 handlerID) external view returns (uint256);
function getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) external view returns (uint256);
function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 liquidateHandlerID, uint256 rewardHandlerID) external returns (uint256, uint256, uint256);
function getMaxLiquidationReward(address payable delinquentBorrower, uint256 liquidateHandlerID, uint256 liquidateAmount, uint256 rewardHandlerID, uint256 rewardRatio) external view returns (uint256);
function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) external returns (uint256);
function setLiquidationManager(address liquidationManagerAddr) external returns (bool);
function rewardClaimAll(address payable userAddr) external returns (uint256);
function updateRewardParams(address payable userAddr) external returns (bool);
function interestUpdateReward() external returns (bool);
function getGlobalRewardInfo() external view returns (uint256, uint256, uint256);
function setOracleProxy(address oracleProxyAddr) external returns (bool);
function rewardUpdateOfInAction(address payable userAddr, uint256 callerID) external returns (bool);
function ownerRewardTransfer(uint256 _amount) external returns (bool);
function getFeeTotal(uint256 handlerID) external returns (uint256);
function getFeeFromArguments(uint256 handlerID, uint256 amount, uint256 bifiAmount) external returns (uint256);
}
// File: contracts/interfaces/IInterestModel.sol
pragma solidity 0.6.12;
/**
* @title BiFi's interest model interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IInterestModel {
function getInterestAmount(address handlerDataStorageAddr, address payable userAddr, bool isView) external view returns (bool, uint256, uint256, bool, uint256, uint256);
function viewInterestAmount(address handlerDataStorageAddr, address payable userAddr) external view returns (bool, uint256, uint256, bool, uint256, uint256);
function getSIRandBIR(uint256 depositTotalAmount, uint256 borrowTotalAmount) external view returns (uint256, uint256);
}
// File: contracts/interfaces/IMarketSIHandlerDataStorage.sol
pragma solidity 0.6.12;
/**
* @title BiFi's market si handler data storage interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IMarketSIHandlerDataStorage {
function setCircuitBreaker(bool _emergency) external returns (bool);
function updateRewardPerBlockStorage(uint256 _rewardPerBlock) external returns (bool);
function getRewardInfo(address userAddr) external view returns (uint256, uint256, uint256, uint256, uint256, uint256);
function getMarketRewardInfo() external view returns (uint256, uint256, uint256);
function setMarketRewardInfo(uint256 _rewardLane, uint256 _rewardLaneUpdateAt, uint256 _rewardPerBlock) external returns (bool);
function getUserRewardInfo(address userAddr) external view returns (uint256, uint256, uint256);
function setUserRewardInfo(address userAddr, uint256 _rewardLane, uint256 _rewardLaneUpdateAt, uint256 _rewardAmount) external returns (bool);
function getBetaRate() external view returns (uint256);
function setBetaRate(uint256 _betaRate) external returns (bool);
}
// File: contracts/interfaces/IERC20.sol
// from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol
pragma solidity 0.6.12;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external ;
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external ;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/interfaces/IProxy.sol
pragma solidity 0.6.12;
/**
* @title BiFi's proxy interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IProxy {
function handlerProxy(bytes memory data) external returns (bool, bytes memory);
function handlerViewProxy(bytes memory data) external view returns (bool, bytes memory);
function siProxy(bytes memory data) external returns (bool, bytes memory);
function siViewProxy(bytes memory data) external view returns (bool, bytes memory);
}
// File: contracts/interfaces/IServiceIncentive.sol
pragma solidity 0.6.12;
/**
* @title BiFi's si interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IServiceIncentive {
function setCircuitBreakWithOwner(bool emergency) external returns (bool);
function setCircuitBreaker(bool emergency) external returns (bool);
function updateRewardPerBlockLogic(uint256 _rewardPerBlock) external returns (bool);
function updateRewardLane(address payable userAddr) external returns (bool);
function getBetaRateBaseTotalAmount() external view returns (uint256);
function getBetaRateBaseUserAmount(address payable userAddr) external view returns (uint256);
function getMarketRewardInfo() external view returns (uint256, uint256, uint256);
function getUserRewardInfo(address payable userAddr) external view returns (uint256, uint256, uint256);
function claimRewardAmountUser(address payable userAddr) external returns (uint256);
}
// File: contracts/interfaces/IFlashloanReceiver.sol
pragma solidity 0.6.12;
interface IFlashloanReceiver {
function executeOperation(
address reserve,
uint256 amount,
uint256 fee,
bytes calldata params
) external returns (bool);
}
// File: contracts/interfaces/IinterchainManager.sol
pragma solidity 0.6.12;
/**
* @title Bifrost's interchain manager interfaces
* @author Bifrost(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IinterchainManager {
function executeOutflow(address _userAddr, uint256 _btcAmount, uint256 actionType) external returns (bool);
}
// File: contracts/Errors.sol
pragma solidity 0.6.12;
contract Modifier {
string internal constant ONLY_OWNER = "O";
string internal constant ONLY_MANAGER = "M";
string internal constant CIRCUIT_BREAKER = "emergency";
}
contract ManagerModifier is Modifier {
string internal constant ONLY_HANDLER = "H";
string internal constant ONLY_LIQUIDATION_MANAGER = "LM";
string internal constant ONLY_BREAKER = "B";
}
contract HandlerDataStorageModifier is Modifier {
string internal constant ONLY_BIFI_CONTRACT = "BF";
}
contract SIDataStorageModifier is Modifier {
string internal constant ONLY_SI_HANDLER = "SI";
}
contract HandlerErrors is Modifier {
string internal constant USE_VAULE = "use value";
string internal constant USE_ARG = "use arg";
string internal constant EXCEED_LIMIT = "exceed limit";
string internal constant NO_LIQUIDATION = "no liquidation";
string internal constant NO_LIQUIDATION_REWARD = "no enough reward";
string internal constant NO_EFFECTIVE_BALANCE = "not enough balance";
string internal constant TRANSFER = "err transfer";
}
contract SIErrors is Modifier { }
contract InterestErrors is Modifier { }
contract LiquidationManagerErrors is Modifier {
string internal constant NO_DELINQUENT = "not delinquent";
}
contract ManagerErrors is ManagerModifier {
string internal constant REWARD_TRANSFER = "RT";
string internal constant UNSUPPORTED_TOKEN = "UT";
}
contract OracleProxyErrors is Modifier {
string internal constant ZERO_PRICE = "price zero";
}
contract RequestProxyErrors is Modifier { }
contract ManagerDataStorageErrors is ManagerModifier {
string internal constant NULL_ADDRESS = "err addr null";
}
// File: contracts/context/BlockContext.sol
pragma solidity 0.6.12;
/**
* @title BiFi's BlockContext contract
* @notice BiFi getter Contract for Block Context Information
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
contract BlockContext {
function _blockContext() internal view returns(uint256 context) {
// block number chain
context = block.number;
// block timestamp chain
// context = block.timestamp;
}
}
// File: contracts/marketHandler/TokenHandler.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.6.12;
/**
* @title BiFi's TokenHandler logic contract for ERC20 tokens
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
contract TokenHandler is IMarketHandler, HandlerErrors, BlockContext {
event MarketIn(address userAddr);
event Deposit(address depositor, uint256 depositAmount, uint256 handlerID);
event DepositTo(address from, address depositor, uint256 depositAmount, uint256 handlerID);
event Withdraw(address redeemer, uint256 redeemAmount, uint256 handlerID);
event Borrow(address borrower, uint256 borrowAmount, uint256 handlerID);
event Repay(address repayer, uint256 repayAmount, uint256 handlerID);
event RepayTo(address from, address repayer, uint256 repayAmount, uint256 handlerID);
event ExternalWithdraw(address redeemer, uint256 redeemAmount, uint256 handlerID);
event ExternalBorrow(address borrower, uint256 borrowAmount, uint256 handlerID);
event ReserveDeposit(uint256 reserveDepositAmount, uint256 handlerID);
event ReserveWithdraw(uint256 reserveWithdrawAmount, uint256 handlerID);
event FlashloanFeeWithdraw(uint256 flashloanFeeWithdrawAmount, uint256 handlerID);
event OwnershipTransferred(address owner, address newOwner);
event CircuitBreaked(bool breaked, uint256 blockNumber, uint256 handlerID);
address payable owner;
uint256 handlerID;
string tokenName;
uint256 constant unifiedPoint = 10 ** 18;
uint256 unifiedTokenDecimal;
uint256 underlyingTokenDecimal;
IMarketManager marketManager;
IInterestModel interestModelInstance;
IMarketHandlerDataStorage handlerDataStorage;
IMarketSIHandlerDataStorage SIHandlerDataStorage;
IERC20 erc20Instance;
address handler;
address SI;
IinterchainManager interchainManager;
struct ProxyInfo {
bool result;
bytes returnData;
bytes data;
bytes proxyData;
}
modifier onlyMarketManager {
address msgSender = msg.sender;
require((msgSender == address(marketManager)) || (msgSender == owner), ONLY_MANAGER);
_;
}
modifier onlyOwner {
require(msg.sender == address(owner), ONLY_OWNER);
_;
}
/**
* @dev Set circuitBreak to freeze all of handlers by owner
* @param _emergency Boolean state of the circuit break.
* @return true (TODO: validate results)
*/
function setCircuitBreakWithOwner(bool _emergency) onlyOwner external override returns (bool)
{
handlerDataStorage.setCircuitBreaker(_emergency);
emit CircuitBreaked(_emergency, block.number, handlerID);
return true;
}
/**
* @dev Set circuitBreak which freeze all of handlers by marketManager
* @param _emergency Boolean state of the circuit break.
* @return true (TODO: validate results)
*/
function setCircuitBreaker(bool _emergency) onlyMarketManager external override returns (bool)
{
handlerDataStorage.setCircuitBreaker(_emergency);
emit CircuitBreaked(_emergency, block.number, handlerID);
return true;
}
/**
* @dev Change the owner of the handler
* @param newOwner the address of the owner to be replaced
* @return true (TODO: validate results)
*/
function ownershipTransfer(address payable newOwner) onlyOwner external override returns (bool)
{
owner = newOwner;
emit OwnershipTransferred(owner, newOwner);
return true;
}
/**
* @dev Get the token name
* @return the token name
*/
function getTokenName() external view override returns (string memory)
{
return tokenName;
}
/**
* @dev Deposit assets to the reserve of the handler.
* @param unifiedTokenAmount The amount of token to deposit
* @return true (TODO: validate results)
*/
function reserveDeposit(uint256 unifiedTokenAmount) external payable override returns (bool)
{
require(msg.value == 0, USE_ARG);
handlerDataStorage.addReservedAmount(unifiedTokenAmount);
handlerDataStorage.addDepositTotalAmount(unifiedTokenAmount);
_transferFrom(msg.sender, unifiedTokenAmount);
emit ReserveDeposit(unifiedTokenAmount, handlerID);
return true;
}
/**
* @dev Withdraw assets from the reserve of the handler.
* @param unifiedTokenAmount The amount of token to withdraw
* @return true (TODO: validate results)
*/
function reserveWithdraw(uint256 unifiedTokenAmount) onlyOwner external override returns (bool)
{
address payable reserveAddr = handlerDataStorage.getReservedAddr();
handlerDataStorage.subReservedAmount(unifiedTokenAmount);
handlerDataStorage.subDepositTotalAmount(unifiedTokenAmount);
_transfer(reserveAddr, unifiedTokenAmount);
emit ReserveWithdraw(unifiedTokenAmount, handlerID);
return true;
}
function withdrawFlashloanFee(uint256 unifiedTokenAmount) onlyMarketManager external override returns (bool) {
address payable reserveAddr = handlerDataStorage.getReservedAddr();
handlerDataStorage.subReservedAmount(unifiedTokenAmount);
handlerDataStorage.subDepositTotalAmount(unifiedTokenAmount);
_transfer(reserveAddr, unifiedTokenAmount);
emit FlashloanFeeWithdraw(unifiedTokenAmount, handlerID);
return true;
}
/**
* @dev Deposit action
* @param unifiedTokenAmount The deposit amount
* @param flag Flag for the full calcuation mode
* @return true (TODO: validate results)
*/
function deposit(uint256 unifiedTokenAmount, bool flag) external payable override returns (bool)
{
require(msg.value == 0, USE_ARG);
address payable userAddr = msg.sender;
uint256 _handlerID = handlerID;
if(flag) {
// flag is true, update interest, reward all handlers
marketManager.applyInterestHandlers(userAddr, _handlerID, flag);
} else {
marketManager.rewardUpdateOfInAction(userAddr, _handlerID);
_applyInterest(userAddr);
}
handlerDataStorage.addDepositAmount(userAddr, unifiedTokenAmount);
_transferFrom(userAddr, unifiedTokenAmount);
emit Deposit(userAddr, unifiedTokenAmount, _handlerID);
return true;
}
function depositTo(address payable toUser, uint256 unifiedTokenAmount, bool flag) external returns (bool)
{
uint256 _handlerID = handlerID;
address payable _sender = msg.sender;
if(flag) {
// flag is true, update interest, reward all handlers
marketManager.applyInterestHandlers(toUser, _handlerID, flag);
} else {
marketManager.rewardUpdateOfInAction(toUser, _handlerID);
_applyInterest(toUser);
}
handlerDataStorage.addDepositAmount(toUser, unifiedTokenAmount);
_transferFrom(_sender, unifiedTokenAmount);
emit DepositTo(_sender, toUser, unifiedTokenAmount, _handlerID);
return true;
}
/**
* @dev Withdraw action
* @param unifiedTokenAmount The withdraw amount
* @param flag Flag for the full calcuation mode
* @return true (TODO: validate results)
*/
function withdraw(uint256 unifiedTokenAmount, bool flag) external override returns (bool)
{
address payable userAddr = msg.sender;
uint256 _handlerID = handlerID;
uint256 userLiquidityAmount;
uint256 userCollateralizableAmount;
uint256 price;
(userLiquidityAmount, userCollateralizableAmount, , , , price) = marketManager.applyInterestHandlers(userAddr, _handlerID, flag);
uint256 adjustedAmount = _getUserActionMaxWithdrawAmount(userAddr, unifiedTokenAmount, userCollateralizableAmount);
require(unifiedMul(adjustedAmount, price) <= handlerDataStorage.getLimitOfAction(), EXCEED_LIMIT);
handlerDataStorage.subDepositAmount(userAddr, adjustedAmount);
_transfer(userAddr, adjustedAmount);
emit Withdraw(userAddr, adjustedAmount, _handlerID);
return true;
}
/**
* @dev Borrow action
* @param unifiedTokenAmount The borrow amount
* @param flag Flag for the full calcuation mode
* @return true (TODO: validate results)
*/
function borrow(uint256 unifiedTokenAmount, bool flag) external override returns (bool)
{
address payable userAddr = msg.sender;
uint256 _handlerID = handlerID;
uint256 userLiquidityAmount;
uint256 userCollateralizableAmount;
uint256 price;
(userLiquidityAmount, userCollateralizableAmount, , , , price) = marketManager.applyInterestHandlers(userAddr, _handlerID, flag);
uint256 adjustedAmount = _getUserActionMaxBorrowAmount(unifiedTokenAmount, userLiquidityAmount);
require(unifiedMul(adjustedAmount, price) <= handlerDataStorage.getLimitOfAction(), EXCEED_LIMIT);
handlerDataStorage.addBorrowAmount(userAddr, adjustedAmount);
_transfer(userAddr, adjustedAmount);
emit Borrow(userAddr, adjustedAmount, _handlerID);
return true;
}
/**
* @dev Repay action
* @param unifiedTokenAmount The repay amount
* @param flag Flag for the full calcuation mode
* @return true (TODO: validate results)
*/
function repay(uint256 unifiedTokenAmount, bool flag) external payable override returns (bool)
{
require(msg.value == 0, USE_ARG);
address payable userAddr = msg.sender;
uint256 _handlerID = handlerID;
if(flag) {
// flag is true, update interest, reward all handlers
marketManager.applyInterestHandlers(userAddr, _handlerID, flag);
} else {
marketManager.rewardUpdateOfInAction(userAddr, _handlerID);
_applyInterest(userAddr);
}
uint256 userBorrowAmount = handlerDataStorage.getUserIntraBorrowAmount(userAddr);
if (userBorrowAmount < unifiedTokenAmount)
{
unifiedTokenAmount = userBorrowAmount;
}
handlerDataStorage.subBorrowAmount(userAddr, unifiedTokenAmount);
_transferFrom(userAddr, unifiedTokenAmount);
emit Repay(userAddr, unifiedTokenAmount, _handlerID);
return true;
}
function repayTo(address payable toUser, uint256 unifiedTokenAmount, bool flag) external returns (bool)
{
uint256 _handlerID = handlerID;
address _sender = msg.sender;
if(flag) {
// flag is true, update interest, reward all handlers
marketManager.applyInterestHandlers(toUser, _handlerID, flag);
} else {
marketManager.rewardUpdateOfInAction(toUser, _handlerID);
_applyInterest(toUser);
}
uint256 userBorrowAmount = handlerDataStorage.getUserIntraBorrowAmount(toUser);
if (userBorrowAmount < unifiedTokenAmount)
{
handlerDataStorage.subBorrowAmount(toUser, userBorrowAmount);
handlerDataStorage.addDepositAmount(toUser, sub(unifiedTokenAmount, userBorrowAmount) );
emit Deposit(toUser, sub(unifiedTokenAmount, userBorrowAmount), _handlerID);
} else {
handlerDataStorage.subBorrowAmount(toUser, unifiedTokenAmount);
}
_transferFrom(msg.sender, unifiedTokenAmount);
emit RepayTo(_sender, toUser, unifiedTokenAmount, _handlerID);
return true;
}
function reqExternalWithdraw(uint256 unifiedTokenAmount, bool flag) external returns (bool)
{
address payable userAddr = msg.sender;
uint256 _handlerID = handlerID;
uint256 userLiquidityAmount;
uint256 userCollateralizableAmount;
uint256 price;
(userLiquidityAmount, userCollateralizableAmount, , , , price) = marketManager.applyInterestHandlers(userAddr, _handlerID, flag);
uint256 adjustedAmount = _getUserActionMaxWithdrawAmount(userAddr, unifiedTokenAmount, userCollateralizableAmount);
require(unifiedMul(adjustedAmount, price) <= handlerDataStorage.getLimitOfAction(), EXCEED_LIMIT);
handlerDataStorage.subDepositAmount(userAddr, adjustedAmount);
uint256 underlyingAmount = _approve(address(interchainManager), adjustedAmount);
interchainManager.executeOutflow(userAddr, underlyingAmount, 2);
emit ExternalWithdraw(userAddr, adjustedAmount, _handlerID);
return true;
}
function reqExternalborrow(uint256 unifiedTokenAmount, bool flag) external returns (bool)
{
address payable userAddr = msg.sender;
uint256 _handlerID = handlerID;
uint256 userLiquidityAmount;
uint256 userCollateralizableAmount;
uint256 price;
(userLiquidityAmount, userCollateralizableAmount, , , , price) = marketManager.applyInterestHandlers(userAddr, _handlerID, flag);
uint256 adjustedAmount = _getUserActionMaxBorrowAmount(unifiedTokenAmount, userLiquidityAmount);
require(unifiedMul(adjustedAmount, price) <= handlerDataStorage.getLimitOfAction(), EXCEED_LIMIT);
handlerDataStorage.addBorrowAmount(userAddr, adjustedAmount);
uint256 underlyingAmount = _approve(address(interchainManager), adjustedAmount);
interchainManager.executeOutflow(userAddr, underlyingAmount, 3);
emit ExternalBorrow(userAddr, adjustedAmount, _handlerID);
return true;
}
function executeFlashloan(
address receiverAddress,
uint256 amount
) external onlyMarketManager override returns (bool) {
_transfer(payable(receiverAddress), amount);
return true;
}
function depositFlashloanFee(
uint256 amount
) external onlyMarketManager override returns (bool) {
handlerDataStorage.addReservedAmount(amount);
handlerDataStorage.addDepositTotalAmount(amount);
emit ReserveDeposit(amount, handlerID);
return true;
}
/**
* @dev liquidate delinquentBorrower's partial(or can total) asset
* @param delinquentBorrower The user addresss of liquidation target
* @param liquidateAmount The amount of liquidator request
* @param liquidator The address of a user executing liquidate
* @param rewardHandlerID The handler id of delinquentBorrower's collateral for receive
* @return (liquidateAmount, delinquentDepositAsset, delinquentBorrowAsset), result of liquidate
*/
function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 rewardHandlerID) onlyMarketManager external override returns (uint256, uint256, uint256)
{
/* over paied amount compaction */
uint256 tmp;
uint256 delinquentMarginCallDeposit;
uint256 delinquentDepositAsset;
uint256 delinquentBorrowAsset;
uint256 liquidatorLiquidityAmount;
/* apply interest for sync "latest" asset for delinquentBorrower and liquidator */
(, , delinquentMarginCallDeposit, delinquentDepositAsset, delinquentBorrowAsset, ) = marketManager.applyInterestHandlers(delinquentBorrower, handlerID, false);
(, liquidatorLiquidityAmount, , , , ) = marketManager.applyInterestHandlers(liquidator, handlerID, false);
/* check delinquentBorrower liquidatable */
require(delinquentMarginCallDeposit <= delinquentBorrowAsset, NO_LIQUIDATION);
tmp = handlerDataStorage.getUserIntraDepositAmount(liquidator);
if (tmp <= liquidateAmount)
{
liquidateAmount = tmp;
}
tmp = handlerDataStorage.getUserIntraBorrowAmount(delinquentBorrower);
if (tmp <= liquidateAmount)
{
liquidateAmount = tmp;
}
/* get maximum "receive handler" amount by liquidate amount */
liquidateAmount = marketManager.getMaxLiquidationReward(delinquentBorrower, handlerID, liquidateAmount, rewardHandlerID, unifiedDiv(delinquentBorrowAsset, delinquentDepositAsset));
/* check liquidator has enough amount for liquidation */
require(liquidatorLiquidityAmount > liquidateAmount, NO_EFFECTIVE_BALANCE);
/* update storage for liquidate*/
handlerDataStorage.subDepositAmount(liquidator, liquidateAmount);
handlerDataStorage.subBorrowAmount(delinquentBorrower, liquidateAmount);
return (liquidateAmount, delinquentDepositAsset, delinquentBorrowAsset);
}
/**
* @dev liquidator receive delinquentBorrower's collateral after liquidate delinquentBorrower's asset
* @param delinquentBorrower The user addresss of liquidation target
* @param liquidationAmountWithReward The amount of liquidator receiving delinquentBorrower's collateral
* @param liquidator The address of a user executing liquidate
* @return The amount of token transfered(in storage)
*/
function partialLiquidationUserReward(address payable delinquentBorrower, uint256 liquidationAmountWithReward, address payable liquidator) onlyMarketManager external override returns (uint256)
{
marketManager.rewardUpdateOfInAction(delinquentBorrower, handlerID);
_applyInterest(delinquentBorrower);
/* check delinquentBorrower's collateral enough */
uint256 collateralAmount = handlerDataStorage.getUserIntraDepositAmount(delinquentBorrower);
require(collateralAmount >= liquidationAmountWithReward, NO_LIQUIDATION_REWARD);
/* collateral transfer */
handlerDataStorage.subDepositAmount(delinquentBorrower, liquidationAmountWithReward);
_transfer(liquidator, liquidationAmountWithReward);
return liquidationAmountWithReward;
}
/**
* @dev Get borrowLimit and marginCallLimit
* @return borrowLimit and marginCallLimit
*/
function getTokenHandlerLimit() external view override returns (uint256, uint256)
{
return handlerDataStorage.getLimit();
}
/**
* @dev Set the borrow limit of the handler through a specific handlerID
* @param borrowLimit The borrow limit
* @return true (TODO: validate results)
*/
function setTokenHandlerBorrowLimit(uint256 borrowLimit) onlyOwner external override returns (bool)
{
handlerDataStorage.setBorrowLimit(borrowLimit);
return true;
}
/**
* @dev Set the liquidation limit of the handler through a specific handlerID
* @param marginCallLimit The liquidation limit
* @return true (TODO: validate results)
*/
function setTokenHandlerMarginCallLimit(uint256 marginCallLimit) onlyOwner external override returns (bool)
{
handlerDataStorage.setMarginCallLimit(marginCallLimit);
return true;
}
/**
* @dev Get the liquidation limit of handler through a specific handlerID
* @return The liquidation limit
*/
function getTokenHandlerMarginCallLimit() external view override returns (uint256)
{
return handlerDataStorage.getMarginCallLimit();
}
/**
* @dev Get the borrow limit of the handler through a specific handlerID
* @return The borrow limit
*/
function getTokenHandlerBorrowLimit() external view override returns (uint256)
{
return handlerDataStorage.getBorrowLimit();
}
/**
* @dev Get the maximum amount that user can borrow
* @param userAddr The address of user
* @return the maximum amount that user can borrow
*/
function getUserMaxBorrowAmount(address payable userAddr) external view override returns (uint256)
{
return _getUserMaxBorrowAmount(userAddr);
}
/**
* @dev Get (total deposit - total borrow) of the handler including interest
* @param userAddr The user address(for wrapping function, unused)
* @return (total deposit - total borrow) of the handler including interest
*/
function getTokenLiquidityAmountWithInterest(address payable userAddr) external view override returns (uint256)
{
return _getTokenLiquidityAmountWithInterest(userAddr);
}
/**
* @dev Get the maximum amount that user can borrow
* @param userAddr The address of user
* @return the maximum amount that user can borrow
*/
function _getUserMaxBorrowAmount(address payable userAddr) internal view returns (uint256)
{
/* Prevent Action: over "Token Liquidity" amount*/
uint256 handlerLiquidityAmount = _getTokenLiquidityLimitAmountWithInterest(userAddr);
/* Prevent Action: over "CREDIT" amount */
uint256 userLiquidityAmount = marketManager.getUserExtraLiquidityAmount(userAddr, handlerID);
uint256 minAmount = userLiquidityAmount;
if (handlerLiquidityAmount < minAmount)
{
minAmount = handlerLiquidityAmount;
}
return minAmount;
}
/**
* @dev Get the maximum amount that user can borrow
* @param requestedAmount The amount of token to borrow
* @param userLiquidityAmount The amount of liquidity that users can borrow
* @return the maximum amount that user can borrow
*/
function _getUserActionMaxBorrowAmount(uint256 requestedAmount, uint256 userLiquidityAmount) internal view returns (uint256)
{
/* Prevent Action: over "Token Liquidity" amount*/
uint256 handlerLiquidityAmount = _getTokenLiquidityLimitAmount();
/* select minimum of handlerLiqudity and user liquidity */
uint256 minAmount = requestedAmount;
if (minAmount > handlerLiquidityAmount)
{
minAmount = handlerLiquidityAmount;
}
if (minAmount > userLiquidityAmount)
{
minAmount = userLiquidityAmount;
}
return minAmount;
}
/**
* @dev Get the maximum amount that users can withdraw
* @param userAddr The address of user
* @return the maximum amount that users can withdraw
*/
function getUserMaxWithdrawAmount(address payable userAddr) external view override returns (uint256)
{
return _getUserMaxWithdrawAmount(userAddr);
}
/**
* @dev Get the rate of SIR and BIR
* @return The rate of SIR and BIR
*/
function getSIRandBIR() external view override returns (uint256, uint256)
{
uint256 totalDepositAmount = handlerDataStorage.getDepositTotalAmount();
uint256 totalBorrowAmount = handlerDataStorage.getBorrowTotalAmount();
return interestModelInstance.getSIRandBIR(totalDepositAmount, totalBorrowAmount);
}
/**
* @dev Get the maximum amount that users can withdraw
* @param userAddr The address of user
* @return the maximum amount that users can withdraw
*/
function _getUserMaxWithdrawAmount(address payable userAddr) internal view returns (uint256)
{
uint256 depositAmountWithInterest;
uint256 borrowAmountWithInterest;
(depositAmountWithInterest, borrowAmountWithInterest) = _getUserAmountWithInterest(userAddr);
uint256 handlerLiquidityAmount = _getTokenLiquidityAmountWithInterest(userAddr);
uint256 userLiquidityAmount = marketManager.getUserCollateralizableAmount(userAddr, handlerID);
/* Prevent Action: over "DEPOSIT" amount */
uint256 minAmount = depositAmountWithInterest;
/* Prevent Action: over "CREDIT" amount */
if (minAmount > userLiquidityAmount)
{
minAmount = userLiquidityAmount;
}
if (minAmount > handlerLiquidityAmount)
{
minAmount = handlerLiquidityAmount;
}
return minAmount;
}
/**
* @dev Get the maximum amount that users can withdraw
* @param userAddr The address of user
* @param requestedAmount The amount of token to withdraw
* @param collateralableAmount The amount of liquidity that users can borrow
* @return the maximum amount that users can withdraw
*/
function _getUserActionMaxWithdrawAmount(address payable userAddr, uint256 requestedAmount, uint256 collateralableAmount) internal view returns (uint256)
{
uint256 depositAmount = handlerDataStorage.getUserIntraDepositAmount(userAddr);
uint256 handlerLiquidityAmount = _getTokenLiquidityAmount();
/* select minimum among deposited, requested and collateralable*/
uint256 minAmount = depositAmount;
if (minAmount > requestedAmount)
{
minAmount = requestedAmount;
}
if (minAmount > collateralableAmount)
{
minAmount = collateralableAmount;
}
if (minAmount > handlerLiquidityAmount)
{
minAmount = handlerLiquidityAmount;
}
return minAmount;
}
/**
* @dev Get the maximum amount that users can repay
* @param userAddr The address of user
* @return the maximum amount that users can repay
*/
function getUserMaxRepayAmount(address payable userAddr) external view override returns (uint256)
{
uint256 depositAmountWithInterest;
uint256 borrowAmountWithInterest;
(depositAmountWithInterest, borrowAmountWithInterest) = _getUserAmountWithInterest(userAddr);
return borrowAmountWithInterest;
}
/**
* @dev Update (apply) interest entry point (external)
* @param userAddr The user address
* @return "latest" (userDepositAmount, userBorrowAmount)
*/
function applyInterest(address payable userAddr) external override returns (uint256, uint256)
{
return _applyInterest(userAddr);
}
/**
* @dev Update (apply) interest entry point (external)
* @param userAddr The user address
* @return "latest" (userDepositAmount, userBorrowAmount)
*/
function _applyInterest(address payable userAddr) internal returns (uint256, uint256)
{
_checkNewCustomer(userAddr);
_checkFirstAction();
return _updateInterestAmount(userAddr);
}
/**
* @dev Check whether a given userAddr is a new user or not
* @param userAddr The user address
* @return true if the user is a new user; false otherwise.
*/
function _checkNewCustomer(address payable userAddr) internal returns (bool)
{
IMarketHandlerDataStorage _handlerDataStorage = handlerDataStorage;
if (_handlerDataStorage.getUserAccessed(userAddr))
{
return false;
}
/* hotfix */
_handlerDataStorage.setUserAccessed(userAddr, true);
(uint256 gDEXR, uint256 gBEXR) = _handlerDataStorage.getGlobalEXR();
_handlerDataStorage.setUserEXR(userAddr, gDEXR, gBEXR);
return true;
}
/**
* @dev Get the address of the token that the handler is dealing with
* (CoinHandler don't deal with tokens in coin handlers)
* @return The address of the token
*/
function getERC20Addr() external override view returns (address)
{
return address(erc20Instance);
}
/**
* @dev Get the amount of deposit and borrow of the user
* @param userAddr The address of user
* (depositAmount, borrowAmount)
*/
function getUserAmount(address payable userAddr) external view override returns (uint256, uint256)
{
uint256 depositAmount = handlerDataStorage.getUserIntraDepositAmount(userAddr);
uint256 borrowAmount = handlerDataStorage.getUserIntraBorrowAmount(userAddr);
return (depositAmount, borrowAmount);
}
/**
* @dev Get the amount of user's deposit
* @param userAddr The address of user
* @return the amount of user's deposit
*/
function getUserIntraDepositAmount(address payable userAddr) external view returns (uint256)
{
return handlerDataStorage.getUserIntraDepositAmount(userAddr);
}
/**
* @dev Get the amount of user's borrow
* @param userAddr The address of user
* @return the amount of user's borrow
*/
function getUserIntraBorrowAmount(address payable userAddr) external view returns (uint256)
{
return handlerDataStorage.getUserIntraBorrowAmount(userAddr);
}
/**
* @dev Get the amount of handler's total deposit
* @return the amount of handler's total deposit
*/
function getDepositTotalAmount() external view override returns (uint256)
{
return handlerDataStorage.getDepositTotalAmount();
}
/**
* @dev Get the amount of handler's total borrow
* @return the amount of handler's total borrow
*/
function getBorrowTotalAmount() external view override returns (uint256)
{
return handlerDataStorage.getBorrowTotalAmount();
}
/**
* @dev Get the amount of deposit and borrow of user including interest
* @param userAddr The user address
* @return (userDepositAmount, userBorrowAmount)
*/
function getUserAmountWithInterest(address payable userAddr) external view override returns (uint256, uint256)
{
return _getUserAmountWithInterest(userAddr);
}
/**
* @dev Get the address of owner
* @return the address of owner
*/
function getOwner() public view returns (address)
{
return owner;
}
/**
* @dev Check first action of user in the This Block (external)
* @return true for first action
*/
function checkFirstAction() onlyMarketManager external override returns (bool)
{
return _checkFirstAction();
}
/**
* @dev Convert amount of handler's unified decimals to amount of token's underlying decimals
* @param unifiedTokenAmount The amount of unified decimals
* @return (underlyingTokenAmount)
*/
function convertUnifiedToUnderlying(uint256 unifiedTokenAmount) external override view returns (uint256)
{
return _convertUnifiedToUnderlying(unifiedTokenAmount);
}
/**
* @dev Check first action of user in the This Block (external)
* @return true for first action
*/
function _checkFirstAction() internal returns (bool)
{
IMarketHandlerDataStorage _handlerDataStorage = handlerDataStorage;
uint256 lastUpdatedBlock = _handlerDataStorage.getLastUpdatedBlock();
uint256 currentBlockNumber = _blockContext();
uint256 blockDelta = sub(currentBlockNumber, lastUpdatedBlock);
if (blockDelta > 0)
{
_handlerDataStorage.setBlocks(currentBlockNumber, blockDelta);
_handlerDataStorage.syncActionEXR();
return true;
}
return false;
}
/**
* @dev calculate (apply) interest (internal) and call storage update function
* @param userAddr The user address
* @return "latest" (userDepositAmount, userBorrowAmount)
*/
function _updateInterestAmount(address payable userAddr) internal returns (uint256, uint256)
{
bool depositNegativeFlag;
uint256 deltaDepositAmount;
uint256 globalDepositEXR;
bool borrowNegativeFlag;
uint256 deltaBorrowAmount;
uint256 globalBorrowEXR;
/* calculate interest amount and params by call Interest Model */
(depositNegativeFlag, deltaDepositAmount, globalDepositEXR, borrowNegativeFlag, deltaBorrowAmount, globalBorrowEXR) = interestModelInstance.getInterestAmount(address(handlerDataStorage), userAddr, false);
/* update new global EXR to user EXR*/
handlerDataStorage.setEXR(userAddr, globalDepositEXR, globalBorrowEXR);
/* call storage update function for update "latest" interest information */
return _setAmountReflectInterest(userAddr, depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount);
}
/**
* @dev Apply the user's interest
* @param userAddr The user address
* @param depositNegativeFlag the sign of deltaDepositAmount (true for negative)
* @param deltaDepositAmount The delta amount of deposit
* @param borrowNegativeFlag the sign of deltaBorrowAmount (true for negative)
* @param deltaBorrowAmount The delta amount of borrow
* @return "latest" (userDepositAmount, userBorrowAmount)
*/
function _setAmountReflectInterest(address payable userAddr, bool depositNegativeFlag, uint256 deltaDepositAmount, bool borrowNegativeFlag, uint256 deltaBorrowAmount) internal returns (uint256, uint256)
{
uint256 depositTotalAmount;
uint256 userDepositAmount;
uint256 borrowTotalAmount;
uint256 userBorrowAmount;
/* call _getAmountWithInterest for adding user storage amount and interest delta amount (deposit and borrow)*/
(depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) = _getAmountWithInterest(userAddr, depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount);
/* update user amount in storage*/
handlerDataStorage.setAmount(userAddr, depositTotalAmount, borrowTotalAmount, userDepositAmount, userBorrowAmount);
/* update "spread between deposits and borrows" */
_updateReservedAmount(depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount);
return (userDepositAmount, userBorrowAmount);
}
/**
* @dev Get the "latest" user amount of deposit and borrow including interest (internal, view)
* @param userAddr The user address
* @return "latest" (userDepositAmount, userBorrowAmount)
*/
function _getUserAmountWithInterest(address payable userAddr) internal view returns (uint256, uint256)
{
uint256 depositTotalAmount;
uint256 userDepositAmount;
uint256 borrowTotalAmount;
uint256 userBorrowAmount;
(depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) = _calcAmountWithInterest(userAddr);
return (userDepositAmount, userBorrowAmount);
}
/**
* @dev Get the "latest" handler amount of deposit and borrow including interest (internal, view)
* @param userAddr The user address
* @return "latest" (depositTotalAmount, borrowTotalAmount)
*/
function _getTotalAmountWithInterest(address payable userAddr) internal view returns (uint256, uint256)
{
uint256 depositTotalAmount;
uint256 userDepositAmount;
uint256 borrowTotalAmount;
uint256 userBorrowAmount;
(depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) = _calcAmountWithInterest(userAddr);
return (depositTotalAmount, borrowTotalAmount);
}
/**
* @dev The deposit and borrow amount with interest for the user
* @param userAddr The user address
* @return "latest" (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount)
*/
function _calcAmountWithInterest(address payable userAddr) internal view returns (uint256, uint256, uint256, uint256)
{
bool depositNegativeFlag;
uint256 deltaDepositAmount;
uint256 globalDepositEXR;
bool borrowNegativeFlag;
uint256 deltaBorrowAmount;
uint256 globalBorrowEXR;
(depositNegativeFlag, deltaDepositAmount, globalDepositEXR, borrowNegativeFlag, deltaBorrowAmount, globalBorrowEXR) = interestModelInstance.getInterestAmount(address(handlerDataStorage), userAddr, true);
return _getAmountWithInterest(userAddr, depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount);
}
/**
* @dev Calculate "latest" amount with interest for the block delta
* @param userAddr The user address
* @param depositNegativeFlag the sign of deltaDepositAmount (true for negative)
* @param deltaDepositAmount The delta amount of deposit
* @param borrowNegativeFlag the sign of deltaBorrowAmount (true for negative)
* @param deltaBorrowAmount The delta amount of borrow
* @return "latest" (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount)
*/
function _getAmountWithInterest(address payable userAddr, bool depositNegativeFlag, uint256 deltaDepositAmount, bool borrowNegativeFlag, uint256 deltaBorrowAmount) internal view returns (uint256, uint256, uint256, uint256)
{
uint256 depositTotalAmount;
uint256 userDepositAmount;
uint256 borrowTotalAmount;
uint256 userBorrowAmount;
(depositTotalAmount, borrowTotalAmount, userDepositAmount, userBorrowAmount) = handlerDataStorage.getAmount(userAddr);
if (depositNegativeFlag)
{
depositTotalAmount = sub(depositTotalAmount, deltaDepositAmount);
userDepositAmount = sub(userDepositAmount, deltaDepositAmount);
}
else
{
depositTotalAmount = add(depositTotalAmount, deltaDepositAmount);
userDepositAmount = add(userDepositAmount, deltaDepositAmount);
}
if (borrowNegativeFlag)
{
borrowTotalAmount = sub(borrowTotalAmount, deltaBorrowAmount);
userBorrowAmount = sub(userBorrowAmount, deltaBorrowAmount);
}
else
{
borrowTotalAmount = add(borrowTotalAmount, deltaBorrowAmount);
userBorrowAmount = add(userBorrowAmount, deltaBorrowAmount);
}
return (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount);
}
/**
* @dev Update the amount of the reserve
* @param depositNegativeFlag the sign of deltaDepositAmount (true for negative)
* @param deltaDepositAmount The delta amount of deposit
* @param borrowNegativeFlag the sign of deltaBorrowAmount (true for negative)
* @param deltaBorrowAmount The delta amount of borrow
* @return true (TODO: validate results)
*/
function _updateReservedAmount(bool depositNegativeFlag, uint256 deltaDepositAmount, bool borrowNegativeFlag, uint256 deltaBorrowAmount) internal returns (bool)
{
int256 signedDeltaDepositAmount = int(deltaDepositAmount);
int256 signedDeltaBorrowAmount = int(deltaBorrowAmount);
if (depositNegativeFlag)
{
signedDeltaDepositAmount = signedDeltaDepositAmount * (-1);
}
if (borrowNegativeFlag)
{
signedDeltaBorrowAmount = signedDeltaBorrowAmount * (-1);
}
/* signedDeltaReservedAmount is singed amount */
int256 signedDeltaReservedAmount = signedSub(signedDeltaBorrowAmount, signedDeltaDepositAmount);
handlerDataStorage.updateSignedReservedAmount(signedDeltaReservedAmount);
return true;
}
/**
* @dev Sends the handler's assets to the given user
* @param userAddr The address of user
* @param unifiedTokenAmount The amount of token to send in unified token amount
* @return true (TODO: validate results)
*/
function _transfer(address payable userAddr, uint256 unifiedTokenAmount) internal returns (bool)
{
uint256 beforeBalance = erc20Instance.balanceOf(userAddr);
uint256 underlyingAmount = _convertUnifiedToUnderlying(unifiedTokenAmount);
erc20Instance.transfer(userAddr, underlyingAmount);
uint256 afterBalance = erc20Instance.balanceOf(userAddr);
require(underlyingAmount == sub(afterBalance, beforeBalance), TRANSFER);
return true;
}
// TODO: need review
function _approve(address userAddr, uint256 unifiedTokenAmount) internal returns (uint256)
{
uint256 beforeBalance = erc20Instance.allowance(address(this), userAddr);
uint256 underlyingAmount = _convertUnifiedToUnderlying(unifiedTokenAmount);
erc20Instance.approve(userAddr, underlyingAmount);
uint256 afterBalance = erc20Instance.allowance(address(this), userAddr);
require(underlyingAmount == sub(afterBalance, beforeBalance), TRANSFER);
return underlyingAmount;
}
/**
* @dev Sends the assets from the user to the contract
* @param userAddr The address of user
* @param unifiedTokenAmount The amount of token to send in unified token amount
* @return true (TODO: validate results)
*/
function _transferFrom(address payable userAddr, uint256 unifiedTokenAmount) internal returns (bool)
{
uint256 beforeBalance = erc20Instance.balanceOf(userAddr);
uint256 underlyingAmount = _convertUnifiedToUnderlying(unifiedTokenAmount);
erc20Instance.transferFrom(userAddr, address(this), underlyingAmount);
uint256 afterBalance = erc20Instance.balanceOf(userAddr);
require(underlyingAmount == sub(beforeBalance, afterBalance), TRANSFER);
return true;
}
/**
* @dev Convert amount of handler's unified decimals to amount of token's underlying decimals
* @param unifiedTokenAmount The amount of unified decimals
* @return (underlyingTokenAmount)
*/
function _convertUnifiedToUnderlying(uint256 unifiedTokenAmount) internal view returns (uint256)
{
return div(mul(unifiedTokenAmount, underlyingTokenDecimal), unifiedTokenDecimal);
}
/**
* @dev Convert amount of token's underlying decimals to amount of handler's unified decimals
* @param underlyingTokenAmount The amount of underlying decimals
* @return (unifiedTokenAmount)
*/
function _convertUnderlyingToUnified(uint256 underlyingTokenAmount) internal view returns (uint256)
{
return div(mul(underlyingTokenAmount, unifiedTokenDecimal), underlyingTokenDecimal);
}
/**
* @dev Get (total deposit - total borrow) of the handler
* @return (total deposit - total borrow) of the handler
*/
function _getTokenLiquidityAmount() internal view returns (uint256)
{
IMarketHandlerDataStorage _handlerDataStorage = handlerDataStorage;
uint256 depositTotalAmount;
uint256 borrowTotalAmount;
(depositTotalAmount, borrowTotalAmount) = _handlerDataStorage.getHandlerAmount();
if (depositTotalAmount == 0 || depositTotalAmount < borrowTotalAmount)
{
return 0;
}
return sub(depositTotalAmount, borrowTotalAmount);
}
/**
* @dev Get (total deposit * liquidity limit - total borrow) of the handler
* @return (total deposit * liquidity limit - total borrow) of the handler
*/
function _getTokenLiquidityLimitAmount() internal view returns (uint256)
{
IMarketHandlerDataStorage _handlerDataStorage = handlerDataStorage;
uint256 depositTotalAmount;
uint256 borrowTotalAmount;
(depositTotalAmount, borrowTotalAmount) = _handlerDataStorage.getHandlerAmount();
uint256 liquidityDeposit = unifiedMul(depositTotalAmount, _handlerDataStorage.getLiquidityLimit());
if (depositTotalAmount == 0 || liquidityDeposit < borrowTotalAmount) {
return 0;
}
return sub(liquidityDeposit, borrowTotalAmount);
}
/**
* @dev Get (total deposit - total borrow) of the handler including interest
* @param userAddr The user address(for wrapping function, unused)
* @return (total deposit - total borrow) of the handler including interest
*/
function _getTokenLiquidityAmountWithInterest(address payable userAddr) internal view returns (uint256)
{
uint256 depositTotalAmount;
uint256 borrowTotalAmount;
(depositTotalAmount, borrowTotalAmount) = _getTotalAmountWithInterest(userAddr);
if (depositTotalAmount == 0 || depositTotalAmount < borrowTotalAmount)
{
return 0;
}
return sub(depositTotalAmount, borrowTotalAmount);
}
/**
* @dev Get (total deposit * liquidity limit - total borrow) of the handler including interest
* @param userAddr The user address(for wrapping function, unused)
* @return (total deposit * liquidity limit - total borrow) of the handler including interest
*/
function _getTokenLiquidityLimitAmountWithInterest(address payable userAddr) internal view returns (uint256)
{
uint256 depositTotalAmount;
uint256 borrowTotalAmount;
(depositTotalAmount, borrowTotalAmount) = _getTotalAmountWithInterest(userAddr);
uint256 liquidityDeposit = unifiedMul(depositTotalAmount, handlerDataStorage.getLiquidityLimit());
if (depositTotalAmount == 0 || liquidityDeposit < borrowTotalAmount)
{
return 0;
}
return sub(liquidityDeposit, borrowTotalAmount);
}
/**
* @dev Set the unifiedPoint of token's decimal
* @param _unifiedTokenDecimal the unifiedPoint of token's decimal
* @return true (TODO: validate results)
*/
function setUnifiedTokenDecimal(uint256 _unifiedTokenDecimal) onlyOwner external returns (bool)
{
unifiedTokenDecimal = _unifiedTokenDecimal;
return true;
}
/**
* @dev Get the decimal of token
* @return (uint256, uint256) the decimal of token and the unifiedPoint of token's decimal
*/
function getTokenDecimals() external view returns (uint256, uint256)
{
return (underlyingTokenDecimal, unifiedTokenDecimal);
}
/**
* @dev Get the unifiedPoint of token's decimal (for fixed decimal number)
* @return the unifiedPoint of token's decimal
*/
/* default: UnifiedTokenDecimal Function */
function getUnifiedTokenDecimal() external view returns (uint256)
{
return unifiedTokenDecimal;
}
/**
* @dev Get the decimal of the underlying token
* @return the decimal of the underlying token
*/
/* default: UnderlyingTokenDecimal Function */
function getUnderlyingTokenDecimal() external view returns (uint256)
{
return underlyingTokenDecimal;
}
/**
* @dev Set the decimal of token
* @param _underlyingTokenDecimal the decimal of token
* @return true (TODO: validate results)
*/
function setUnderlyingTokenDecimal(uint256 _underlyingTokenDecimal) onlyOwner external returns (bool)
{
underlyingTokenDecimal = _underlyingTokenDecimal;
return true;
}
/**
* @dev Set the address of the marketManager contract
* @param marketManagerAddr The address of the marketManager contract
* @return true (TODO: validate results)
*/
function setMarketManager(address marketManagerAddr) onlyOwner public returns (bool)
{
marketManager = IMarketManager(marketManagerAddr);
return true;
}
/**
* @dev Set the address of the InterestModel contract
* @param interestModelAddr The address of the InterestModel contract
* @return true (TODO: validate results)
*/
function setInterestModel(address interestModelAddr) onlyOwner public returns (bool)
{
interestModelInstance = IInterestModel(interestModelAddr);
return true;
}
/**
* @dev Set the address of the marketDataStorage contract
* @param marketDataStorageAddr The address of the marketDataStorage contract
* @return true (TODO: validate results)
*/
function setHandlerDataStorage(address marketDataStorageAddr) onlyOwner public returns (bool)
{
handlerDataStorage = IMarketHandlerDataStorage(marketDataStorageAddr);
return true;
}
/**
* @dev Set the address and name of the underlying ERC-20 token
* @param erc20Addr The address of ERC-20 token
* @param name The name of ERC-20 token
* @return true (TODO: validate results)
*/
function setErc20(address erc20Addr, string memory name) onlyOwner public returns (bool)
{
erc20Instance = IERC20(erc20Addr);
tokenName = name;
return true;
}
/**
* @dev Set the address of the siHandlerDataStorage contract
* @param SIHandlerDataStorageAddr The address of the siHandlerDataStorage contract
* @return true (TODO: validate results)
*/
function setSiHandlerDataStorage(address SIHandlerDataStorageAddr) onlyOwner public returns (bool)
{
SIHandlerDataStorage = IMarketSIHandlerDataStorage(SIHandlerDataStorageAddr);
return true;
}
/**
* @dev Get the address of the siHandlerDataStorage contract
* @return The address of the siHandlerDataStorage contract
*/
function getSiHandlerDataStorage() public view returns (address)
{
return address(SIHandlerDataStorage);
}
/**
* @dev Get the address of the marketManager contract
* @return The address of the marketManager contract
*/
function getMarketManagerAddr() public view returns (address)
{
return address(marketManager);
}
/**
* @dev Get the address of the InterestModel contract
* @return The address of the InterestModel contract
*/
function getInterestModelAddr() public view returns (address)
{
return address(interestModelInstance);
}
/**
* @dev Get the address of handler's dataStroage
* @return the address of handler's dataStroage
*/
function getHandlerDataStorageAddr() public view returns (address)
{
return address(handlerDataStorage);
}
/**
* @dev Get the address of the underlying ERC-20 token
* @return The address of the underlying ERC-20 token
*/
function getErc20Addr() public view returns (address)
{
return address(erc20Instance);
}
/**
* @dev Get the outgoing limit of tokens
* @return The outgoing limit of tokens
*/
function getLimitOfAction() external view returns (uint256)
{
return handlerDataStorage.getLimitOfAction();
}
function get_interchainManager() external view returns (address) {
return address(interchainManager);
}
function set_interchainManager(IinterchainManager _interchainManager) onlyOwner external returns (bool) {
interchainManager = _interchainManager;
return true;
}
/* ******************* Safe Math ******************* */
// from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol
// Subject to the MIT license.
function add(uint256 a, uint256 b) internal pure returns (uint256)
{
uint256 c = a + b;
require(c >= a, "add overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256)
{
return _sub(a, b, "sub overflow");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256)
{
return _mul(a, b);
}
function div(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(a, b, "div by zero");
}
function mod(uint256 a, uint256 b) internal pure returns (uint256)
{
return _mod(a, b, "mod by zero");
}
function _sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256)
{
require(b <= a, errorMessage);
return a - b;
}
function _mul(uint256 a, uint256 b) internal pure returns (uint256)
{
if (a == 0)
{
return 0;
}
uint256 c = a * b;
require((c / a) == b, "mul overflow");
return c;
}
function _div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256)
{
require(b > 0, errorMessage);
return a / b;
}
function _mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256)
{
require(b != 0, errorMessage);
return a % b;
}
function unifiedDiv(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(_mul(a, unifiedPoint), b, "unified div by zero");
}
function unifiedMul(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(_mul(a, b), unifiedPoint, "unified mul by zero");
}
function signedAdd(int256 a, int256 b) internal pure returns (int256)
{
int256 c = a + b;
require(((b >= 0) && (c >= a)) || ((b < 0) && (c < a)), "SignedSafeMath: addition overflow");
return c;
}
function signedSub(int256 a, int256 b) internal pure returns (int256)
{
int256 c = a - b;
require(((b >= 0) && (c <= a)) || ((b < 0) && (c > a)), "SignedSafeMath: subtraction overflow");
return c;
}
} | Update (apply) interest entry point (external) userAddr The user address return "latest" (userDepositAmount, userBorrowAmount)/ | function applyInterest(address payable userAddr) external override returns (uint256, uint256)
{
return _applyInterest(userAddr);
}
| 1,420,272 |
./full_match/80001/0x6885802fdb3f027b8F45aFfe7fc56592Afe1aaDB/sources/contracts/CyberMarketplace2.sol | cyberVerse.transferFrom( address(this), idToMarketItem[itemId].seller, price ); | function createMarketSale(
address nftContract,
uint256 itemId
) public payable nonReentrant {
uint256 price = idToMarketItem[itemId].price;
uint256 tokenId = idToMarketItem[itemId].tokenId;
require(
cyberVerse.balanceOf(msg.sender) > price,
"Not enought CyberVerse in wallet"
);
cyberVerse.transferFrom(
msg.sender,
idToMarketItem[itemId].seller,
price
);
IERC721(nftContract).transferFrom(address(this), msg.sender, tokenId);
idToMarketItem[itemId].owner = payable(msg.sender);
_itemsSold.increment();
}
| 5,685,590 |
./full_match/4/0x376fbFD580Ff7A26fA3F82E6BFa524cd22d74f85/sources/_jpegmint/contracts/token/ERC721/ERC721Lean.sol | Returns whether `spender` is allowed to manage `tokenId`. Requirements: - `tokenId` must exist./ | function _isApprovedOrOwner(address spender, uint16 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
| 13,328,908 |
./full_match/1/0x9ED98fD1C29018B9342CB8F57A3073B9695f0c02/sources/solidity/contracts/StakeDelegatable.sol | Gets the list of operators of the specified address. return An array of addresses. | function operatorsOf(address _address) public view returns (address[] memory) {
return ownerOperators[_address];
}
| 8,312,233 |
./full_match/1/0x5Bb938861f7561a4Bc2332980CcBC92519173b70/sources/contracts/utils/AuctionOwnable.sol | Sets the auctioneer for the contract to a new account (`newAuctioneer`). Can only be called by the current owner./ | function setAuctioneer(address newAuctioneer) public virtual onlyOwner {
_auctioneer = newAuctioneer;
}
| 8,416,553 |
./full_match/8453/0x3A5E791405526EFaDf1432Bac8d114B77Da3628c/sources/src/farms/LeetChefV1.sol | Update reward variables of the given pool. pid The index of the pool. See `poolInfo`. return pool Returns the pool that was updated. | function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.timestamp > pool.lastRewardTime) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 time = block.timestamp.sub(pool.lastRewardTime);
uint256 primaryTokenReward = time
.mul(primaryTokenPerSecond)
.mul(pool.allocPoint) / totalAllocPoint;
pool.accPrimaryTokenPerShare = pool.accPrimaryTokenPerShare.add(
(primaryTokenReward.mul(ACC_PRIMARY_TOKEN_PRECISION) /
lpSupply)
);
}
pool.lastRewardTime = block.timestamp;
poolInfo[pid] = pool;
emit LogUpdatePool(
pid,
pool.lastRewardTime,
lpSupply,
pool.accPrimaryTokenPerShare
);
}
}
| 11,550,717 |
./full_match/1/0x3Bd85DF9633eF0205206BB519E4dDee152Bb0005/sources/contracts/token/RewardsDistributor.sol | Sends profits and BABL tokens rewards to an address (contributor or heart garden) after a claim is requested to the protocol. _to Address to send the BABL tokens to _babl Amount of BABL to send/ | function _sendBABLToAddress(address _to, uint256 _babl) internal returns (uint256) {
_onlyUnpaused();
uint256 bablBal = babltoken.balanceOf(address(this));
uint256 bablToSend = _babl > bablBal ? bablBal : _babl;
_require(bablToSend <= (maxBablCap != 0 ? maxBablCap : DEFAULT_BABL_CAP), Errors.MAX_BABL_CAP_REACHED);
SafeERC20.safeTransfer(babltoken, _to, bablToSend);
return bablToSend;
}
| 3,050,118 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4 <0.9.0;
import '../Keep3rAccountance.sol';
import '../Keep3rParameters.sol';
import '../../../interfaces/peripherals/IKeep3rKeepers.sol';
import '../../../interfaces/external/IKeep3rV1.sol';
import '../../../interfaces/external/IKeep3rV1Proxy.sol';
import '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
abstract contract Keep3rKeeperFundable is IKeep3rKeeperFundable, ReentrancyGuard, Keep3rParameters {
using EnumerableSet for EnumerableSet.AddressSet;
using SafeERC20 for IERC20;
/// @inheritdoc IKeep3rKeeperFundable
function bond(address _bonding, uint256 _amount) external override nonReentrant {
if (disputes[msg.sender]) revert Disputed();
if (_jobs.contains(msg.sender)) revert AlreadyAJob();
canActivateAfter[msg.sender][_bonding] = block.timestamp + bondTime;
uint256 _before = IERC20(_bonding).balanceOf(address(this));
IERC20(_bonding).safeTransferFrom(msg.sender, address(this), _amount);
_amount = IERC20(_bonding).balanceOf(address(this)) - _before;
hasBonded[msg.sender] = true;
pendingBonds[msg.sender][_bonding] += _amount;
emit Bonding(msg.sender, _bonding, _amount);
}
/// @inheritdoc IKeep3rKeeperFundable
function activate(address _bonding) external override {
if (disputes[msg.sender]) revert Disputed();
if (canActivateAfter[msg.sender][_bonding] == 0) revert BondsUnexistent();
if (canActivateAfter[msg.sender][_bonding] >= block.timestamp) revert BondsLocked();
_activate(msg.sender, _bonding);
}
/// @inheritdoc IKeep3rKeeperFundable
function unbond(address _bonding, uint256 _amount) external override {
canWithdrawAfter[msg.sender][_bonding] = block.timestamp + unbondTime;
bonds[msg.sender][_bonding] -= _amount;
pendingUnbonds[msg.sender][_bonding] += _amount;
emit Unbonding(msg.sender, _bonding, _amount);
}
/// @inheritdoc IKeep3rKeeperFundable
function withdraw(address _bonding) external override nonReentrant {
if (canWithdrawAfter[msg.sender][_bonding] == 0) revert UnbondsUnexistent();
if (canWithdrawAfter[msg.sender][_bonding] >= block.timestamp) revert UnbondsLocked();
if (disputes[msg.sender]) revert Disputed();
uint256 _amount = pendingUnbonds[msg.sender][_bonding];
if (_bonding == keep3rV1) {
IKeep3rV1Proxy(keep3rV1Proxy).mint(_amount);
}
pendingUnbonds[msg.sender][_bonding] = 0;
IERC20(_bonding).safeTransfer(msg.sender, _amount);
emit Withdrawal(msg.sender, _bonding, _amount);
}
function _bond(
address _bonding,
address _from,
uint256 _amount
) internal {
bonds[_from][_bonding] += _amount;
if (_bonding == keep3rV1) {
IKeep3rV1(keep3rV1).burn(_amount);
}
}
function _activate(address _keeper, address _bonding) internal {
if (firstSeen[_keeper] == 0) {
firstSeen[_keeper] = block.timestamp;
}
_keepers.add(_keeper);
uint256 _amount = pendingBonds[_keeper][_bonding];
pendingBonds[_keeper][_bonding] = 0;
_bond(_bonding, _keeper, _amount);
emit Activation(_keeper, _bonding, _amount);
}
}
| @inheritdoc IKeep3rKeeperFundable | function unbond(address _bonding, uint256 _amount) external override {
canWithdrawAfter[msg.sender][_bonding] = block.timestamp + unbondTime;
bonds[msg.sender][_bonding] -= _amount;
pendingUnbonds[msg.sender][_bonding] += _amount;
emit Unbonding(msg.sender, _bonding, _amount);
}
| 1,757,473 |
./partial_match/1/0xEa135c1c267124107F448f454Ad33f24FF521702/sources/StrategyWBTCPickle.sol | require(_p3crv <= pledgePickles, "Invalid amount!"); | function _withdrawSome(uint256 _amount) internal returns(uint256){
uint256 crvBefore = IERC20(crvPla).balanceOf(address(this));
uint256 _crvpla = _amount.mul(1e18).div((ICurveFi(curvefi).get_virtual_price().div(1e10)));
if (crvBefore < _crvpla)
{
_crvpla = _crvpla.sub(crvBefore);
uint256 _p3crv = _crvpla.mul(1e18).div(yERC20(pickleJar).getRatio());
uint _before = IERC20(pickleJar).balanceOf(address(this));
if (_before < _p3crv) {
_p3crv = _p3crv.sub(_before);
if (_p3crv > pledgePickles)
{
_p3crv = pledgePickles;
}
pERC20(PICKLE).withdraw(pickleindex,_p3crv);
pledgePickles = pledgePickles.sub(_p3crv);
}
uint p3CRV = IERC20(pickleJar).balanceOf(address(this));
yERC20(pickleJar).withdraw(p3CRV);
}
uint crv = IERC20(crvPla).balanceOf(address(this));
return withdrawUnderlying(crv);
}
| 3,661,156 |
// UstxDEXv2.sol
// SPDX-License-Identifier: MIT
// solhint-disable-next-line
pragma solidity ^0.8.0;
import "./IUSTX.sol";
import "./IERC20.sol";
import "./Roles.sol";
import "./Initializable.sol";
import "./SafeERC20.sol";
/// @title Up Stable Token eXperiment DEX
/// @author USTX Team
/// @dev This contract implements the DEX functionality for the USTX token (v2).
// solhint-disable-next-line
contract UstxDEX is Initializable {
using Roles for Roles.Role;
//SafeERC20 not needed for USDT(TRC20) and USTX(TRC20)
using SafeERC20 for IERC20;
/***********************************|
| Variables && Events |
|__________________________________*/
//Constants
uint256 private constant MAX_FEE = 200; //maximum fee in BP (2%)
uint256 private constant MAX_LAUNCH_FEE = 1000; //maximum fee during launchpad (10%)
//Variables
uint256 private _decimals; // 6
uint256 private _feeBuy; //buy fee in basis points
uint256 private _feeSell; //sell fee in basis points
uint256 private _targetRatioExp; //target reserve ratio for expansion in TH (1000s) to circulating cap
uint256 private _targetRatioDamp; //target reserve ratio for damping in TH (1000s) to circulating cap
uint256 private _expFactor; //expansion factor in TH
uint256 private _dampFactor; //damping factor in TH
uint256 private _minExp; //minimum expansion in TH
uint256 private _maxDamp; //maximum damping in TH
uint256 private _collectedFees; //amount of collected fees
uint256 private _launchEnabled; //launchpad mode if >=1
uint256 private _launchTargetSize; //number of tokens reserved for launchpad
uint256 private _launchPrice; //Launchpad price
uint256 private _launchBought; //number of tokens bought so far in Launchpad
uint256 private _launchMaxLot; //max number of usdtSold for a single operation during Launchpad
uint256 private _launchFee; //Launchpad fee
address private _launchTeamAddr; //Launchpad team address
bool private _notEntered; //reentrancyguard state
bool private _paused; //pausable state
Roles.Role private _administrators;
uint256 private _numAdmins;
uint256 private _minAdmins;
uint256 private _version; //contract version
uint256[5] private _rtEnable; //reserve token enable
uint256[5] private _rtTradeEnable; //reserve token enable for trading
uint256[5] private _rtValue; //reserve token value in TH (0-1000)
uint256[5] private _rtShift; //reserve token decimal shift
IERC20[5] private _rt; //reserve token address (element 0 is USDT)
IUSTX private _token; // address of USTX token
// Events
event TokenBuy(address indexed buyer, uint256 indexed usdtSold, uint256 indexed tokensBought, uint256 price, uint256 tIndex);
event TokenSell(address indexed buyer, uint256 indexed tokensSold, uint256 indexed usdtBought, uint256 price, uint256 tIndex);
event Snapshot(address indexed operator, uint256 indexed reserveBalance, uint256 indexed tokenBalance);
event Paused(address account);
event Unpaused(address account);
event AdminAdded(address indexed account);
event AdminRemoved(address indexed account);
/**
* @dev initialize function
*
*/
function initialize() public initializer {
_launchTeamAddr = _msgSender();
_decimals = 6;
_feeBuy = 0; //0%
_feeSell = 100; //1%
_targetRatioExp = 240; //24%
_targetRatioDamp = 260; //26%
_expFactor = 1000; //1
_dampFactor = 1000; //1
_minExp = 100; //0.1
_maxDamp = 100; //0.1
_collectedFees = 0;
_launchEnabled = 0;
_notEntered = true;
_paused = false;
_numAdmins=0;
_addAdmin(_msgSender()); //default admin
_minAdmins = 2; //at least 2 admins in charge
_version = 1;
uint256 j; //initialize reserve variables
for (j=0; j<5; j++) {
_rtEnable[j]=0;
_rtTradeEnable[j]=0;
}
}
/**
* @dev upgrade function for V2
*/
//function upgradeToV2() public onlyAdmin {
// require(_version<2,"Contract already up to date");
// _version=2;
// DO THINGS
//}
/***********************************|
| AdminRole |
|__________________________________*/
modifier onlyAdmin() {
require(isAdmin(_msgSender()), "AdminRole: caller does not have the Admin role");
_;
}
function isAdmin(address account) public view returns (bool) {
return _administrators.has(account);
}
function addAdmin(address account) public onlyAdmin {
_addAdmin(account);
}
function renounceAdmin() public {
require(_numAdmins>_minAdmins, "There must always be a minimum number of admins in charge");
_removeAdmin(_msgSender());
}
function _addAdmin(address account) internal {
_administrators.add(account);
_numAdmins++;
emit AdminAdded(account);
}
function _removeAdmin(address account) internal {
_administrators.remove(account);
_numAdmins--;
emit AdminRemoved(account);
}
/***********************************|
| Pausable |
|__________________________________*/
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyAdmin whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyAdmin whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
/***********************************|
| ReentrancyGuard |
|__________________________________*/
/**
* @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(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
/***********************************|
| Context |
|__________________________________*/
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/***********************************|
| Exchange Functions |
|__________________________________*/
/**
* @dev Public function to preview token purchase with exact input in USDT
* @param usdtSold amount of USDT to sell
* @return number of tokens that can be purchased with input usdtSold
*/
function buyTokenInputPreview(uint256 usdtSold) public view returns (uint256) {
require(usdtSold > 0, "USDT sold must greater than 0");
uint256 tokenBalance = _token.balanceOf(address(this));
uint256 reserveBalance = getReserveBalance();
(uint256 tokensBought,,) = _getBoughtMinted(usdtSold,tokenBalance,reserveBalance);
return tokensBought;
}
/**
* @dev Public function to preview token sale with exact input in tokens
* @param tokensSold amount of token to sell
* @return Amount of USDT that can be bought with input Tokens.
*/
function sellTokenInputPreview(uint256 tokensSold) public view returns (uint256) {
require(tokensSold > 0, "Tokens sold must greater than 0");
uint256 tokenBalance = _token.balanceOf(address(this));
uint256 reserveBalance = getReserveBalance();
(uint256 usdtsBought,,) = _getBoughtBurned(tokensSold,tokenBalance,reserveBalance);
return usdtsBought;
}
/**
* @dev Public function to buy tokens during launchpad
* @param rSell amount of UDST to sell
* @param minTokens minimum amount of tokens to buy
* @return number of tokens bought
*/
function buyTokenLaunchInput(uint256 rSell, uint256 tIndex, uint256 minTokens) public whenNotPaused returns (uint256) {
require(_launchEnabled>0,"Function allowed only during launchpad");
require(_launchBought<_launchTargetSize,"Launchpad target reached!");
require(rSell<=_launchMaxLot,"Order too big for Launchpad");
require(tIndex<5, "INVALID_INDEX");
require(_rtEnable[tIndex]>0 && _rtTradeEnable[tIndex]>0,"Token disabled");
return _buyLaunchpadInput(rSell, tIndex, minTokens, _msgSender(), _msgSender());
}
/**
* @dev Public function to buy tokens during launchpad and transfer them to recipient
* @param rSell amount of UDST to sell
* @param minTokens minimum amount of tokens to buy
* @param recipient recipient of the transaction
* @return number of tokens bought
*/
function buyTokenLaunchTransferInput(uint256 rSell, uint256 tIndex, uint256 minTokens, address recipient) public whenNotPaused returns(uint256) {
require(_launchEnabled>0,"Function allowed only during launchpad");
require(recipient != address(this) && recipient != address(0),"Recipient cannot be DEX or address 0");
require(_launchBought<_launchTargetSize,"Launchpad target reached!");
require(rSell<=_launchMaxLot,"Order too big for Launchpad");
require(tIndex<5, "INVALID_INDEX");
require(_rtEnable[tIndex]>0 && _rtTradeEnable[tIndex]>0,"Token disabled");
return _buyLaunchpadInput(rSell, tIndex, minTokens, _msgSender(), recipient);
}
/**
* @dev Public function to buy tokens
* @param rSell amount of UDST to sell
* @param minTokens minimum amount of tokens to buy
* @param tIndex index of the reserve token to swap
* @return number of tokens bought
*/
function buyTokenInput(uint256 rSell, uint256 tIndex, uint256 minTokens) public whenNotPaused returns (uint256) {
require(_launchEnabled==0,"Function not allowed during launchpad");
require(tIndex<5, "INVALID_INDEX");
require(_rtEnable[tIndex]>0 && _rtTradeEnable[tIndex]>0,"Token disabled");
return _buyStableInput(rSell, tIndex, minTokens, _msgSender(), _msgSender());
}
/**
* @dev Public function to buy tokens and transfer them to recipient
* @param rSell amount of UDST to sell
* @param minTokens minimum amount of tokens to buy
* @param tIndex index of the reserve token to swap
* @param recipient recipient of the transaction
* @return number of tokens bought
*/
function buyTokenTransferInput(uint256 rSell, uint256 tIndex, uint256 minTokens, address recipient) public whenNotPaused returns(uint256) {
require(_launchEnabled==0,"Function not allowed during launchpad");
require(recipient != address(this) && recipient != address(0),"Recipient cannot be DEX or address 0");
require(tIndex<5, "INVALID_INDEX");
require(_rtEnable[tIndex]>0 && _rtTradeEnable[tIndex]>0,"Token disabled");
return _buyStableInput(rSell, tIndex, minTokens, _msgSender(), recipient);
}
/**
* @dev Public function to sell tokens
* @param tokensSold number of tokens to sell
* @param minUsdts minimum number of UDST to buy
* @return number of USDTs bought
*/
function sellTokenInput(uint256 tokensSold, uint256 tIndex, uint256 minUsdts) public whenNotPaused returns (uint256) {
require(_launchEnabled==0,"Function not allowed during launchpad");
require(tIndex<5, "INVALID_INDEX");
require(_rtEnable[tIndex]>0 && _rtTradeEnable[tIndex]>0,"Token disabled");
return _sellStableInput(tokensSold, tIndex, minUsdts, _msgSender(), _msgSender());
}
/**
* @dev Public function to sell tokens and trasnfer USDT to recipient
* @param tokensSold number of tokens to sell
* @param minUsdts minimum number of UDST to buy
* @param recipient recipient of the transaction
* @return number of USDTs bought
*/
function sellTokenTransferInput(uint256 tokensSold, uint256 tIndex, uint256 minUsdts, address recipient) public whenNotPaused returns (uint256) {
require(_launchEnabled==0,"Function not allowed during launchpad");
require(recipient != address(this) && recipient != address(0),"Recipient cannot be DEX or address 0");
require(tIndex<5, "INVALID_INDEX");
require(_rtEnable[tIndex]>0 && _rtTradeEnable[tIndex]>0,"Token disabled");
return _sellStableInput(tokensSold, tIndex, minUsdts, _msgSender(), recipient);
}
/**
* @dev public function to setup the reserve after launchpad (onlyAdmin, whenPaused)
* @param startPrice target price
* @return new reserve value
*/
function setupReserve(uint256 startPrice) public onlyAdmin whenPaused returns (uint256) {
require(startPrice>0,"Price cannot be 0");
uint256 tokenBalance = _token.balanceOf(address(this));
uint256 reserveBalance = getReserveBalance();
uint256 newReserve = reserveBalance * (10**_decimals) / startPrice;
uint256 temp;
if (newReserve>tokenBalance) {
temp = newReserve - tokenBalance;
_token.mint(address(this),temp);
} else {
temp = tokenBalance - newReserve;
_token.burn(temp);
}
return newReserve;
}
/**
* @dev public function to swap 1:1 between reserve tokens (onlyAdmin)
* @param amount, amount to swap (6 decimal places)
* @param tIndexIn, index of token to sell
* @param tIndexOut, index of token to buy
* @return amount swapped
*/
function swapReserveTokens(uint256 amount, uint256 tIndexIn, uint256 tIndexOut) public onlyAdmin returns (uint256) {
require(amount > 0,"Amount should be higher than 0");
require(tIndexIn <5 && tIndexOut <5 && tIndexIn != tIndexOut,"Index out of bounds or equal");
require(_rtEnable[tIndexIn]>0 && _rtEnable[tIndexOut]>0,"Tokens disabled");
_swapReserveTokens(amount, tIndexIn, tIndexOut, _msgSender());
return amount;
}
/**
* @dev private function to swap 1:1 between reserve tokens (nonReentrant)
* @param amount, amount to swap (6 decimal places)
* @param tIndexIn, index of token to sell
* @param tIndexOut, index of token to buy
* @param buyer, recipient
* @return amount swapped
*/
function _swapReserveTokens(uint256 amount, uint256 tIndexIn, uint256 tIndexOut, address buyer) private nonReentrant returns (uint256) {
if (tIndexIn==0) {
_rt[tIndexIn].transferFrom(buyer, address(this), amount*(10**_rtShift[tIndexIn]));
} else {
_rt[tIndexIn].safeTransferFrom(buyer, address(this), amount*(10**_rtShift[tIndexIn]));
}
if (tIndexOut==0) {
_rt[tIndexOut].transfer(buyer, amount*(10**_rtShift[tIndexOut]));
} else {
_rt[tIndexOut].safeTransfer(buyer, amount*(10**_rtShift[tIndexOut]));
}
return amount;
}
/**
* @dev Private function to buy tokens with exact input in USDT
*
*/
function _buyStableInput(uint256 usdtSold, uint256 tIndex, uint256 minTokens, address buyer, address recipient) private nonReentrant returns (uint256) {
require(usdtSold > 0 && minTokens > 0,"USDT sold and min tokens should be higher than 0");
uint256 tokenBalance = _token.balanceOf(address(this));
uint256 reserveBalance = getReserveBalance();
(uint256 tokensBought, uint256 minted, uint256 fee) = _getBoughtMinted(usdtSold,tokenBalance,reserveBalance);
_collectedFees = _collectedFees + fee;
fee = fee*(10**_rtShift[tIndex]);
require(tokensBought >= minTokens, "Tokens bought lower than requested minimum amount");
if (minted>0) {
_token.mint(address(this),minted);
}
if (tIndex==0) {
_rt[tIndex].transferFrom(buyer, address(this), usdtSold*(10**_rtShift[tIndex]));
if (fee>0) {
_rt[tIndex].transfer(_launchTeamAddr,fee); //transfer fees to team
}
} else {
_rt[tIndex].safeTransferFrom(buyer, address(this), usdtSold*(10**_rtShift[tIndex]));
if (fee>0) {
_rt[tIndex].safeTransfer(_launchTeamAddr,fee); //transfer fees to team
}
}
_token.transfer(address(recipient),tokensBought);
tokenBalance = _token.balanceOf(address(this)); //update token reserve
reserveBalance = getReserveBalance(); //update usdt reserve
uint256 newPrice = reserveBalance * (10**_decimals) / tokenBalance; //calc new price
emit TokenBuy(buyer, usdtSold, tokensBought, newPrice, tIndex); //emit TokenBuy event
emit Snapshot(buyer, reserveBalance, tokenBalance); //emit Snapshot event
return tokensBought;
}
/**
* @dev Private function to buy tokens during launchpad with exact input in USDT
*
*/
function _buyLaunchpadInput(uint256 usdtSold, uint256 tIndex, uint256 minTokens, address buyer, address recipient) private nonReentrant returns (uint256) {
require(usdtSold > 0 && minTokens > 0, "USDT sold and min tokens should be higher than 0");
uint256 tokensBought = usdtSold * (10**_decimals) / _launchPrice;
uint256 fee = usdtSold * _launchFee * (10**_rtShift[tIndex]) / 10000;
require(tokensBought >= minTokens, "Tokens bought lower than requested minimum amount");
_launchBought = _launchBought + tokensBought;
_token.mint(address(this),tokensBought); //mint new tokens
if (tIndex==0) {
_rt[0].transferFrom(buyer, address(this), usdtSold * (10**_rtShift[tIndex])); //add usdtSold to reserve
_rt[0].transfer(_launchTeamAddr,fee); //transfer fees to team
} else {
_rt[tIndex].safeTransferFrom(buyer, address(this), usdtSold * (10**_rtShift[tIndex])); //add usdtSold to reserve
_rt[tIndex].safeTransfer(_launchTeamAddr,fee); //transfer fees to team
}
_token.transfer(address(recipient),tokensBought); //transfer tokens to recipient
emit TokenBuy(buyer, usdtSold, tokensBought, _launchPrice, tIndex);
emit Snapshot(buyer, getReserveBalance(), _token.balanceOf(address(this)));
return tokensBought;
}
/**
* @dev Private function to sell tokens with exact input in tokens
*
*/
function _sellStableInput(uint256 tokensSold, uint256 tIndex, uint256 minUsdts, address buyer, address recipient) private nonReentrant returns (uint256) {
require(tokensSold > 0 && minUsdts > 0, "Tokens sold and min USDT should be higher than 0");
uint256 tokenBalance = _token.balanceOf(address(this));
uint256 reserveBalance = getReserveBalance();
(uint256 usdtsBought, uint256 burned, uint256 fee) = _getBoughtBurned(tokensSold,tokenBalance,reserveBalance);
_collectedFees = _collectedFees + fee;
fee = fee * (10**_rtShift[tIndex]); //adjust for correct number of decimals
require(usdtsBought >= minUsdts, "USDT bought lower than requested minimum amount");
if (burned>0) {
_token.burn(burned);
}
_token.transferFrom(buyer, address(this), tokensSold); //transfer tokens to DEX
if (tIndex==0) { //USDT no safeERC20
_rt[0].transfer(recipient,usdtsBought * (10**_rtShift[tIndex])); //transfer USDT to user
if (fee>0) {
_rt[0].transfer(_launchTeamAddr,fee); //transfer fees to team
}
} else {
_rt[tIndex].safeTransfer(recipient,usdtsBought * (10**_rtShift[tIndex])); //transfer USDT to user
if (fee>0) {
_rt[tIndex].safeTransfer(_launchTeamAddr,fee); //transfer fees to team
}
}
tokenBalance = _token.balanceOf(address(this)); //update token reserve
reserveBalance = getReserveBalance(); //update usdt reserve
uint256 newPrice = reserveBalance * (10**_decimals) / tokenBalance; //calc new price
emit TokenSell(buyer, tokensSold, usdtsBought, newPrice, tIndex); //emit Token event
emit Snapshot(buyer, reserveBalance, tokenBalance); //emit Snapshot event
return usdtsBought;
}
/**
* @dev Private function to get expansion correction
*
*/
function _getExp(uint256 tokenReserve, uint256 usdtReserve) private view returns (uint256,uint256) {
uint256 tokenCirc = _token.totalSupply(); //total
tokenCirc = tokenCirc - tokenReserve;
uint256 price = getPrice(); //multiplied by 10**decimals
uint256 cirCap = price * tokenCirc; //multiplied by 10**decimals
uint256 ratio = usdtReserve * 1000000000 / cirCap;
uint256 exp = ratio * 1000 / _targetRatioExp;
if (exp<1000) {
exp=1000;
}
exp = exp - 1000;
exp=exp * _expFactor / 1000;
if (exp<_minExp) {
exp=_minExp;
}
if (exp>1000) {
exp = 1000;
}
return (exp,ratio);
}
/**
* @dev Private function to get k exponential factor for expansion
*
*/
function _getKXe(uint256 pool, uint256 trade, uint256 exp) private pure returns (uint256) {
uint256 temp = 1000-exp;
temp = trade * temp;
temp = temp / 1000;
temp = temp + pool;
temp = temp * 1000000000;
uint256 kexp = temp / pool;
return kexp;
}
/**
* @dev Private function to get k exponential factor for damping
*
*/
function _getKXd(uint256 pool, uint256 trade, uint256 exp) private pure returns (uint256) {
uint256 temp = 1000-exp;
temp = trade * temp;
temp = temp / 1000;
temp = temp+ pool;
uint256 kexp = pool * 1000000000 / temp;
return kexp;
}
/**
* @dev Private function to get amount of tokens bought and minted
*
*/
function _getBoughtMinted(uint256 usdtSold, uint256 tokenReserve, uint256 usdtReserve) private view returns (uint256,uint256,uint256) {
uint256 fees = usdtSold * _feeBuy / 10000;
uint256 usdtSoldNet = usdtSold - fees;
(uint256 exp,) = _getExp(tokenReserve,usdtReserve);
uint256 kexp = _getKXe(usdtReserve,usdtSoldNet,exp);
uint256 temp = tokenReserve * usdtReserve; //k
temp = temp * kexp;
temp = temp * kexp;
uint256 kn = temp / 1000000000000000000; //uint256 kn=tokenReserve.mul(usdtReserve).mul(kexp).mul(kexp).div(1000000);
temp = tokenReserve * usdtReserve; //k
usdtReserve = usdtReserve + usdtSoldNet; //uint256 usdtReserveNew= usdtReserve.add(usdtSoldNet);
temp = temp / usdtReserve; //USTXamm
uint256 tokensBought = tokenReserve -temp; //out=tokenReserve-USTXamm
temp=kn / usdtReserve; //USXTPool_n
uint256 minted=temp + tokensBought - tokenReserve;
return (tokensBought, minted, fees);
}
/**
* @dev Private function to get damping correction
*
*/
function _getDamp(uint256 tokenReserve, uint256 usdtReserve) private view returns (uint256,uint256) {
uint256 tokenCirc = _token.totalSupply(); //total
tokenCirc = tokenCirc - tokenReserve;
uint256 price = getPrice(); //multiplied by 10**decimals
uint256 cirCap = price * tokenCirc; //multiplied by 10**decimals
uint256 ratio = usdtReserve * 1000000000/ cirCap; //in TH
if (ratio>_targetRatioDamp) {
ratio=_targetRatioDamp;
}
uint256 damp = _targetRatioDamp - ratio;
damp = damp * _dampFactor / _targetRatioDamp;
if (damp<_maxDamp) {
damp=_maxDamp;
}
if (damp>1000) {
damp = 1000;
}
return (damp,ratio);
}
/**
* @dev Private function to get number of USDT bought and tokens burned
*
*/
function _getBoughtBurned(uint256 tokenSold, uint256 tokenReserve, uint256 usdtReserve) private view returns (uint256,uint256,uint256) {
(uint256 damp,) = _getDamp(tokenReserve,usdtReserve);
uint256 kexp = _getKXd(tokenReserve,tokenSold,damp);
uint256 k = tokenReserve * usdtReserve; //k
uint256 temp = k * kexp;
temp = temp * kexp;
uint256 kn = temp / 1000000000000000000; //uint256 kn=tokenReserve.mul(usdtReserve).mul(kexp).mul(kexp).div(1000000);
tokenReserve = tokenReserve + tokenSold; //USTXpool_n
temp = k / tokenReserve; //USDamm
uint256 usdtsBought = usdtReserve - temp; //out
usdtReserve = temp;
temp = kn / usdtReserve; //USTXPool_n
uint256 burned=tokenReserve - temp;
temp = usdtsBought * _feeSell / 10000; //fee
usdtsBought = usdtsBought - temp;
return (usdtsBought, burned, temp);
}
/**************************************|
| Getter and Setter Functions |
|_____________________________________*/
/**
* @dev Function to set Token address (only admin)
* @param tokenAddress address of the traded token contract
*/
function setTokenAddr(address tokenAddress) public onlyAdmin {
require(tokenAddress != address(0), "INVALID_ADDRESS");
_token = IUSTX(tokenAddress);
}
/**
* @dev Function to set reserve token address (only admin)
* @param reserveAddress address of the reserve token contract
* @param index token index in array 0-4
* @param decimals number of decimals
*/
function setReserveTokenAddr(uint256 index, address reserveAddress, uint256 decimals) public onlyAdmin {
require(reserveAddress != address(0), "INVALID_ADDRESS");
require(index<5, "INVALID_INDEX");
require(decimals>=6, "INVALID_DECIMALS");
_rt[index] = IERC20(reserveAddress);
_rtShift[index] = decimals-_decimals;
_rtEnable[index] = 0;
_rtTradeEnable[index] = 0;
_rtValue[index] = 1000;
}
/**
* @dev Function to enable reserve token (only admin)
* @param index token index in array 0-4
* @param enable 0-1
*/
function setReserveTokenEnable(uint256 index, uint256 enable) public onlyAdmin {
require(index<5, "INVALID_INDEX");
_rtEnable[index] = enable;
}
/**
* @dev Function to enable reserve token trading (only admin)
* @param index token index in array 0-4
* @param enable 0-1
*/
function setReserveTokenTradeEnable(uint256 index, uint256 enable) public onlyAdmin {
require(index<5, "INVALID_INDEX");
_rtTradeEnable[index] = enable;
}
/**
* @dev Function to set reserve token value, relative to 1USD (only admin)
* @param index token index in array 0-4
* @param value in TH (0-1000)
*/
function setReserveTokenValue(uint256 index, uint256 value) public onlyAdmin {
require(index<5, "INVALID_INDEX");
require(value<=1000, "Invalid value range");
_rtValue[index] = value;
}
/**
* @dev Function to set fees (only admin)
* @param feeBuy fee for buy operations (in basis points)
* @param feeSell fee for sell operations (in basis points)
*/
function setFees(uint256 feeBuy, uint256 feeSell) public onlyAdmin {
require(feeBuy<=MAX_FEE && feeSell<=MAX_FEE,"Fees cannot be higher than MAX_FEE");
_feeBuy=feeBuy;
_feeSell=feeSell;
}
/**
* @dev Function to get fees
* @return buy and sell fees in basis points
*
*/
function getFees() public view returns (uint256, uint256) {
return (_feeBuy, _feeSell);
}
/**
* @dev Function to set target ratio level (only admin)
* @param ratioExp target reserve ratio for expansion (in thousandths)
* @param ratioDamp target reserve ratio for damping (in thousandths)
*/
function setTargetRatio(uint256 ratioExp, uint256 ratioDamp) public onlyAdmin {
require(ratioExp<=1000 && ratioExp>=10 && ratioDamp<=1000 && ratioDamp >=10,"Target ratio must be between 1% and 100%");
_targetRatioExp = ratioExp; //in TH
_targetRatioDamp = ratioDamp; //in TH
}
/**
* @dev Function to get target ratio level
* return ratioExp and ratioDamp in thousandths
*
*/
function getTargetRatio() public view returns (uint256, uint256) {
return (_targetRatioExp, _targetRatioDamp);
}
/**
* @dev Function to get currect reserve ratio level
* return current ratio in thousandths
*
*/
function getCurrentRatio() public view returns (uint256) {
uint256 tokenBalance = _token.balanceOf(address(this));
uint256 reserveBalance = getReserveBalance();
uint256 tokenCirc = _token.totalSupply(); //total
tokenCirc = tokenCirc - tokenBalance;
uint256 price = getPrice(); //multiplied by 10**decimals
uint256 cirCap = price * tokenCirc; //multiplied by 10**decimals
uint256 ratio = reserveBalance * 1000000000 / cirCap; //in TH
return ratio;
}
/**
* @dev Function to set target expansion factors (only admin)
* @param expF expansion factor (in thousandths)
* @param minExp minimum expansion coefficient to use (in thousandths)
*/
function setExpFactors(uint256 expF, uint256 minExp) public onlyAdmin {
require(expF<=10000 && minExp<=1000,"Expansion factor cannot be more than 1000% and the minimum expansion cannot be over 100%");
_expFactor=expF;
_minExp=minExp;
}
/**
* @dev Function to get expansion factors
* @return _expFactor and _minExp in thousandths
*
*/
function getExpFactors() public view returns (uint256, uint256) {
return (_expFactor,_minExp);
}
/**
* @dev Function to set target damping factors (only admin)
* @param dampF damping factor (in thousandths)
* @param maxDamp maximum damping to use (in thousandths)
*/
function setDampFactors(uint256 dampF, uint256 maxDamp) public onlyAdmin {
require(dampF<=1000 && maxDamp<=1000,"Damping factor cannot be more than 100% and the maximum damping be over 100%");
_dampFactor=dampF;
_maxDamp=maxDamp;
}
/**
* @dev Function to get damping factors
* @return _dampFactor and _maxDamp in thousandths
*
*/
function getDampFactors() public view returns (uint256, uint256) {
return (_dampFactor,_maxDamp);
}
/**
* @dev Function to get current price
* @return current price
*
*/
function getPrice() public view returns (uint256) {
if (_launchEnabled>0) {
return (_launchPrice);
}else {
uint256 tokenBalance = _token.balanceOf(address(this));
uint256 reserveBalance = getReserveBalance();
return (reserveBalance * (10**_decimals) / tokenBalance); //price with decimals
}
}
/**
* @dev Function to get address of the traded token contract
* @return Address of token that is traded on this exchange
*
*/
function getTokenAddress() public view returns (address) {
return address(_token);
}
/**
* @dev Function to get the address of the reserve token contract
* @param index token index in array 0-4
* @return Address of token, relative decimal shift, enable, gradeenable, value, balance
*/
function getReserveData(uint256 index) public view returns (address, uint256, uint256, uint256, uint256, uint256) {
uint256 bal=_rt[index].balanceOf(address(this));
return (address(_rt[index]), _rtShift[index], _rtEnable[index], _rtTradeEnable[index], _rtValue[index], bal);
}
/**
* @dev Function to get total reserve balance
* @return reserve balance
*/
function getReserveBalance() public view returns (uint256) {
uint256 j=0;
uint256 temp;
uint256 reserve=0;
for (j=0; j<5; j++) {
temp=0;
if (_rtEnable[j]>0) {
temp = _rt[j].balanceOf(address(this));
temp = temp * _rtValue[j] / 1000;
temp = temp / (10**_rtShift[j]);
}
reserve += temp;
}
return reserve;
}
/**
* @dev Function to get current reserves balance
* @return USD reserve, USTX reserve, USTX circulating, collected fees
*/
function getBalances() public view returns (uint256,uint256,uint256,uint256) {
uint256 tokenBalance = _token.balanceOf(address(this));
uint256 reserveBalance = getReserveBalance();
uint256 tokenCirc = _token.totalSupply() - tokenBalance;
return (reserveBalance,tokenBalance,tokenCirc,_collectedFees);
}
/**
* @dev Function to get every reserve token balance
* @return b0, b1, b2, b3, b4 balances
*/
function getEveryReserveBalance() public view returns (uint256,uint256,uint256,uint256,uint256) {
uint256 j=0;
uint256[5] memory b;
for (j=0; j<5; j++) {
if (_rtEnable[j]>0) {
b[j] = _rt[j].balanceOf(address(this));
b[j] = b[j] / (10**_rtShift[j]);
}
}
return (b[0], b[1], b[2], b[3], b[4]);
}
/**
* @dev Function to enable launchpad (only admin)
* @param price launchpad fixed price
* @param target launchpad target USTX sale
* @param maxLot launchpad maximum purchase size in USDT
* @param fee launchpad fee for the dev team (in basis points)
* @return true if launchpad is enabled
*/
function enableLaunchpad(uint256 price, uint256 target, uint256 maxLot, uint256 fee) public onlyAdmin returns (bool) {
require(price>0 && target>0 && maxLot>0 && fee<=MAX_LAUNCH_FEE,"Price, target and max lotsize cannot be 0. Fee must be lower than MAX_LAUNCH_FEE");
_launchPrice = price; //in USDT units
_launchTargetSize = target; //in USTX units
_launchBought = 0; //in USTX units
_launchFee = fee; //in bp
_launchMaxLot = maxLot; //in USDT units
_launchEnabled = 1;
return true;
}
/**
* @dev Function to disable launchpad (only admin)
*
*
*/
function disableLaunchpad() public onlyAdmin {
_launchEnabled = 0;
}
/**
* @dev Function to get launchpad status (only admin)
* @return enabled state, price, amount of tokens bought, target tokens, max ourschase lot, fee
*
*/
function getLaunchpadStatus() public view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
return (_launchEnabled,_launchPrice,_launchBought,_launchTargetSize,_launchMaxLot,_launchFee);
}
/**
* @dev Set team address (only admin)
* @param team address for collecting fees
*/
function setTeamAddress(address team) public onlyAdmin {
require(team != address(0) && team != address(this), "Invalid team address");
_launchTeamAddr = team;
}
}
| Private function to get damping correction/ | function _getDamp(uint256 tokenReserve, uint256 usdtReserve) private view returns (uint256,uint256) {
tokenCirc = tokenCirc - tokenReserve;
if (ratio>_targetRatioDamp) {
ratio=_targetRatioDamp;
}
uint256 damp = _targetRatioDamp - ratio;
damp = damp * _dampFactor / _targetRatioDamp;
if (damp<_maxDamp) {
damp=_maxDamp;
}
if (damp>1000) {
damp = 1000;
}
return (damp,ratio);
}
| 12,534,573 |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.3;
import "./ZkSyncBridgeSwapper.sol";
import "./interfaces/ILido.sol";
import "./interfaces/ICurvePool.sol";
import "./interfaces/IYearnVault.sol";
/**
* @notice Exchanges Eth for the "Yearn vault Curve pool staked Eth" token.
* Indexes:
* 0: Eth
* 1: yvCrvStEth
*/
contract BoostedEthBridgeSwapper is ZkSyncBridgeSwapper {
address public immutable stEth;
address public immutable crvStEth;
address public immutable yvCrvStEth;
ICurvePool public immutable stEthPool;
address public immutable lidoReferral;
constructor(
address _zkSync,
address _l2Account,
address _yvCrvStEth,
address _stEthPool,
address _lidoReferral
)
ZkSyncBridgeSwapper(_zkSync, _l2Account)
{
require(_yvCrvStEth != address(0), "null _yvCrvStEth");
yvCrvStEth = _yvCrvStEth;
address _crvStEth = IYearnVault(_yvCrvStEth).token();
require(_crvStEth != address(0), "null crvStEth");
require(_stEthPool != address(0), "null _stEthPool");
require(_crvStEth == ICurvePool(_stEthPool).lp_token(), "crvStEth mismatch");
crvStEth = _crvStEth;
stEth = ICurvePool(_stEthPool).coins(1);
stEthPool = ICurvePool(_stEthPool);
lidoReferral = _lidoReferral;
}
function exchange(uint256 _indexIn, uint256 _indexOut, uint256 _amountIn) external override returns (uint256 amountOut) {
require(_indexIn + _indexOut == 1, "invalid indexes");
if (_indexIn == 0) {
transferFromZkSync(ETH_TOKEN);
amountOut = swapEthForYvCrv(_amountIn);
transferToZkSync(yvCrvStEth, amountOut);
emit Swapped(ETH_TOKEN, _amountIn, yvCrvStEth, amountOut);
} else {
transferFromZkSync(yvCrvStEth);
amountOut = swapYvCrvForEth(_amountIn);
transferToZkSync(ETH_TOKEN, amountOut);
emit Swapped(yvCrvStEth, _amountIn, ETH_TOKEN, amountOut);
}
}
function swapEthForYvCrv(uint256 _amountIn) public payable returns (uint256) {
// ETH -> crvStETH
uint256 minLpAmount = getMinAmountOut((1 ether * _amountIn) / stEthPool.get_virtual_price());
uint256 crvStEthAmount = stEthPool.add_liquidity{value: _amountIn}([_amountIn, 0], minLpAmount);
// crvStETH -> yvCrvStETH
IERC20(crvStEth).approve(yvCrvStEth, crvStEthAmount);
return IYearnVault(yvCrvStEth).deposit(crvStEthAmount);
}
function swapYvCrvForEth(uint256 _amountIn) public returns (uint256) {
// yvCrvStETH -> crvStETH
uint256 crvStEthAmount = IYearnVault(yvCrvStEth).withdraw(_amountIn);
// crvStETH -> ETH
uint256 minAmountOut = getMinAmountOut((crvStEthAmount * stEthPool.get_virtual_price()) / 1 ether);
return stEthPool.remove_liquidity_one_coin(crvStEthAmount, 0, minAmountOut);
}
function ethPerYvCrvStEth() public view returns (uint256) {
return IYearnVault(yvCrvStEth).pricePerShare() * stEthPool.get_virtual_price() / 1 ether;
}
function yvCrvStEthPerEth() public view returns (uint256) {
return (1 ether ** 2) / ethPerYvCrvStEth();
}
function tokens(uint256 _index) external view returns (address) {
if (_index == 0) {
return ETH_TOKEN;
} else if (_index == 1) {
return yvCrvStEth;
}
revert("invalid _index");
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.3;
import "./interfaces/IZkSync.sol";
import "./interfaces/IBridgeSwapper.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
abstract contract ZkSyncBridgeSwapper is IBridgeSwapper {
// The owner of the contract
address public owner;
// The max slippage accepted for swapping. Defaults to 1% with 6 decimals.
uint256 public slippagePercent = 1e6;
// The ZkSync bridge contract
address public immutable zkSync;
// The L2 market maker account
address public immutable l2Account;
address constant internal ETH_TOKEN = address(0);
event OwnerChanged(address _owner, address _newOwner);
event SlippageChanged(uint256 _slippagePercent);
modifier onlyOwner {
require(msg.sender == owner, "unauthorised");
_;
}
constructor(address _zkSync, address _l2Account) {
zkSync = _zkSync;
l2Account = _l2Account;
owner = msg.sender;
}
function changeOwner(address _newOwner) external onlyOwner {
require(_newOwner != address(0), "invalid input");
owner = _newOwner;
emit OwnerChanged(owner, _newOwner);
}
function changeSlippage(uint256 _slippagePercent) external onlyOwner {
require(_slippagePercent != slippagePercent && _slippagePercent <= 100e6, "invalid slippage");
slippagePercent = _slippagePercent;
emit SlippageChanged(slippagePercent);
}
/**
* @dev Check if there is a pending balance to withdraw in zkSync and withdraw it if applicable.
* @param _token The token to withdraw.
*/
function transferFromZkSync(address _token) internal {
uint128 pendingBalance = IZkSync(zkSync).getPendingBalance(address(this), _token);
if (pendingBalance > 0) {
IZkSync(zkSync).withdrawPendingBalance(payable(address(this)), _token, pendingBalance);
}
}
/**
* @dev Deposit the ETH or ERC20 token to zkSync.
* @param _outputToken The token that was given.
* @param _amountOut The amount of given token.
*/
function transferToZkSync(address _outputToken, uint256 _amountOut) internal {
if (_outputToken == ETH_TOKEN) {
// deposit Eth to L2 bridge
IZkSync(zkSync).depositETH{value: _amountOut}(l2Account);
} else {
// approve the zkSync bridge to take the output token
IERC20(_outputToken).approve(zkSync, _amountOut);
// deposit the output token to the L2 bridge
IZkSync(zkSync).depositERC20(IERC20(_outputToken), toUint104(_amountOut), l2Account);
}
}
/**
* @dev Safety method to recover ETH or ERC20 tokens that are sent to the contract by error.
* @param _token The token to recover.
*/
function recoverToken(address _recipient, address _token) external onlyOwner returns (uint256 balance) {
bool success;
if (_token == ETH_TOKEN) {
balance = address(this).balance;
(success, ) = _recipient.call{value: balance}("");
} else {
balance = IERC20(_token).balanceOf(address(this));
success = IERC20(_token).transfer(_recipient, balance);
}
require(success, "failed to recover");
}
/**
* @dev fallback method to make sure we can receive ETH
*/
receive() external payable {
}
/**
* @dev Returns the minimum accepted out amount.
*/
function getMinAmountOut(uint256 _amountIn) internal view returns (uint256) {
return _amountIn * (100e6 - slippagePercent) / 100e6;
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*/
function toUint104(uint256 value) internal pure returns (uint104) {
require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
return uint104(value);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.3;
interface ILido {
function submit(address _referral) external payable returns (uint256);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.3;
interface ICurvePool {
function coins(uint256 _i) external view returns (address);
function lp_token() external view returns (address);
function get_virtual_price() external view returns (uint256);
function exchange(int128 _i, int128 _j, uint256 _dx, uint256 _minDy) external returns (uint256);
function add_liquidity(uint256[2] calldata _amounts, uint256 _minMintAmount) external payable returns (uint256);
function remove_liquidity_one_coin(uint256 _amount, int128 _i, uint256 _minAmount) external payable returns (uint256);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.3;
interface IYearnVault {
function token() external view returns (address);
function pricePerShare() external view returns (uint256);
function deposit(uint256 _amount) external returns (uint256);
function withdraw(uint256 _maxShares) external returns (uint256);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IZkSync {
function getPendingBalance(address _address, address _token) external view returns (uint128);
function withdrawPendingBalance(address payable _owner, address _token, uint128 _amount) external;
function depositETH(address _zkSyncAddress) external payable;
function depositERC20(IERC20 _token, uint104 _amount, address _zkSyncAddress) external;
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.3;
interface IBridgeSwapper {
event Swapped(address _inputToken, uint256 _amountIn, address _outputToken, uint256 _amountOut);
/**
* @notice Perform an exchange between two tokens
* @dev Index values can usually be found via the constructor arguments (if not hardcoded)
* @param _indexIn Index value for the token to send
* @param _indexOut Index valie of the token to receive
* @param _amountIn Amount of `_indexIn` being exchanged
* @return Actual amount of `_indexOut` received
*/
function exchange(uint256 _indexIn, uint256 _indexOut, uint256 _amountIn) external returns (uint256);
}
// 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);
} | yvCrvStETH -> crvStETH crvStETH -> ETH | function swapYvCrvForEth(uint256 _amountIn) public returns (uint256) {
uint256 crvStEthAmount = IYearnVault(yvCrvStEth).withdraw(_amountIn);
uint256 minAmountOut = getMinAmountOut((crvStEthAmount * stEthPool.get_virtual_price()) / 1 ether);
return stEthPool.remove_liquidity_one_coin(crvStEthAmount, 0, minAmountOut);
}
| 14,004,963 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.