contract_name
stringlengths
1
61
file_path
stringlengths
5
50.4k
contract_address
stringlengths
42
42
language
stringclasses
1 value
class_name
stringlengths
1
61
class_code
stringlengths
4
330k
class_documentation
stringlengths
0
29.1k
class_documentation_type
stringclasses
6 values
func_name
stringlengths
0
62
func_code
stringlengths
1
303k
func_documentation
stringlengths
2
14.9k
func_documentation_type
stringclasses
4 values
compiler_version
stringlengths
15
42
license_type
stringclasses
14 values
swarm_source
stringlengths
0
71
meta
dict
__index_level_0__
int64
0
60.4k
DexBrokerage
DexBrokerage.sol
0x41a5b8aa081dcd69ace566061d5b6adcb92cae1c
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // require(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // require(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev a to power of b, throws on overflow. */ function pow(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a ** b; require(c >= a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
pow
function pow(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a ** b; require(c >= a); return c; }
/** * @dev a to power of b, throws on overflow. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://08d43b7bceff4c3bda6099d6bfe95f6f51fadf64d77309ccc487dda94eb6b121
{ "func_code_index": [ 1127, 1265 ] }
59,561
DexBrokerage
DexBrokerage.sol
0x41a5b8aa081dcd69ace566061d5b6adcb92cae1c
Solidity
Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://08d43b7bceff4c3bda6099d6bfe95f6f51fadf64d77309ccc487dda94eb6b121
{ "func_code_index": [ 635, 816 ] }
59,562
DexBrokerage
DexBrokerage.sol
0x41a5b8aa081dcd69ace566061d5b6adcb92cae1c
Solidity
DexBrokerage
contract DexBrokerage is Ownable { using SafeMath for uint256; address public feeAccount; uint256 public makerFee; uint256 public takerFee; uint256 public inactivityReleasePeriod; mapping (address => bool) public approvedCurrencyTokens; mapping (address => uint256) public invalidOrder; mapping (address => mapping (address => uint256)) public tokens; mapping (address => bool) public admins; mapping (address => uint256) public lastActiveTransaction; mapping (bytes32 => uint256) public orderFills; mapping (bytes32 => bool) public withdrawn; event Trade(address tokenBuy, uint256 amountBuy, address tokenSell, uint256 amountSell, address maker, address taker); event Deposit(address token, address user, uint256 amount, uint256 balance); event Withdraw(address token, address user, uint256 amount, uint256 balance); event MakerFeeUpdated(uint256 oldFee, uint256 newFee); event TakerFeeUpdated(uint256 oldFee, uint256 newFee); modifier onlyAdmin { require(msg.sender == owner || admins[msg.sender]); _; } constructor(uint256 _makerFee, uint256 _takerFee , address _feeAccount, uint256 _inactivityReleasePeriod) public { owner = msg.sender; makerFee = _makerFee; takerFee = _takerFee; feeAccount = _feeAccount; inactivityReleasePeriod = _inactivityReleasePeriod; } function approveCurrencyTokenAddress(address currencyTokenAddress, bool isApproved) onlyAdmin public { approvedCurrencyTokens[currencyTokenAddress] = isApproved; } function invalidateOrdersBefore(address user, uint256 nonce) onlyAdmin public { require(nonce >= invalidOrder[user]); invalidOrder[user] = nonce; } function setMakerFee(uint256 _makerFee) onlyAdmin public { //market maker fee will never be more than 1% uint256 oldFee = makerFee; if (_makerFee > 10 finney) { _makerFee = 10 finney; } require(makerFee != _makerFee); makerFee = _makerFee; emit MakerFeeUpdated(oldFee, makerFee); } function setTakerFee(uint256 _takerFee) onlyAdmin public { //market taker fee will never be more than 2% uint256 oldFee = takerFee; if (_takerFee > 20 finney) { _takerFee = 20 finney; } require(takerFee != _takerFee); takerFee = _takerFee; emit TakerFeeUpdated(oldFee, takerFee); } function setInactivityReleasePeriod(uint256 expire) onlyAdmin public returns (bool) { require(expire <= 50000); inactivityReleasePeriod = expire; return true; } function setAdmin(address admin, bool isAdmin) onlyOwner public { admins[admin] = isAdmin; } function depositToken(address token, uint256 amount) public { receiveTokenDeposit(token, msg.sender, amount); } function receiveTokenDeposit(address token, address from, uint256 amount) public { tokens[token][from] = tokens[token][from].add(amount); lastActiveTransaction[from] = block.number; require(ERC20(token).transferFrom(from, address(this), amount)); emit Deposit(token, from, amount, tokens[token][from]); } function deposit() payable public { tokens[address(0)][msg.sender] = tokens[address(0)][msg.sender].add(msg.value); lastActiveTransaction[msg.sender] = block.number; emit Deposit(address(0), msg.sender, msg.value, tokens[address(0)][msg.sender]); } function withdraw(address token, uint256 amount) public returns (bool) { require(block.number.sub(lastActiveTransaction[msg.sender]) >= inactivityReleasePeriod); require(tokens[token][msg.sender] >= amount); tokens[token][msg.sender] = tokens[token][msg.sender].sub(amount); if (token == address(0)) { msg.sender.transfer(amount); } else { require(ERC20(token).transfer(msg.sender, amount)); } emit Withdraw(token, msg.sender, amount, tokens[token][msg.sender]); return true; } function adminWithdraw(address token, uint256 amount, address user, uint256 nonce, uint8 v, bytes32 r, bytes32 s, uint256 gasCost) onlyAdmin public returns (bool) { //gasCost will never be more than 30 finney if (gasCost > 30 finney) gasCost = 30 finney; if(token == address(0)){ require(tokens[address(0)][user] >= gasCost.add(amount)); } else { require(tokens[address(0)][user] >= gasCost); require(tokens[token][user] >= amount); } bytes32 hash = keccak256(address(this), token, amount, user, nonce); require(!withdrawn[hash]); withdrawn[hash] = true; require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) == user); if(token == address(0)){ tokens[address(0)][user] = tokens[address(0)][user].sub(gasCost.add(amount)); tokens[address(0)][feeAccount] = tokens[address(0)][feeAccount].add(gasCost); user.transfer(amount); } else { tokens[token][user] = tokens[token][user].sub(amount); tokens[address(0)][user] = tokens[address(0)][user].sub(gasCost); tokens[address(0)][feeAccount] = tokens[address(0)][feeAccount].add(gasCost); require(ERC20(token).transfer(user, amount)); } lastActiveTransaction[user] = block.number; emit Withdraw(token, user, amount, tokens[token][user]); return true; } function balanceOf(address token, address user) view public returns (uint256) { return tokens[token][user]; } /* tradeValues [0] amountBuy [1] amountSell [2] makerNonce [3] takerAmountBuy [4] takerAmountSell [5] takerExpires [6] takerNonce [7] makerAmountBuy [8] makerAmountSell [9] makerExpires [10] gasCost tradeAddressses [0] tokenBuy [1] tokenSell [2] maker [3] taker */ function trade(uint256[11] tradeValues, address[4] tradeAddresses, uint8[2] v, bytes32[4] rs) onlyAdmin public returns (bool) { uint256 price = tradeValues[0].mul(1 ether).div(tradeValues[1]); require(price >= tradeValues[7].mul(1 ether).div(tradeValues[8]).sub(100000 wei)); require(price <= tradeValues[4].mul(1 ether).div(tradeValues[3]).add(100000 wei)); require(block.number < tradeValues[9]); require(block.number < tradeValues[5]); require(invalidOrder[tradeAddresses[2]] <= tradeValues[2]); require(invalidOrder[tradeAddresses[3]] <= tradeValues[6]); bytes32 orderHash = keccak256(address(this), tradeAddresses[0], tradeValues[7], tradeAddresses[1], tradeValues[8], tradeValues[9], tradeValues[2], tradeAddresses[2]); bytes32 tradeHash = keccak256(address(this), tradeAddresses[1], tradeValues[3], tradeAddresses[0], tradeValues[4], tradeValues[5], tradeValues[6], tradeAddresses[3]); require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", orderHash), v[0], rs[0], rs[1]) == tradeAddresses[2]); require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", tradeHash), v[1], rs[2], rs[3]) == tradeAddresses[3]); require(tokens[tradeAddresses[0]][tradeAddresses[3]] >= tradeValues[0]); require(tokens[tradeAddresses[1]][tradeAddresses[2]] >= tradeValues[1]); if ((tradeAddresses[0] == address(0) || tradeAddresses[1] == address(0)) && tradeValues[10] > 30 finney) tradeValues[10] = 30 finney; if ((approvedCurrencyTokens[tradeAddresses[0]] == true || approvedCurrencyTokens[tradeAddresses[1]] == true) && tradeValues[10] > 10 ether) tradeValues[10] = 10 ether; if(tradeAddresses[0] == address(0) || approvedCurrencyTokens[tradeAddresses[0]] == true){ require(orderFills[orderHash].add(tradeValues[1]) <= tradeValues[8]); require(orderFills[tradeHash].add(tradeValues[1]) <= tradeValues[3]); //tradeAddresses[0] is ether uint256 valueInTokens = tradeValues[1]; //move tokens tokens[tradeAddresses[1]][tradeAddresses[2]] = tokens[tradeAddresses[1]][tradeAddresses[2]].sub(valueInTokens); tokens[tradeAddresses[1]][tradeAddresses[3]] = tokens[tradeAddresses[1]][tradeAddresses[3]].add(valueInTokens); //from taker, take ether payment, fee and gasCost tokens[tradeAddresses[0]][tradeAddresses[3]] = tokens[tradeAddresses[0]][tradeAddresses[3]].sub(tradeValues[0]); tokens[tradeAddresses[0]][tradeAddresses[3]] = tokens[tradeAddresses[0]][tradeAddresses[3]].sub(takerFee.mul(tradeValues[0]).div(1 ether)); tokens[tradeAddresses[0]][tradeAddresses[3]] = tokens[tradeAddresses[0]][tradeAddresses[3]].sub(tradeValues[10]); //to maker add ether payment, take fee tokens[tradeAddresses[0]][tradeAddresses[2]] = tokens[tradeAddresses[0]][tradeAddresses[2]].add(tradeValues[0]); tokens[tradeAddresses[0]][tradeAddresses[2]] = tokens[tradeAddresses[0]][tradeAddresses[2]].sub(makerFee.mul(tradeValues[0]).div(1 ether)); // take maker fee, taker fee and gasCost tokens[tradeAddresses[0]][feeAccount] = tokens[tradeAddresses[0]][feeAccount].add(makerFee.mul(tradeValues[0]).div(1 ether)); tokens[tradeAddresses[0]][feeAccount] = tokens[tradeAddresses[0]][feeAccount].add(takerFee.mul(tradeValues[0]).div(1 ether)); tokens[tradeAddresses[0]][feeAccount] = tokens[tradeAddresses[0]][feeAccount].add(tradeValues[10]); orderFills[orderHash] = orderFills[orderHash].add(tradeValues[1]); orderFills[tradeHash] = orderFills[tradeHash].add(tradeValues[1]); } else { require(orderFills[orderHash].add(tradeValues[0]) <= tradeValues[7]); require(orderFills[tradeHash].add(tradeValues[0]) <= tradeValues[4]); //tradeAddresses[0] is token uint256 valueInEth = tradeValues[1]; //move tokens //changed tradeValues to 0 tokens[tradeAddresses[0]][tradeAddresses[3]] = tokens[tradeAddresses[0]][tradeAddresses[3]].sub(tradeValues[0]); tokens[tradeAddresses[0]][tradeAddresses[2]] = tokens[tradeAddresses[0]][tradeAddresses[2]].add(tradeValues[0]); //from maker, take ether payment and fee tokens[tradeAddresses[1]][tradeAddresses[2]] = tokens[tradeAddresses[1]][tradeAddresses[2]].sub(valueInEth); tokens[tradeAddresses[1]][tradeAddresses[2]] = tokens[tradeAddresses[1]][tradeAddresses[2]].sub(makerFee.mul(valueInEth).div(1 ether)); //add ether payment to taker, take fee, take gasCost tokens[tradeAddresses[1]][tradeAddresses[3]] = tokens[tradeAddresses[1]][tradeAddresses[3]].add(valueInEth); tokens[tradeAddresses[1]][tradeAddresses[3]] = tokens[tradeAddresses[1]][tradeAddresses[3]].sub(takerFee.mul(valueInEth).div(1 ether)); tokens[tradeAddresses[1]][tradeAddresses[3]] = tokens[tradeAddresses[1]][tradeAddresses[3]].sub(tradeValues[10]); //take maker fee, taker fee and gasCost tokens[tradeAddresses[1]][feeAccount] = tokens[tradeAddresses[1]][feeAccount].add(makerFee.mul(valueInEth).div(1 ether)); tokens[tradeAddresses[1]][feeAccount] = tokens[tradeAddresses[1]][feeAccount].add(takerFee.mul(valueInEth).div(1 ether)); tokens[tradeAddresses[1]][feeAccount] = tokens[tradeAddresses[1]][feeAccount].add(tradeValues[10]); orderFills[orderHash] = orderFills[orderHash].add(tradeValues[0]); orderFills[tradeHash] = orderFills[tradeHash].add(tradeValues[0]); } lastActiveTransaction[tradeAddresses[2]] = block.number; lastActiveTransaction[tradeAddresses[3]] = block.number; emit Trade(tradeAddresses[0], tradeValues[0], tradeAddresses[1], tradeValues[1], tradeAddresses[2], tradeAddresses[3]); return true; } }
trade
function trade(uint256[11] tradeValues, address[4] tradeAddresses, uint8[2] v, bytes32[4] rs) onlyAdmin public returns (bool) { uint256 price = tradeValues[0].mul(1 ether).div(tradeValues[1]); require(price >= tradeValues[7].mul(1 ether).div(tradeValues[8]).sub(100000 wei)); require(price <= tradeValues[4].mul(1 ether).div(tradeValues[3]).add(100000 wei)); require(block.number < tradeValues[9]); require(block.number < tradeValues[5]); require(invalidOrder[tradeAddresses[2]] <= tradeValues[2]); require(invalidOrder[tradeAddresses[3]] <= tradeValues[6]); bytes32 orderHash = keccak256(address(this), tradeAddresses[0], tradeValues[7], tradeAddresses[1], tradeValues[8], tradeValues[9], tradeValues[2], tradeAddresses[2]); bytes32 tradeHash = keccak256(address(this), tradeAddresses[1], tradeValues[3], tradeAddresses[0], tradeValues[4], tradeValues[5], tradeValues[6], tradeAddresses[3]); require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", orderHash), v[0], rs[0], rs[1]) == tradeAddresses[2]); require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", tradeHash), v[1], rs[2], rs[3]) == tradeAddresses[3]); require(tokens[tradeAddresses[0]][tradeAddresses[3]] >= tradeValues[0]); require(tokens[tradeAddresses[1]][tradeAddresses[2]] >= tradeValues[1]); if ((tradeAddresses[0] == address(0) || tradeAddresses[1] == address(0)) && tradeValues[10] > 30 finney) tradeValues[10] = 30 finney; if ((approvedCurrencyTokens[tradeAddresses[0]] == true || approvedCurrencyTokens[tradeAddresses[1]] == true) && tradeValues[10] > 10 ether) tradeValues[10] = 10 ether; if(tradeAddresses[0] == address(0) || approvedCurrencyTokens[tradeAddresses[0]] == true){ require(orderFills[orderHash].add(tradeValues[1]) <= tradeValues[8]); require(orderFills[tradeHash].add(tradeValues[1]) <= tradeValues[3]); //tradeAddresses[0] is ether uint256 valueInTokens = tradeValues[1]; //move tokens tokens[tradeAddresses[1]][tradeAddresses[2]] = tokens[tradeAddresses[1]][tradeAddresses[2]].sub(valueInTokens); tokens[tradeAddresses[1]][tradeAddresses[3]] = tokens[tradeAddresses[1]][tradeAddresses[3]].add(valueInTokens); //from taker, take ether payment, fee and gasCost tokens[tradeAddresses[0]][tradeAddresses[3]] = tokens[tradeAddresses[0]][tradeAddresses[3]].sub(tradeValues[0]); tokens[tradeAddresses[0]][tradeAddresses[3]] = tokens[tradeAddresses[0]][tradeAddresses[3]].sub(takerFee.mul(tradeValues[0]).div(1 ether)); tokens[tradeAddresses[0]][tradeAddresses[3]] = tokens[tradeAddresses[0]][tradeAddresses[3]].sub(tradeValues[10]); //to maker add ether payment, take fee tokens[tradeAddresses[0]][tradeAddresses[2]] = tokens[tradeAddresses[0]][tradeAddresses[2]].add(tradeValues[0]); tokens[tradeAddresses[0]][tradeAddresses[2]] = tokens[tradeAddresses[0]][tradeAddresses[2]].sub(makerFee.mul(tradeValues[0]).div(1 ether)); // take maker fee, taker fee and gasCost tokens[tradeAddresses[0]][feeAccount] = tokens[tradeAddresses[0]][feeAccount].add(makerFee.mul(tradeValues[0]).div(1 ether)); tokens[tradeAddresses[0]][feeAccount] = tokens[tradeAddresses[0]][feeAccount].add(takerFee.mul(tradeValues[0]).div(1 ether)); tokens[tradeAddresses[0]][feeAccount] = tokens[tradeAddresses[0]][feeAccount].add(tradeValues[10]); orderFills[orderHash] = orderFills[orderHash].add(tradeValues[1]); orderFills[tradeHash] = orderFills[tradeHash].add(tradeValues[1]); } else { require(orderFills[orderHash].add(tradeValues[0]) <= tradeValues[7]); require(orderFills[tradeHash].add(tradeValues[0]) <= tradeValues[4]); //tradeAddresses[0] is token uint256 valueInEth = tradeValues[1]; //move tokens //changed tradeValues to 0 tokens[tradeAddresses[0]][tradeAddresses[3]] = tokens[tradeAddresses[0]][tradeAddresses[3]].sub(tradeValues[0]); tokens[tradeAddresses[0]][tradeAddresses[2]] = tokens[tradeAddresses[0]][tradeAddresses[2]].add(tradeValues[0]); //from maker, take ether payment and fee tokens[tradeAddresses[1]][tradeAddresses[2]] = tokens[tradeAddresses[1]][tradeAddresses[2]].sub(valueInEth); tokens[tradeAddresses[1]][tradeAddresses[2]] = tokens[tradeAddresses[1]][tradeAddresses[2]].sub(makerFee.mul(valueInEth).div(1 ether)); //add ether payment to taker, take fee, take gasCost tokens[tradeAddresses[1]][tradeAddresses[3]] = tokens[tradeAddresses[1]][tradeAddresses[3]].add(valueInEth); tokens[tradeAddresses[1]][tradeAddresses[3]] = tokens[tradeAddresses[1]][tradeAddresses[3]].sub(takerFee.mul(valueInEth).div(1 ether)); tokens[tradeAddresses[1]][tradeAddresses[3]] = tokens[tradeAddresses[1]][tradeAddresses[3]].sub(tradeValues[10]); //take maker fee, taker fee and gasCost tokens[tradeAddresses[1]][feeAccount] = tokens[tradeAddresses[1]][feeAccount].add(makerFee.mul(valueInEth).div(1 ether)); tokens[tradeAddresses[1]][feeAccount] = tokens[tradeAddresses[1]][feeAccount].add(takerFee.mul(valueInEth).div(1 ether)); tokens[tradeAddresses[1]][feeAccount] = tokens[tradeAddresses[1]][feeAccount].add(tradeValues[10]); orderFills[orderHash] = orderFills[orderHash].add(tradeValues[0]); orderFills[tradeHash] = orderFills[tradeHash].add(tradeValues[0]); } lastActiveTransaction[tradeAddresses[2]] = block.number; lastActiveTransaction[tradeAddresses[3]] = block.number; emit Trade(tradeAddresses[0], tradeValues[0], tradeAddresses[1], tradeValues[1], tradeAddresses[2], tradeAddresses[3]); return true; }
/* tradeValues [0] amountBuy [1] amountSell [2] makerNonce [3] takerAmountBuy [4] takerAmountSell [5] takerExpires [6] takerNonce [7] makerAmountBuy [8] makerAmountSell [9] makerExpires [10] gasCost tradeAddressses [0] tokenBuy [1] tokenSell [2] maker [3] taker */
Comment
v0.4.25+commit.59dbf8f1
bzzr://08d43b7bceff4c3bda6099d6bfe95f6f51fadf64d77309ccc487dda94eb6b121
{ "func_code_index": [ 5850, 11582 ] }
59,563
UniBlueFinance
UniBlueFinance.sol
0xfa72c4d6dbaff668b7905cd4076efd8062c81066
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. **/ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. **/ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). **/ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. **/ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
mul
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 Multiplies two numbers, throws on overflow. **/
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://dd83d5462f253f5f6aca7764840442bc7ef046242505fa42b84d4e4bf6258aae
{ "func_code_index": [ 96, 303 ] }
59,564
UniBlueFinance
UniBlueFinance.sol
0xfa72c4d6dbaff668b7905cd4076efd8062c81066
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. **/ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. **/ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). **/ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. **/ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
div
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 Integer division of two numbers, truncating the quotient. **/
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://dd83d5462f253f5f6aca7764840442bc7ef046242505fa42b84d4e4bf6258aae
{ "func_code_index": [ 400, 700 ] }
59,565
UniBlueFinance
UniBlueFinance.sol
0xfa72c4d6dbaff668b7905cd4076efd8062c81066
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. **/ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. **/ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). **/ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. **/ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; }
/** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). **/
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://dd83d5462f253f5f6aca7764840442bc7ef046242505fa42b84d4e4bf6258aae
{ "func_code_index": [ 827, 955 ] }
59,566
UniBlueFinance
UniBlueFinance.sol
0xfa72c4d6dbaff668b7905cd4076efd8062c81066
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. **/ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. **/ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). **/ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. **/ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
add
function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; }
/** * @dev Adds two numbers, throws on overflow. **/
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://dd83d5462f253f5f6aca7764840442bc7ef046242505fa42b84d4e4bf6258aae
{ "func_code_index": [ 1032, 1178 ] }
59,567
UniBlueFinance
UniBlueFinance.sol
0xfa72c4d6dbaff668b7905cd4076efd8062c81066
Solidity
Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender account. **/ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. **/ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. **/ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". **/
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. **/
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://dd83d5462f253f5f6aca7764840442bc7ef046242505fa42b84d4e4bf6258aae
{ "func_code_index": [ 665, 856 ] }
59,568
UniBlueFinance
UniBlueFinance.sol
0xfa72c4d6dbaff668b7905cd4076efd8062c81066
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence **/ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. **/ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. **/ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. **/
NatSpecMultiLine
totalSupply
function totalSupply() public view returns (uint256) { return totalSupply_; }
/** * @dev total number of tokens in existence **/
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://dd83d5462f253f5f6aca7764840442bc7ef046242505fa42b84d4e4bf6258aae
{ "func_code_index": [ 214, 310 ] }
59,569
UniBlueFinance
UniBlueFinance.sol
0xfa72c4d6dbaff668b7905cd4076efd8062c81066
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence **/ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. **/ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. **/ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. **/
NatSpecMultiLine
transfer
function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. **/
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://dd83d5462f253f5f6aca7764840442bc7ef046242505fa42b84d4e4bf6258aae
{ "func_code_index": [ 487, 855 ] }
59,570
UniBlueFinance
UniBlueFinance.sol
0xfa72c4d6dbaff668b7905cd4076efd8062c81066
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence **/ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. **/ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. **/ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. **/
NatSpecMultiLine
balanceOf
function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; }
/** * @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. **/
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://dd83d5462f253f5f6aca7764840442bc7ef046242505fa42b84d4e4bf6258aae
{ "func_code_index": [ 1080, 1192 ] }
59,571
UniBlueFinance
UniBlueFinance.sol
0xfa72c4d6dbaff668b7905cd4076efd8062c81066
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred **/ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. **/ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. **/ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. **/ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. **/ function decreaseApproval(address _spender, 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); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; }
/** * @dev 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 **/
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://dd83d5462f253f5f6aca7764840442bc7ef046242505fa42b84d4e4bf6258aae
{ "func_code_index": [ 410, 917 ] }
59,572
UniBlueFinance
UniBlueFinance.sol
0xfa72c4d6dbaff668b7905cd4076efd8062c81066
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred **/ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. **/ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. **/ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. **/ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. **/ function decreaseApproval(address _spender, 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); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
approve
function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _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. **/
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://dd83d5462f253f5f6aca7764840442bc7ef046242505fa42b84d4e4bf6258aae
{ "func_code_index": [ 1574, 1785 ] }
59,573
UniBlueFinance
UniBlueFinance.sol
0xfa72c4d6dbaff668b7905cd4076efd8062c81066
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred **/ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. **/ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. **/ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. **/ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. **/ function decreaseApproval(address _spender, 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); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
allowance
function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; }
/** * @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. **/
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://dd83d5462f253f5f6aca7764840442bc7ef046242505fa42b84d4e4bf6258aae
{ "func_code_index": [ 2126, 2265 ] }
59,574
UniBlueFinance
UniBlueFinance.sol
0xfa72c4d6dbaff668b7905cd4076efd8062c81066
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred **/ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. **/ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. **/ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. **/ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. **/ function decreaseApproval(address _spender, 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); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
increaseApproval
function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
/** * @dev 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. **/
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://dd83d5462f253f5f6aca7764840442bc7ef046242505fa42b84d4e4bf6258aae
{ "func_code_index": [ 2756, 3041 ] }
59,575
UniBlueFinance
UniBlueFinance.sol
0xfa72c4d6dbaff668b7905cd4076efd8062c81066
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred **/ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. **/ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. **/ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. **/ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. **/ function decreaseApproval(address _spender, 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); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
decreaseApproval
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); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
/** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. **/
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://dd83d5462f253f5f6aca7764840442bc7ef046242505fa42b84d4e4bf6258aae
{ "func_code_index": [ 3537, 3992 ] }
59,576
UniBlueFinance
UniBlueFinance.sol
0xfa72c4d6dbaff668b7905cd4076efd8062c81066
Solidity
CrowdsaleToken
contract CrowdsaleToken is StandardToken, Configurable, Ownable { /** * @dev enum of current crowd sale state **/ enum Stages { none, icoStart, icoEnd } Stages currentStage; /** * @dev constructor of CrowdsaleToken **/ constructor() public { currentStage = Stages.none; balances[owner] = balances[owner].add(tokenReserve); totalSupply_ = totalSupply_.add(tokenReserve); remainingTokens = cap; emit Transfer(address(this), owner, tokenReserve); } /** * @dev fallback function to send ether to for Crowd sale **/ function () public payable { require(currentStage == Stages.icoStart); require(msg.value > 0); require(remainingTokens > 0); uint256 weiAmount = msg.value; // Calculate tokens to sell uint256 tokens = weiAmount.mul(basePrice).div(1 ether); uint256 returnWei = 0; if(tokensSold.add(tokens) > cap){ uint256 newTokens = cap.sub(tokensSold); uint256 newWei = newTokens.div(basePrice).mul(1 ether); returnWei = weiAmount.sub(newWei); weiAmount = newWei; tokens = newTokens; } tokensSold = tokensSold.add(tokens); // Increment raised amount remainingTokens = cap.sub(tokensSold); if(returnWei > 0){ msg.sender.transfer(returnWei); emit Transfer(address(this), msg.sender, returnWei); } balances[msg.sender] = balances[msg.sender].add(tokens); emit Transfer(address(this), msg.sender, tokens); totalSupply_ = totalSupply_.add(tokens); owner.transfer(weiAmount);// Send money to owner } /** * @dev startIco starts the public ICO **/ function startIco() public onlyOwner { require(currentStage != Stages.icoEnd); currentStage = Stages.icoStart; } /** * @dev endIco closes down the ICO **/ function endIco() internal { currentStage = Stages.icoEnd; // Transfer any remaining tokens if(remainingTokens > 0) balances[owner] = balances[owner].add(remainingTokens); // transfer any remaining ETH balance in the contract to the owner owner.transfer(address(this).balance); } /** * @dev finalizeIco closes down the ICO and sets needed varriables **/ function finalizeIco() public onlyOwner { require(currentStage != Stages.icoEnd); endIco(); } }
/** * @title CrowdsaleToken * @dev Contract to preform crowd sale with token **/
NatSpecMultiLine
function () public payable { require(currentStage == Stages.icoStart); require(msg.value > 0); require(remainingTokens > 0); uint256 weiAmount = msg.value; // Calculate tokens to sell uint256 tokens = weiAmount.mul(basePrice).div(1 ether); uint256 returnWei = 0; if(tokensSold.add(tokens) > cap){ uint256 newTokens = cap.sub(tokensSold); uint256 newWei = newTokens.div(basePrice).mul(1 ether); returnWei = weiAmount.sub(newWei); weiAmount = newWei; tokens = newTokens; } tokensSold = tokensSold.add(tokens); // Increment raised amount remainingTokens = cap.sub(tokensSold); if(returnWei > 0){ msg.sender.transfer(returnWei); emit Transfer(address(this), msg.sender, returnWei); } balances[msg.sender] = balances[msg.sender].add(tokens); emit Transfer(address(this), msg.sender, tokens); totalSupply_ = totalSupply_.add(tokens); owner.transfer(weiAmount);// Send money to owner }
/** * @dev fallback function to send ether to for Crowd sale **/
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://dd83d5462f253f5f6aca7764840442bc7ef046242505fa42b84d4e4bf6258aae
{ "func_code_index": [ 678, 1851 ] }
59,577
UniBlueFinance
UniBlueFinance.sol
0xfa72c4d6dbaff668b7905cd4076efd8062c81066
Solidity
CrowdsaleToken
contract CrowdsaleToken is StandardToken, Configurable, Ownable { /** * @dev enum of current crowd sale state **/ enum Stages { none, icoStart, icoEnd } Stages currentStage; /** * @dev constructor of CrowdsaleToken **/ constructor() public { currentStage = Stages.none; balances[owner] = balances[owner].add(tokenReserve); totalSupply_ = totalSupply_.add(tokenReserve); remainingTokens = cap; emit Transfer(address(this), owner, tokenReserve); } /** * @dev fallback function to send ether to for Crowd sale **/ function () public payable { require(currentStage == Stages.icoStart); require(msg.value > 0); require(remainingTokens > 0); uint256 weiAmount = msg.value; // Calculate tokens to sell uint256 tokens = weiAmount.mul(basePrice).div(1 ether); uint256 returnWei = 0; if(tokensSold.add(tokens) > cap){ uint256 newTokens = cap.sub(tokensSold); uint256 newWei = newTokens.div(basePrice).mul(1 ether); returnWei = weiAmount.sub(newWei); weiAmount = newWei; tokens = newTokens; } tokensSold = tokensSold.add(tokens); // Increment raised amount remainingTokens = cap.sub(tokensSold); if(returnWei > 0){ msg.sender.transfer(returnWei); emit Transfer(address(this), msg.sender, returnWei); } balances[msg.sender] = balances[msg.sender].add(tokens); emit Transfer(address(this), msg.sender, tokens); totalSupply_ = totalSupply_.add(tokens); owner.transfer(weiAmount);// Send money to owner } /** * @dev startIco starts the public ICO **/ function startIco() public onlyOwner { require(currentStage != Stages.icoEnd); currentStage = Stages.icoStart; } /** * @dev endIco closes down the ICO **/ function endIco() internal { currentStage = Stages.icoEnd; // Transfer any remaining tokens if(remainingTokens > 0) balances[owner] = balances[owner].add(remainingTokens); // transfer any remaining ETH balance in the contract to the owner owner.transfer(address(this).balance); } /** * @dev finalizeIco closes down the ICO and sets needed varriables **/ function finalizeIco() public onlyOwner { require(currentStage != Stages.icoEnd); endIco(); } }
/** * @title CrowdsaleToken * @dev Contract to preform crowd sale with token **/
NatSpecMultiLine
startIco
function startIco() public onlyOwner { require(currentStage != Stages.icoEnd); currentStage = Stages.icoStart; }
/** * @dev startIco starts the public ICO **/
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://dd83d5462f253f5f6aca7764840442bc7ef046242505fa42b84d4e4bf6258aae
{ "func_code_index": [ 1911, 2051 ] }
59,578
UniBlueFinance
UniBlueFinance.sol
0xfa72c4d6dbaff668b7905cd4076efd8062c81066
Solidity
CrowdsaleToken
contract CrowdsaleToken is StandardToken, Configurable, Ownable { /** * @dev enum of current crowd sale state **/ enum Stages { none, icoStart, icoEnd } Stages currentStage; /** * @dev constructor of CrowdsaleToken **/ constructor() public { currentStage = Stages.none; balances[owner] = balances[owner].add(tokenReserve); totalSupply_ = totalSupply_.add(tokenReserve); remainingTokens = cap; emit Transfer(address(this), owner, tokenReserve); } /** * @dev fallback function to send ether to for Crowd sale **/ function () public payable { require(currentStage == Stages.icoStart); require(msg.value > 0); require(remainingTokens > 0); uint256 weiAmount = msg.value; // Calculate tokens to sell uint256 tokens = weiAmount.mul(basePrice).div(1 ether); uint256 returnWei = 0; if(tokensSold.add(tokens) > cap){ uint256 newTokens = cap.sub(tokensSold); uint256 newWei = newTokens.div(basePrice).mul(1 ether); returnWei = weiAmount.sub(newWei); weiAmount = newWei; tokens = newTokens; } tokensSold = tokensSold.add(tokens); // Increment raised amount remainingTokens = cap.sub(tokensSold); if(returnWei > 0){ msg.sender.transfer(returnWei); emit Transfer(address(this), msg.sender, returnWei); } balances[msg.sender] = balances[msg.sender].add(tokens); emit Transfer(address(this), msg.sender, tokens); totalSupply_ = totalSupply_.add(tokens); owner.transfer(weiAmount);// Send money to owner } /** * @dev startIco starts the public ICO **/ function startIco() public onlyOwner { require(currentStage != Stages.icoEnd); currentStage = Stages.icoStart; } /** * @dev endIco closes down the ICO **/ function endIco() internal { currentStage = Stages.icoEnd; // Transfer any remaining tokens if(remainingTokens > 0) balances[owner] = balances[owner].add(remainingTokens); // transfer any remaining ETH balance in the contract to the owner owner.transfer(address(this).balance); } /** * @dev finalizeIco closes down the ICO and sets needed varriables **/ function finalizeIco() public onlyOwner { require(currentStage != Stages.icoEnd); endIco(); } }
/** * @title CrowdsaleToken * @dev Contract to preform crowd sale with token **/
NatSpecMultiLine
endIco
function endIco() internal { currentStage = Stages.icoEnd; // Transfer any remaining tokens if(remainingTokens > 0) balances[owner] = balances[owner].add(remainingTokens); // transfer any remaining ETH balance in the contract to the owner owner.transfer(address(this).balance); }
/** * @dev endIco closes down the ICO **/
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://dd83d5462f253f5f6aca7764840442bc7ef046242505fa42b84d4e4bf6258aae
{ "func_code_index": [ 2108, 2456 ] }
59,579
UniBlueFinance
UniBlueFinance.sol
0xfa72c4d6dbaff668b7905cd4076efd8062c81066
Solidity
CrowdsaleToken
contract CrowdsaleToken is StandardToken, Configurable, Ownable { /** * @dev enum of current crowd sale state **/ enum Stages { none, icoStart, icoEnd } Stages currentStage; /** * @dev constructor of CrowdsaleToken **/ constructor() public { currentStage = Stages.none; balances[owner] = balances[owner].add(tokenReserve); totalSupply_ = totalSupply_.add(tokenReserve); remainingTokens = cap; emit Transfer(address(this), owner, tokenReserve); } /** * @dev fallback function to send ether to for Crowd sale **/ function () public payable { require(currentStage == Stages.icoStart); require(msg.value > 0); require(remainingTokens > 0); uint256 weiAmount = msg.value; // Calculate tokens to sell uint256 tokens = weiAmount.mul(basePrice).div(1 ether); uint256 returnWei = 0; if(tokensSold.add(tokens) > cap){ uint256 newTokens = cap.sub(tokensSold); uint256 newWei = newTokens.div(basePrice).mul(1 ether); returnWei = weiAmount.sub(newWei); weiAmount = newWei; tokens = newTokens; } tokensSold = tokensSold.add(tokens); // Increment raised amount remainingTokens = cap.sub(tokensSold); if(returnWei > 0){ msg.sender.transfer(returnWei); emit Transfer(address(this), msg.sender, returnWei); } balances[msg.sender] = balances[msg.sender].add(tokens); emit Transfer(address(this), msg.sender, tokens); totalSupply_ = totalSupply_.add(tokens); owner.transfer(weiAmount);// Send money to owner } /** * @dev startIco starts the public ICO **/ function startIco() public onlyOwner { require(currentStage != Stages.icoEnd); currentStage = Stages.icoStart; } /** * @dev endIco closes down the ICO **/ function endIco() internal { currentStage = Stages.icoEnd; // Transfer any remaining tokens if(remainingTokens > 0) balances[owner] = balances[owner].add(remainingTokens); // transfer any remaining ETH balance in the contract to the owner owner.transfer(address(this).balance); } /** * @dev finalizeIco closes down the ICO and sets needed varriables **/ function finalizeIco() public onlyOwner { require(currentStage != Stages.icoEnd); endIco(); } }
/** * @title CrowdsaleToken * @dev Contract to preform crowd sale with token **/
NatSpecMultiLine
finalizeIco
function finalizeIco() public onlyOwner { require(currentStage != Stages.icoEnd); endIco(); }
/** * @dev finalizeIco closes down the ICO and sets needed varriables **/
NatSpecMultiLine
v0.4.23+commit.124ca40d
MIT
bzzr://dd83d5462f253f5f6aca7764840442bc7ef046242505fa42b84d4e4bf6258aae
{ "func_code_index": [ 2544, 2665 ] }
59,580
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
Ownable
function Ownable() { owner = msg.sender; }
/** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */
NatSpecMultiLine
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 253, 306 ] }
59,581
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 621, 796 ] }
59,582
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
Haltable
contract Haltable is Ownable { bool public halted; modifier stopInEmergency { require(!halted); _; } modifier stopNonOwnersInEmergency { require(!halted && msg.sender == owner); _; } modifier onlyInEmergency { require(halted); _; } // called by the owner on emergency, triggers stopped state function halt() external onlyOwner { halted = true; } // called by the owner on end of emergency, returns to normal state function unhalt() external onlyOwner onlyInEmergency { halted = false; } }
/* * Haltable * emergency stop mechanism. Differs from Pausable by causing a throw when in halt mode. * Originally envisioned in FirstBlood ICO contract. */
Comment
halt
function halt() external onlyOwner { halted = true; }
// called by the owner on emergency, triggers stopped state
LineComment
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 347, 411 ] }
59,583
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
Haltable
contract Haltable is Ownable { bool public halted; modifier stopInEmergency { require(!halted); _; } modifier stopNonOwnersInEmergency { require(!halted && msg.sender == owner); _; } modifier onlyInEmergency { require(halted); _; } // called by the owner on emergency, triggers stopped state function halt() external onlyOwner { halted = true; } // called by the owner on end of emergency, returns to normal state function unhalt() external onlyOwner onlyInEmergency { halted = false; } }
/* * Haltable * emergency stop mechanism. Differs from Pausable by causing a throw when in halt mode. * Originally envisioned in FirstBlood ICO contract. */
Comment
unhalt
function unhalt() external onlyOwner onlyInEmergency { halted = false; }
// called by the owner on end of emergency, returns to normal state
LineComment
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 483, 566 ] }
59,584
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
transfer
function transfer(address _to, uint256 _value) returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; }
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */
NatSpecMultiLine
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 264, 600 ] }
59,585
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
balanceOf
function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; }
/** * @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. */
NatSpecMultiLine
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 805, 914 ] }
59,586
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { require(_to != address(0)); var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title 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 */
NatSpecMultiLine
transferFrom
function transferFrom(address _from, address _to, uint256 _value) returns (bool) { require(_to != address(0)); var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; }
/** * @dev 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 */
NatSpecMultiLine
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 386, 918 ] }
59,587
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { require(_to != address(0)); var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title 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 */
NatSpecMultiLine
approve
function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; }
/** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */
NatSpecMultiLine
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 1152, 1696 ] }
59,588
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { require(_to != address(0)); var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title 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 */
NatSpecMultiLine
allowance
function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; }
/** * @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. */
NatSpecMultiLine
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 2018, 2156 ] }
59,589
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { require(_to != address(0)); var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title 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 */
NatSpecMultiLine
increaseApproval
function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
/** * 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 */
NatSpecMultiLine
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 2404, 2676 ] }
59,590
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
HarborToken
contract HarborToken is StandardToken, Ownable { //define HarborToken string public constant name = "HarborToken"; string public constant symbol = "HBR"; uint8 public constant decimals = 18; /** List of agents that are allowed to create new tokens */ mapping (address => bool) public mintAgents; event Mint(address indexed to, uint256 amount); event MintOpened(); event MintFinished(); event MintingAgentChanged(address addr, bool state ); event BurnToken(address addr,uint256 amount); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier onlyMintAgent() { // Only crowdsale contracts are allowed to mint new tokens require(mintAgents[msg.sender]); _; } /** * Owner can allow a crowdsale contract to mint new tokens. */ function setMintAgent(address addr, bool state) onlyOwner canMint public { mintAgents[addr] = state; MintingAgentChanged(addr, state); } /** * @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) onlyMintAgent canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to burn down tokens * @param _addr The address that will burn the tokens. * @param _amount The amount of tokens to burn. * @return A boolean that indicates if the burn up was successful. */ function burn(address _addr,uint256 _amount) onlyMintAgent canMint returns (bool) { require(_amount > 0); totalSupply = totalSupply.sub(_amount); balances[_addr] = balances[_addr].sub(_amount); BurnToken(_addr,_amount); return true; } /** * @dev Function to resume minting new tokens. * @return True if the operation was successful. */ function openMinting() onlyOwner returns (bool) { mintingFinished = false; MintOpened(); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } }
/** * @title Harbor 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 */
NatSpecMultiLine
setMintAgent
function setMintAgent(address addr, bool state) onlyOwner canMint public { mintAgents[addr] = state; MintingAgentChanged(addr, state); }
/** * Owner can allow a crowdsale contract to mint new tokens. */
NatSpecMultiLine
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 853, 1005 ] }
59,591
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
HarborToken
contract HarborToken is StandardToken, Ownable { //define HarborToken string public constant name = "HarborToken"; string public constant symbol = "HBR"; uint8 public constant decimals = 18; /** List of agents that are allowed to create new tokens */ mapping (address => bool) public mintAgents; event Mint(address indexed to, uint256 amount); event MintOpened(); event MintFinished(); event MintingAgentChanged(address addr, bool state ); event BurnToken(address addr,uint256 amount); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier onlyMintAgent() { // Only crowdsale contracts are allowed to mint new tokens require(mintAgents[msg.sender]); _; } /** * Owner can allow a crowdsale contract to mint new tokens. */ function setMintAgent(address addr, bool state) onlyOwner canMint public { mintAgents[addr] = state; MintingAgentChanged(addr, state); } /** * @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) onlyMintAgent canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to burn down tokens * @param _addr The address that will burn the tokens. * @param _amount The amount of tokens to burn. * @return A boolean that indicates if the burn up was successful. */ function burn(address _addr,uint256 _amount) onlyMintAgent canMint returns (bool) { require(_amount > 0); totalSupply = totalSupply.sub(_amount); balances[_addr] = balances[_addr].sub(_amount); BurnToken(_addr,_amount); return true; } /** * @dev Function to resume minting new tokens. * @return True if the operation was successful. */ function openMinting() onlyOwner returns (bool) { mintingFinished = false; MintOpened(); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } }
/** * @title Harbor 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 */
NatSpecMultiLine
mint
function mint(address _to, uint256 _amount) onlyMintAgent canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; }
/** * @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. */
NatSpecMultiLine
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 1244, 1505 ] }
59,592
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
HarborToken
contract HarborToken is StandardToken, Ownable { //define HarborToken string public constant name = "HarborToken"; string public constant symbol = "HBR"; uint8 public constant decimals = 18; /** List of agents that are allowed to create new tokens */ mapping (address => bool) public mintAgents; event Mint(address indexed to, uint256 amount); event MintOpened(); event MintFinished(); event MintingAgentChanged(address addr, bool state ); event BurnToken(address addr,uint256 amount); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier onlyMintAgent() { // Only crowdsale contracts are allowed to mint new tokens require(mintAgents[msg.sender]); _; } /** * Owner can allow a crowdsale contract to mint new tokens. */ function setMintAgent(address addr, bool state) onlyOwner canMint public { mintAgents[addr] = state; MintingAgentChanged(addr, state); } /** * @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) onlyMintAgent canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to burn down tokens * @param _addr The address that will burn the tokens. * @param _amount The amount of tokens to burn. * @return A boolean that indicates if the burn up was successful. */ function burn(address _addr,uint256 _amount) onlyMintAgent canMint returns (bool) { require(_amount > 0); totalSupply = totalSupply.sub(_amount); balances[_addr] = balances[_addr].sub(_amount); BurnToken(_addr,_amount); return true; } /** * @dev Function to resume minting new tokens. * @return True if the operation was successful. */ function openMinting() onlyOwner returns (bool) { mintingFinished = false; MintOpened(); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } }
/** * @title Harbor 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 */
NatSpecMultiLine
burn
function burn(address _addr,uint256 _amount) onlyMintAgent canMint returns (bool) { require(_amount > 0); totalSupply = totalSupply.sub(_amount); balances[_addr] = balances[_addr].sub(_amount); BurnToken(_addr,_amount); return true; }
/** * @dev Function to burn down tokens * @param _addr The address that will burn the tokens. * @param _amount The amount of tokens to burn. * @return A boolean that indicates if the burn up was successful. */
NatSpecMultiLine
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 1740, 2006 ] }
59,593
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
HarborToken
contract HarborToken is StandardToken, Ownable { //define HarborToken string public constant name = "HarborToken"; string public constant symbol = "HBR"; uint8 public constant decimals = 18; /** List of agents that are allowed to create new tokens */ mapping (address => bool) public mintAgents; event Mint(address indexed to, uint256 amount); event MintOpened(); event MintFinished(); event MintingAgentChanged(address addr, bool state ); event BurnToken(address addr,uint256 amount); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier onlyMintAgent() { // Only crowdsale contracts are allowed to mint new tokens require(mintAgents[msg.sender]); _; } /** * Owner can allow a crowdsale contract to mint new tokens. */ function setMintAgent(address addr, bool state) onlyOwner canMint public { mintAgents[addr] = state; MintingAgentChanged(addr, state); } /** * @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) onlyMintAgent canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to burn down tokens * @param _addr The address that will burn the tokens. * @param _amount The amount of tokens to burn. * @return A boolean that indicates if the burn up was successful. */ function burn(address _addr,uint256 _amount) onlyMintAgent canMint returns (bool) { require(_amount > 0); totalSupply = totalSupply.sub(_amount); balances[_addr] = balances[_addr].sub(_amount); BurnToken(_addr,_amount); return true; } /** * @dev Function to resume minting new tokens. * @return True if the operation was successful. */ function openMinting() onlyOwner returns (bool) { mintingFinished = false; MintOpened(); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } }
/** * @title Harbor 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 */
NatSpecMultiLine
openMinting
function openMinting() onlyOwner returns (bool) { mintingFinished = false; MintOpened(); return true; }
/** * @dev Function to resume minting new tokens. * @return True if the operation was successful. */
NatSpecMultiLine
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 2123, 2248 ] }
59,594
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
HarborToken
contract HarborToken is StandardToken, Ownable { //define HarborToken string public constant name = "HarborToken"; string public constant symbol = "HBR"; uint8 public constant decimals = 18; /** List of agents that are allowed to create new tokens */ mapping (address => bool) public mintAgents; event Mint(address indexed to, uint256 amount); event MintOpened(); event MintFinished(); event MintingAgentChanged(address addr, bool state ); event BurnToken(address addr,uint256 amount); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier onlyMintAgent() { // Only crowdsale contracts are allowed to mint new tokens require(mintAgents[msg.sender]); _; } /** * Owner can allow a crowdsale contract to mint new tokens. */ function setMintAgent(address addr, bool state) onlyOwner canMint public { mintAgents[addr] = state; MintingAgentChanged(addr, state); } /** * @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) onlyMintAgent canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } /** * @dev Function to burn down tokens * @param _addr The address that will burn the tokens. * @param _amount The amount of tokens to burn. * @return A boolean that indicates if the burn up was successful. */ function burn(address _addr,uint256 _amount) onlyMintAgent canMint returns (bool) { require(_amount > 0); totalSupply = totalSupply.sub(_amount); balances[_addr] = balances[_addr].sub(_amount); BurnToken(_addr,_amount); return true; } /** * @dev Function to resume minting new tokens. * @return True if the operation was successful. */ function openMinting() onlyOwner returns (bool) { mintingFinished = false; MintOpened(); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } }
/** * @title Harbor 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 */
NatSpecMultiLine
finishMinting
function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; }
/** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */
NatSpecMultiLine
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 2362, 2489 ] }
59,595
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
HarborPresale
contract HarborPresale is Haltable { using SafeMath for uint256; // The token being sold HarborToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are excutionFunds address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; //max amount of funds raised uint256 public cap; //is crowdsale end bool public isFinalized = false; // minimum amount of funds to be raised in weis uint256 public minimumFundingGoal; // minimum amount of funds for once uint256 public minSend; // refund vault used to hold funds while crowdsale is running RefundVault public vault; //How many tokens were Minted uint public tokensMinted; //presale buyers mapping (address => uint256) public tokenDeposited; //event for crowdsale end event Finalized(); //event for presale mint event TokenMinted(uint count); // We distributed tokens to an investor event Distributed(address investor, uint tokenAmount); //presale period is Changed event PeriodChanged(uint256 starttm,uint256 endtm); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param investor who participate presale * @param value weis paid for purchase */ event TokenPurchase(address indexed purchaser, address indexed investor, uint256 value); function HarborPresale(address _token, uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _cap, uint256 _minimumFundingGoal, uint256 _minSend) { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != 0x0); require(_cap > 0); require(_minimumFundingGoal > 0); token = HarborToken(_token); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; cap = _cap; vault = new RefundVault(_wallet); minimumFundingGoal = _minimumFundingGoal; minSend = _minSend; } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address investor) payable stopInEmergency { require(investor != 0x0); require(validPurchase()); require(minSend <= msg.value); uint256 weiAmount = msg.value; // update state weiRaised = weiRaised.add(weiAmount); //save for distribution HBR tokenDeposited[investor] = tokenDeposited[investor].add(weiAmount); //valut save for refund vault.deposit.value(msg.value)(msg.sender); TokenPurchase(msg.sender, investor, weiAmount); } /** * Load funds to the crowdsale for all investors. */ function mintForEverybody() onlyOwner public { uint256 allTokenAmount = weiRaised.mul(rate); //for project amount (investor token *2/3) uint256 projectAmount = allTokenAmount.mul(2); projectAmount = projectAmount.div(3); //mint for investor; token.mint(address(this),allTokenAmount); //mint for project share token.mint(wallet,projectAmount); // Record how many tokens we got tokensMinted = allTokenAmount.add(projectAmount); TokenMinted(tokensMinted); } //get claim of token byself function claimToken() payable stopInEmergency{ claimTokenAddress(msg.sender); } //get claim of token by address function claimTokenAddress(address investor) payable stopInEmergency returns(uint256){ require(isFinalized); require(tokenDeposited[investor] != 0); uint256 depositedValue = tokenDeposited[investor]; tokenDeposited[investor] = 0; uint256 tokenAmount = depositedValue * rate; //send token to investor token.transfer(investor,tokenAmount); Distributed(investor, tokenAmount); return tokenAmount; } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; bool withinCap = weiRaised <= cap; return withinPeriod && nonZeroPurchase && withinCap; } // @return true if HarborPresale event has ended function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= cap; return (now > endTime) || capReached ; } /** * called after Presale ends */ function finalize() onlyOwner stopInEmergency{ require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * finalization refund or excute funds. */ function finalization() internal { if (minFundingGoalReached()) { vault.close(); } else { vault.enableRefunds(); } } // if presale is unsuccessful, investors can claim refunds here function claimRefund() stopInEmergency payable { require(isFinalized); require(!minFundingGoalReached()); vault.refund(msg.sender); } function minFundingGoalReached() public constant returns (bool) { return weiRaised >= minimumFundingGoal; } //change presale preiod function setPeriod(uint256 _startTime,uint256 _endTime) onlyOwner { require(now <= _endTime); startTime = _startTime; endTime = _endTime; PeriodChanged(startTime,endTime); } //withdrow for manual distribution function withdrawFund() onlyOwner payable{ require(isFinalized); require(minFundingGoalReached()); uint256 tokenAmount = token.balanceOf(address(this)); token.transfer(wallet, tokenAmount); } }
/** * @title HarborPresale */
NatSpecMultiLine
function () payable { buyTokens(msg.sender); }
// fallback function can be used to buy tokens
LineComment
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 2234, 2291 ] }
59,596
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
HarborPresale
contract HarborPresale is Haltable { using SafeMath for uint256; // The token being sold HarborToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are excutionFunds address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; //max amount of funds raised uint256 public cap; //is crowdsale end bool public isFinalized = false; // minimum amount of funds to be raised in weis uint256 public minimumFundingGoal; // minimum amount of funds for once uint256 public minSend; // refund vault used to hold funds while crowdsale is running RefundVault public vault; //How many tokens were Minted uint public tokensMinted; //presale buyers mapping (address => uint256) public tokenDeposited; //event for crowdsale end event Finalized(); //event for presale mint event TokenMinted(uint count); // We distributed tokens to an investor event Distributed(address investor, uint tokenAmount); //presale period is Changed event PeriodChanged(uint256 starttm,uint256 endtm); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param investor who participate presale * @param value weis paid for purchase */ event TokenPurchase(address indexed purchaser, address indexed investor, uint256 value); function HarborPresale(address _token, uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _cap, uint256 _minimumFundingGoal, uint256 _minSend) { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != 0x0); require(_cap > 0); require(_minimumFundingGoal > 0); token = HarborToken(_token); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; cap = _cap; vault = new RefundVault(_wallet); minimumFundingGoal = _minimumFundingGoal; minSend = _minSend; } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address investor) payable stopInEmergency { require(investor != 0x0); require(validPurchase()); require(minSend <= msg.value); uint256 weiAmount = msg.value; // update state weiRaised = weiRaised.add(weiAmount); //save for distribution HBR tokenDeposited[investor] = tokenDeposited[investor].add(weiAmount); //valut save for refund vault.deposit.value(msg.value)(msg.sender); TokenPurchase(msg.sender, investor, weiAmount); } /** * Load funds to the crowdsale for all investors. */ function mintForEverybody() onlyOwner public { uint256 allTokenAmount = weiRaised.mul(rate); //for project amount (investor token *2/3) uint256 projectAmount = allTokenAmount.mul(2); projectAmount = projectAmount.div(3); //mint for investor; token.mint(address(this),allTokenAmount); //mint for project share token.mint(wallet,projectAmount); // Record how many tokens we got tokensMinted = allTokenAmount.add(projectAmount); TokenMinted(tokensMinted); } //get claim of token byself function claimToken() payable stopInEmergency{ claimTokenAddress(msg.sender); } //get claim of token by address function claimTokenAddress(address investor) payable stopInEmergency returns(uint256){ require(isFinalized); require(tokenDeposited[investor] != 0); uint256 depositedValue = tokenDeposited[investor]; tokenDeposited[investor] = 0; uint256 tokenAmount = depositedValue * rate; //send token to investor token.transfer(investor,tokenAmount); Distributed(investor, tokenAmount); return tokenAmount; } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; bool withinCap = weiRaised <= cap; return withinPeriod && nonZeroPurchase && withinCap; } // @return true if HarborPresale event has ended function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= cap; return (now > endTime) || capReached ; } /** * called after Presale ends */ function finalize() onlyOwner stopInEmergency{ require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * finalization refund or excute funds. */ function finalization() internal { if (minFundingGoalReached()) { vault.close(); } else { vault.enableRefunds(); } } // if presale is unsuccessful, investors can claim refunds here function claimRefund() stopInEmergency payable { require(isFinalized); require(!minFundingGoalReached()); vault.refund(msg.sender); } function minFundingGoalReached() public constant returns (bool) { return weiRaised >= minimumFundingGoal; } //change presale preiod function setPeriod(uint256 _startTime,uint256 _endTime) onlyOwner { require(now <= _endTime); startTime = _startTime; endTime = _endTime; PeriodChanged(startTime,endTime); } //withdrow for manual distribution function withdrawFund() onlyOwner payable{ require(isFinalized); require(minFundingGoalReached()); uint256 tokenAmount = token.balanceOf(address(this)); token.transfer(wallet, tokenAmount); } }
/** * @title HarborPresale */
NatSpecMultiLine
buyTokens
function buyTokens(address investor) payable stopInEmergency { require(investor != 0x0); require(validPurchase()); require(minSend <= msg.value); uint256 weiAmount = msg.value; // update state weiRaised = weiRaised.add(weiAmount); //save for distribution HBR tokenDeposited[investor] = tokenDeposited[investor].add(weiAmount); //valut save for refund vault.deposit.value(msg.value)(msg.sender); TokenPurchase(msg.sender, investor, weiAmount); }
// low level token purchase function
LineComment
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 2332, 2843 ] }
59,597
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
HarborPresale
contract HarborPresale is Haltable { using SafeMath for uint256; // The token being sold HarborToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are excutionFunds address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; //max amount of funds raised uint256 public cap; //is crowdsale end bool public isFinalized = false; // minimum amount of funds to be raised in weis uint256 public minimumFundingGoal; // minimum amount of funds for once uint256 public minSend; // refund vault used to hold funds while crowdsale is running RefundVault public vault; //How many tokens were Minted uint public tokensMinted; //presale buyers mapping (address => uint256) public tokenDeposited; //event for crowdsale end event Finalized(); //event for presale mint event TokenMinted(uint count); // We distributed tokens to an investor event Distributed(address investor, uint tokenAmount); //presale period is Changed event PeriodChanged(uint256 starttm,uint256 endtm); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param investor who participate presale * @param value weis paid for purchase */ event TokenPurchase(address indexed purchaser, address indexed investor, uint256 value); function HarborPresale(address _token, uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _cap, uint256 _minimumFundingGoal, uint256 _minSend) { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != 0x0); require(_cap > 0); require(_minimumFundingGoal > 0); token = HarborToken(_token); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; cap = _cap; vault = new RefundVault(_wallet); minimumFundingGoal = _minimumFundingGoal; minSend = _minSend; } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address investor) payable stopInEmergency { require(investor != 0x0); require(validPurchase()); require(minSend <= msg.value); uint256 weiAmount = msg.value; // update state weiRaised = weiRaised.add(weiAmount); //save for distribution HBR tokenDeposited[investor] = tokenDeposited[investor].add(weiAmount); //valut save for refund vault.deposit.value(msg.value)(msg.sender); TokenPurchase(msg.sender, investor, weiAmount); } /** * Load funds to the crowdsale for all investors. */ function mintForEverybody() onlyOwner public { uint256 allTokenAmount = weiRaised.mul(rate); //for project amount (investor token *2/3) uint256 projectAmount = allTokenAmount.mul(2); projectAmount = projectAmount.div(3); //mint for investor; token.mint(address(this),allTokenAmount); //mint for project share token.mint(wallet,projectAmount); // Record how many tokens we got tokensMinted = allTokenAmount.add(projectAmount); TokenMinted(tokensMinted); } //get claim of token byself function claimToken() payable stopInEmergency{ claimTokenAddress(msg.sender); } //get claim of token by address function claimTokenAddress(address investor) payable stopInEmergency returns(uint256){ require(isFinalized); require(tokenDeposited[investor] != 0); uint256 depositedValue = tokenDeposited[investor]; tokenDeposited[investor] = 0; uint256 tokenAmount = depositedValue * rate; //send token to investor token.transfer(investor,tokenAmount); Distributed(investor, tokenAmount); return tokenAmount; } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; bool withinCap = weiRaised <= cap; return withinPeriod && nonZeroPurchase && withinCap; } // @return true if HarborPresale event has ended function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= cap; return (now > endTime) || capReached ; } /** * called after Presale ends */ function finalize() onlyOwner stopInEmergency{ require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * finalization refund or excute funds. */ function finalization() internal { if (minFundingGoalReached()) { vault.close(); } else { vault.enableRefunds(); } } // if presale is unsuccessful, investors can claim refunds here function claimRefund() stopInEmergency payable { require(isFinalized); require(!minFundingGoalReached()); vault.refund(msg.sender); } function minFundingGoalReached() public constant returns (bool) { return weiRaised >= minimumFundingGoal; } //change presale preiod function setPeriod(uint256 _startTime,uint256 _endTime) onlyOwner { require(now <= _endTime); startTime = _startTime; endTime = _endTime; PeriodChanged(startTime,endTime); } //withdrow for manual distribution function withdrawFund() onlyOwner payable{ require(isFinalized); require(minFundingGoalReached()); uint256 tokenAmount = token.balanceOf(address(this)); token.transfer(wallet, tokenAmount); } }
/** * @title HarborPresale */
NatSpecMultiLine
mintForEverybody
function mintForEverybody() onlyOwner public { uint256 allTokenAmount = weiRaised.mul(rate); //for project amount (investor token *2/3) uint256 projectAmount = allTokenAmount.mul(2); projectAmount = projectAmount.div(3); //mint for investor; token.mint(address(this),allTokenAmount); //mint for project share token.mint(wallet,projectAmount); // Record how many tokens we got tokensMinted = allTokenAmount.add(projectAmount); TokenMinted(tokensMinted); }
/** * Load funds to the crowdsale for all investors. */
NatSpecMultiLine
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 2911, 3426 ] }
59,598
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
HarborPresale
contract HarborPresale is Haltable { using SafeMath for uint256; // The token being sold HarborToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are excutionFunds address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; //max amount of funds raised uint256 public cap; //is crowdsale end bool public isFinalized = false; // minimum amount of funds to be raised in weis uint256 public minimumFundingGoal; // minimum amount of funds for once uint256 public minSend; // refund vault used to hold funds while crowdsale is running RefundVault public vault; //How many tokens were Minted uint public tokensMinted; //presale buyers mapping (address => uint256) public tokenDeposited; //event for crowdsale end event Finalized(); //event for presale mint event TokenMinted(uint count); // We distributed tokens to an investor event Distributed(address investor, uint tokenAmount); //presale period is Changed event PeriodChanged(uint256 starttm,uint256 endtm); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param investor who participate presale * @param value weis paid for purchase */ event TokenPurchase(address indexed purchaser, address indexed investor, uint256 value); function HarborPresale(address _token, uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _cap, uint256 _minimumFundingGoal, uint256 _minSend) { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != 0x0); require(_cap > 0); require(_minimumFundingGoal > 0); token = HarborToken(_token); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; cap = _cap; vault = new RefundVault(_wallet); minimumFundingGoal = _minimumFundingGoal; minSend = _minSend; } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address investor) payable stopInEmergency { require(investor != 0x0); require(validPurchase()); require(minSend <= msg.value); uint256 weiAmount = msg.value; // update state weiRaised = weiRaised.add(weiAmount); //save for distribution HBR tokenDeposited[investor] = tokenDeposited[investor].add(weiAmount); //valut save for refund vault.deposit.value(msg.value)(msg.sender); TokenPurchase(msg.sender, investor, weiAmount); } /** * Load funds to the crowdsale for all investors. */ function mintForEverybody() onlyOwner public { uint256 allTokenAmount = weiRaised.mul(rate); //for project amount (investor token *2/3) uint256 projectAmount = allTokenAmount.mul(2); projectAmount = projectAmount.div(3); //mint for investor; token.mint(address(this),allTokenAmount); //mint for project share token.mint(wallet,projectAmount); // Record how many tokens we got tokensMinted = allTokenAmount.add(projectAmount); TokenMinted(tokensMinted); } //get claim of token byself function claimToken() payable stopInEmergency{ claimTokenAddress(msg.sender); } //get claim of token by address function claimTokenAddress(address investor) payable stopInEmergency returns(uint256){ require(isFinalized); require(tokenDeposited[investor] != 0); uint256 depositedValue = tokenDeposited[investor]; tokenDeposited[investor] = 0; uint256 tokenAmount = depositedValue * rate; //send token to investor token.transfer(investor,tokenAmount); Distributed(investor, tokenAmount); return tokenAmount; } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; bool withinCap = weiRaised <= cap; return withinPeriod && nonZeroPurchase && withinCap; } // @return true if HarborPresale event has ended function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= cap; return (now > endTime) || capReached ; } /** * called after Presale ends */ function finalize() onlyOwner stopInEmergency{ require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * finalization refund or excute funds. */ function finalization() internal { if (minFundingGoalReached()) { vault.close(); } else { vault.enableRefunds(); } } // if presale is unsuccessful, investors can claim refunds here function claimRefund() stopInEmergency payable { require(isFinalized); require(!minFundingGoalReached()); vault.refund(msg.sender); } function minFundingGoalReached() public constant returns (bool) { return weiRaised >= minimumFundingGoal; } //change presale preiod function setPeriod(uint256 _startTime,uint256 _endTime) onlyOwner { require(now <= _endTime); startTime = _startTime; endTime = _endTime; PeriodChanged(startTime,endTime); } //withdrow for manual distribution function withdrawFund() onlyOwner payable{ require(isFinalized); require(minFundingGoalReached()); uint256 tokenAmount = token.balanceOf(address(this)); token.transfer(wallet, tokenAmount); } }
/** * @title HarborPresale */
NatSpecMultiLine
claimToken
function claimToken() payable stopInEmergency{ claimTokenAddress(msg.sender); }
//get claim of token byself
LineComment
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 3458, 3548 ] }
59,599
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
HarborPresale
contract HarborPresale is Haltable { using SafeMath for uint256; // The token being sold HarborToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are excutionFunds address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; //max amount of funds raised uint256 public cap; //is crowdsale end bool public isFinalized = false; // minimum amount of funds to be raised in weis uint256 public minimumFundingGoal; // minimum amount of funds for once uint256 public minSend; // refund vault used to hold funds while crowdsale is running RefundVault public vault; //How many tokens were Minted uint public tokensMinted; //presale buyers mapping (address => uint256) public tokenDeposited; //event for crowdsale end event Finalized(); //event for presale mint event TokenMinted(uint count); // We distributed tokens to an investor event Distributed(address investor, uint tokenAmount); //presale period is Changed event PeriodChanged(uint256 starttm,uint256 endtm); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param investor who participate presale * @param value weis paid for purchase */ event TokenPurchase(address indexed purchaser, address indexed investor, uint256 value); function HarborPresale(address _token, uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _cap, uint256 _minimumFundingGoal, uint256 _minSend) { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != 0x0); require(_cap > 0); require(_minimumFundingGoal > 0); token = HarborToken(_token); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; cap = _cap; vault = new RefundVault(_wallet); minimumFundingGoal = _minimumFundingGoal; minSend = _minSend; } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address investor) payable stopInEmergency { require(investor != 0x0); require(validPurchase()); require(minSend <= msg.value); uint256 weiAmount = msg.value; // update state weiRaised = weiRaised.add(weiAmount); //save for distribution HBR tokenDeposited[investor] = tokenDeposited[investor].add(weiAmount); //valut save for refund vault.deposit.value(msg.value)(msg.sender); TokenPurchase(msg.sender, investor, weiAmount); } /** * Load funds to the crowdsale for all investors. */ function mintForEverybody() onlyOwner public { uint256 allTokenAmount = weiRaised.mul(rate); //for project amount (investor token *2/3) uint256 projectAmount = allTokenAmount.mul(2); projectAmount = projectAmount.div(3); //mint for investor; token.mint(address(this),allTokenAmount); //mint for project share token.mint(wallet,projectAmount); // Record how many tokens we got tokensMinted = allTokenAmount.add(projectAmount); TokenMinted(tokensMinted); } //get claim of token byself function claimToken() payable stopInEmergency{ claimTokenAddress(msg.sender); } //get claim of token by address function claimTokenAddress(address investor) payable stopInEmergency returns(uint256){ require(isFinalized); require(tokenDeposited[investor] != 0); uint256 depositedValue = tokenDeposited[investor]; tokenDeposited[investor] = 0; uint256 tokenAmount = depositedValue * rate; //send token to investor token.transfer(investor,tokenAmount); Distributed(investor, tokenAmount); return tokenAmount; } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; bool withinCap = weiRaised <= cap; return withinPeriod && nonZeroPurchase && withinCap; } // @return true if HarborPresale event has ended function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= cap; return (now > endTime) || capReached ; } /** * called after Presale ends */ function finalize() onlyOwner stopInEmergency{ require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * finalization refund or excute funds. */ function finalization() internal { if (minFundingGoalReached()) { vault.close(); } else { vault.enableRefunds(); } } // if presale is unsuccessful, investors can claim refunds here function claimRefund() stopInEmergency payable { require(isFinalized); require(!minFundingGoalReached()); vault.refund(msg.sender); } function minFundingGoalReached() public constant returns (bool) { return weiRaised >= minimumFundingGoal; } //change presale preiod function setPeriod(uint256 _startTime,uint256 _endTime) onlyOwner { require(now <= _endTime); startTime = _startTime; endTime = _endTime; PeriodChanged(startTime,endTime); } //withdrow for manual distribution function withdrawFund() onlyOwner payable{ require(isFinalized); require(minFundingGoalReached()); uint256 tokenAmount = token.balanceOf(address(this)); token.transfer(wallet, tokenAmount); } }
/** * @title HarborPresale */
NatSpecMultiLine
claimTokenAddress
function claimTokenAddress(address investor) payable stopInEmergency returns(uint256){ require(isFinalized); require(tokenDeposited[investor] != 0); uint256 depositedValue = tokenDeposited[investor]; tokenDeposited[investor] = 0; uint256 tokenAmount = depositedValue * rate; //send token to investor token.transfer(investor,tokenAmount); Distributed(investor, tokenAmount); return tokenAmount; }
//get claim of token by address
LineComment
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 3584, 4038 ] }
59,600
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
HarborPresale
contract HarborPresale is Haltable { using SafeMath for uint256; // The token being sold HarborToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are excutionFunds address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; //max amount of funds raised uint256 public cap; //is crowdsale end bool public isFinalized = false; // minimum amount of funds to be raised in weis uint256 public minimumFundingGoal; // minimum amount of funds for once uint256 public minSend; // refund vault used to hold funds while crowdsale is running RefundVault public vault; //How many tokens were Minted uint public tokensMinted; //presale buyers mapping (address => uint256) public tokenDeposited; //event for crowdsale end event Finalized(); //event for presale mint event TokenMinted(uint count); // We distributed tokens to an investor event Distributed(address investor, uint tokenAmount); //presale period is Changed event PeriodChanged(uint256 starttm,uint256 endtm); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param investor who participate presale * @param value weis paid for purchase */ event TokenPurchase(address indexed purchaser, address indexed investor, uint256 value); function HarborPresale(address _token, uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _cap, uint256 _minimumFundingGoal, uint256 _minSend) { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != 0x0); require(_cap > 0); require(_minimumFundingGoal > 0); token = HarborToken(_token); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; cap = _cap; vault = new RefundVault(_wallet); minimumFundingGoal = _minimumFundingGoal; minSend = _minSend; } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address investor) payable stopInEmergency { require(investor != 0x0); require(validPurchase()); require(minSend <= msg.value); uint256 weiAmount = msg.value; // update state weiRaised = weiRaised.add(weiAmount); //save for distribution HBR tokenDeposited[investor] = tokenDeposited[investor].add(weiAmount); //valut save for refund vault.deposit.value(msg.value)(msg.sender); TokenPurchase(msg.sender, investor, weiAmount); } /** * Load funds to the crowdsale for all investors. */ function mintForEverybody() onlyOwner public { uint256 allTokenAmount = weiRaised.mul(rate); //for project amount (investor token *2/3) uint256 projectAmount = allTokenAmount.mul(2); projectAmount = projectAmount.div(3); //mint for investor; token.mint(address(this),allTokenAmount); //mint for project share token.mint(wallet,projectAmount); // Record how many tokens we got tokensMinted = allTokenAmount.add(projectAmount); TokenMinted(tokensMinted); } //get claim of token byself function claimToken() payable stopInEmergency{ claimTokenAddress(msg.sender); } //get claim of token by address function claimTokenAddress(address investor) payable stopInEmergency returns(uint256){ require(isFinalized); require(tokenDeposited[investor] != 0); uint256 depositedValue = tokenDeposited[investor]; tokenDeposited[investor] = 0; uint256 tokenAmount = depositedValue * rate; //send token to investor token.transfer(investor,tokenAmount); Distributed(investor, tokenAmount); return tokenAmount; } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; bool withinCap = weiRaised <= cap; return withinPeriod && nonZeroPurchase && withinCap; } // @return true if HarborPresale event has ended function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= cap; return (now > endTime) || capReached ; } /** * called after Presale ends */ function finalize() onlyOwner stopInEmergency{ require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * finalization refund or excute funds. */ function finalization() internal { if (minFundingGoalReached()) { vault.close(); } else { vault.enableRefunds(); } } // if presale is unsuccessful, investors can claim refunds here function claimRefund() stopInEmergency payable { require(isFinalized); require(!minFundingGoalReached()); vault.refund(msg.sender); } function minFundingGoalReached() public constant returns (bool) { return weiRaised >= minimumFundingGoal; } //change presale preiod function setPeriod(uint256 _startTime,uint256 _endTime) onlyOwner { require(now <= _endTime); startTime = _startTime; endTime = _endTime; PeriodChanged(startTime,endTime); } //withdrow for manual distribution function withdrawFund() onlyOwner payable{ require(isFinalized); require(minFundingGoalReached()); uint256 tokenAmount = token.balanceOf(address(this)); token.transfer(wallet, tokenAmount); } }
/** * @title HarborPresale */
NatSpecMultiLine
validPurchase
function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; bool withinCap = weiRaised <= cap; return withinPeriod && nonZeroPurchase && withinCap; }
// @return true if the transaction can buy tokens
LineComment
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 4092, 4362 ] }
59,601
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
HarborPresale
contract HarborPresale is Haltable { using SafeMath for uint256; // The token being sold HarborToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are excutionFunds address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; //max amount of funds raised uint256 public cap; //is crowdsale end bool public isFinalized = false; // minimum amount of funds to be raised in weis uint256 public minimumFundingGoal; // minimum amount of funds for once uint256 public minSend; // refund vault used to hold funds while crowdsale is running RefundVault public vault; //How many tokens were Minted uint public tokensMinted; //presale buyers mapping (address => uint256) public tokenDeposited; //event for crowdsale end event Finalized(); //event for presale mint event TokenMinted(uint count); // We distributed tokens to an investor event Distributed(address investor, uint tokenAmount); //presale period is Changed event PeriodChanged(uint256 starttm,uint256 endtm); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param investor who participate presale * @param value weis paid for purchase */ event TokenPurchase(address indexed purchaser, address indexed investor, uint256 value); function HarborPresale(address _token, uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _cap, uint256 _minimumFundingGoal, uint256 _minSend) { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != 0x0); require(_cap > 0); require(_minimumFundingGoal > 0); token = HarborToken(_token); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; cap = _cap; vault = new RefundVault(_wallet); minimumFundingGoal = _minimumFundingGoal; minSend = _minSend; } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address investor) payable stopInEmergency { require(investor != 0x0); require(validPurchase()); require(minSend <= msg.value); uint256 weiAmount = msg.value; // update state weiRaised = weiRaised.add(weiAmount); //save for distribution HBR tokenDeposited[investor] = tokenDeposited[investor].add(weiAmount); //valut save for refund vault.deposit.value(msg.value)(msg.sender); TokenPurchase(msg.sender, investor, weiAmount); } /** * Load funds to the crowdsale for all investors. */ function mintForEverybody() onlyOwner public { uint256 allTokenAmount = weiRaised.mul(rate); //for project amount (investor token *2/3) uint256 projectAmount = allTokenAmount.mul(2); projectAmount = projectAmount.div(3); //mint for investor; token.mint(address(this),allTokenAmount); //mint for project share token.mint(wallet,projectAmount); // Record how many tokens we got tokensMinted = allTokenAmount.add(projectAmount); TokenMinted(tokensMinted); } //get claim of token byself function claimToken() payable stopInEmergency{ claimTokenAddress(msg.sender); } //get claim of token by address function claimTokenAddress(address investor) payable stopInEmergency returns(uint256){ require(isFinalized); require(tokenDeposited[investor] != 0); uint256 depositedValue = tokenDeposited[investor]; tokenDeposited[investor] = 0; uint256 tokenAmount = depositedValue * rate; //send token to investor token.transfer(investor,tokenAmount); Distributed(investor, tokenAmount); return tokenAmount; } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; bool withinCap = weiRaised <= cap; return withinPeriod && nonZeroPurchase && withinCap; } // @return true if HarborPresale event has ended function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= cap; return (now > endTime) || capReached ; } /** * called after Presale ends */ function finalize() onlyOwner stopInEmergency{ require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * finalization refund or excute funds. */ function finalization() internal { if (minFundingGoalReached()) { vault.close(); } else { vault.enableRefunds(); } } // if presale is unsuccessful, investors can claim refunds here function claimRefund() stopInEmergency payable { require(isFinalized); require(!minFundingGoalReached()); vault.refund(msg.sender); } function minFundingGoalReached() public constant returns (bool) { return weiRaised >= minimumFundingGoal; } //change presale preiod function setPeriod(uint256 _startTime,uint256 _endTime) onlyOwner { require(now <= _endTime); startTime = _startTime; endTime = _endTime; PeriodChanged(startTime,endTime); } //withdrow for manual distribution function withdrawFund() onlyOwner payable{ require(isFinalized); require(minFundingGoalReached()); uint256 tokenAmount = token.balanceOf(address(this)); token.transfer(wallet, tokenAmount); } }
/** * @title HarborPresale */
NatSpecMultiLine
hasEnded
function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= cap; return (now > endTime) || capReached ; }
// @return true if HarborPresale event has ended
LineComment
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 4415, 4560 ] }
59,602
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
HarborPresale
contract HarborPresale is Haltable { using SafeMath for uint256; // The token being sold HarborToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are excutionFunds address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; //max amount of funds raised uint256 public cap; //is crowdsale end bool public isFinalized = false; // minimum amount of funds to be raised in weis uint256 public minimumFundingGoal; // minimum amount of funds for once uint256 public minSend; // refund vault used to hold funds while crowdsale is running RefundVault public vault; //How many tokens were Minted uint public tokensMinted; //presale buyers mapping (address => uint256) public tokenDeposited; //event for crowdsale end event Finalized(); //event for presale mint event TokenMinted(uint count); // We distributed tokens to an investor event Distributed(address investor, uint tokenAmount); //presale period is Changed event PeriodChanged(uint256 starttm,uint256 endtm); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param investor who participate presale * @param value weis paid for purchase */ event TokenPurchase(address indexed purchaser, address indexed investor, uint256 value); function HarborPresale(address _token, uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _cap, uint256 _minimumFundingGoal, uint256 _minSend) { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != 0x0); require(_cap > 0); require(_minimumFundingGoal > 0); token = HarborToken(_token); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; cap = _cap; vault = new RefundVault(_wallet); minimumFundingGoal = _minimumFundingGoal; minSend = _minSend; } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address investor) payable stopInEmergency { require(investor != 0x0); require(validPurchase()); require(minSend <= msg.value); uint256 weiAmount = msg.value; // update state weiRaised = weiRaised.add(weiAmount); //save for distribution HBR tokenDeposited[investor] = tokenDeposited[investor].add(weiAmount); //valut save for refund vault.deposit.value(msg.value)(msg.sender); TokenPurchase(msg.sender, investor, weiAmount); } /** * Load funds to the crowdsale for all investors. */ function mintForEverybody() onlyOwner public { uint256 allTokenAmount = weiRaised.mul(rate); //for project amount (investor token *2/3) uint256 projectAmount = allTokenAmount.mul(2); projectAmount = projectAmount.div(3); //mint for investor; token.mint(address(this),allTokenAmount); //mint for project share token.mint(wallet,projectAmount); // Record how many tokens we got tokensMinted = allTokenAmount.add(projectAmount); TokenMinted(tokensMinted); } //get claim of token byself function claimToken() payable stopInEmergency{ claimTokenAddress(msg.sender); } //get claim of token by address function claimTokenAddress(address investor) payable stopInEmergency returns(uint256){ require(isFinalized); require(tokenDeposited[investor] != 0); uint256 depositedValue = tokenDeposited[investor]; tokenDeposited[investor] = 0; uint256 tokenAmount = depositedValue * rate; //send token to investor token.transfer(investor,tokenAmount); Distributed(investor, tokenAmount); return tokenAmount; } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; bool withinCap = weiRaised <= cap; return withinPeriod && nonZeroPurchase && withinCap; } // @return true if HarborPresale event has ended function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= cap; return (now > endTime) || capReached ; } /** * called after Presale ends */ function finalize() onlyOwner stopInEmergency{ require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * finalization refund or excute funds. */ function finalization() internal { if (minFundingGoalReached()) { vault.close(); } else { vault.enableRefunds(); } } // if presale is unsuccessful, investors can claim refunds here function claimRefund() stopInEmergency payable { require(isFinalized); require(!minFundingGoalReached()); vault.refund(msg.sender); } function minFundingGoalReached() public constant returns (bool) { return weiRaised >= minimumFundingGoal; } //change presale preiod function setPeriod(uint256 _startTime,uint256 _endTime) onlyOwner { require(now <= _endTime); startTime = _startTime; endTime = _endTime; PeriodChanged(startTime,endTime); } //withdrow for manual distribution function withdrawFund() onlyOwner payable{ require(isFinalized); require(minFundingGoalReached()); uint256 tokenAmount = token.balanceOf(address(this)); token.transfer(wallet, tokenAmount); } }
/** * @title HarborPresale */
NatSpecMultiLine
finalize
function finalize() onlyOwner stopInEmergency{ require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; }
/** * called after Presale ends */
NatSpecMultiLine
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 4609, 4787 ] }
59,603
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
HarborPresale
contract HarborPresale is Haltable { using SafeMath for uint256; // The token being sold HarborToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are excutionFunds address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; //max amount of funds raised uint256 public cap; //is crowdsale end bool public isFinalized = false; // minimum amount of funds to be raised in weis uint256 public minimumFundingGoal; // minimum amount of funds for once uint256 public minSend; // refund vault used to hold funds while crowdsale is running RefundVault public vault; //How many tokens were Minted uint public tokensMinted; //presale buyers mapping (address => uint256) public tokenDeposited; //event for crowdsale end event Finalized(); //event for presale mint event TokenMinted(uint count); // We distributed tokens to an investor event Distributed(address investor, uint tokenAmount); //presale period is Changed event PeriodChanged(uint256 starttm,uint256 endtm); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param investor who participate presale * @param value weis paid for purchase */ event TokenPurchase(address indexed purchaser, address indexed investor, uint256 value); function HarborPresale(address _token, uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _cap, uint256 _minimumFundingGoal, uint256 _minSend) { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != 0x0); require(_cap > 0); require(_minimumFundingGoal > 0); token = HarborToken(_token); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; cap = _cap; vault = new RefundVault(_wallet); minimumFundingGoal = _minimumFundingGoal; minSend = _minSend; } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address investor) payable stopInEmergency { require(investor != 0x0); require(validPurchase()); require(minSend <= msg.value); uint256 weiAmount = msg.value; // update state weiRaised = weiRaised.add(weiAmount); //save for distribution HBR tokenDeposited[investor] = tokenDeposited[investor].add(weiAmount); //valut save for refund vault.deposit.value(msg.value)(msg.sender); TokenPurchase(msg.sender, investor, weiAmount); } /** * Load funds to the crowdsale for all investors. */ function mintForEverybody() onlyOwner public { uint256 allTokenAmount = weiRaised.mul(rate); //for project amount (investor token *2/3) uint256 projectAmount = allTokenAmount.mul(2); projectAmount = projectAmount.div(3); //mint for investor; token.mint(address(this),allTokenAmount); //mint for project share token.mint(wallet,projectAmount); // Record how many tokens we got tokensMinted = allTokenAmount.add(projectAmount); TokenMinted(tokensMinted); } //get claim of token byself function claimToken() payable stopInEmergency{ claimTokenAddress(msg.sender); } //get claim of token by address function claimTokenAddress(address investor) payable stopInEmergency returns(uint256){ require(isFinalized); require(tokenDeposited[investor] != 0); uint256 depositedValue = tokenDeposited[investor]; tokenDeposited[investor] = 0; uint256 tokenAmount = depositedValue * rate; //send token to investor token.transfer(investor,tokenAmount); Distributed(investor, tokenAmount); return tokenAmount; } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; bool withinCap = weiRaised <= cap; return withinPeriod && nonZeroPurchase && withinCap; } // @return true if HarborPresale event has ended function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= cap; return (now > endTime) || capReached ; } /** * called after Presale ends */ function finalize() onlyOwner stopInEmergency{ require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * finalization refund or excute funds. */ function finalization() internal { if (minFundingGoalReached()) { vault.close(); } else { vault.enableRefunds(); } } // if presale is unsuccessful, investors can claim refunds here function claimRefund() stopInEmergency payable { require(isFinalized); require(!minFundingGoalReached()); vault.refund(msg.sender); } function minFundingGoalReached() public constant returns (bool) { return weiRaised >= minimumFundingGoal; } //change presale preiod function setPeriod(uint256 _startTime,uint256 _endTime) onlyOwner { require(now <= _endTime); startTime = _startTime; endTime = _endTime; PeriodChanged(startTime,endTime); } //withdrow for manual distribution function withdrawFund() onlyOwner payable{ require(isFinalized); require(minFundingGoalReached()); uint256 tokenAmount = token.balanceOf(address(this)); token.transfer(wallet, tokenAmount); } }
/** * @title HarborPresale */
NatSpecMultiLine
finalization
function finalization() internal { if (minFundingGoalReached()) { vault.close(); } else { vault.enableRefunds(); } }
/** * finalization refund or excute funds. */
NatSpecMultiLine
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 4847, 4998 ] }
59,604
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
HarborPresale
contract HarborPresale is Haltable { using SafeMath for uint256; // The token being sold HarborToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are excutionFunds address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; //max amount of funds raised uint256 public cap; //is crowdsale end bool public isFinalized = false; // minimum amount of funds to be raised in weis uint256 public minimumFundingGoal; // minimum amount of funds for once uint256 public minSend; // refund vault used to hold funds while crowdsale is running RefundVault public vault; //How many tokens were Minted uint public tokensMinted; //presale buyers mapping (address => uint256) public tokenDeposited; //event for crowdsale end event Finalized(); //event for presale mint event TokenMinted(uint count); // We distributed tokens to an investor event Distributed(address investor, uint tokenAmount); //presale period is Changed event PeriodChanged(uint256 starttm,uint256 endtm); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param investor who participate presale * @param value weis paid for purchase */ event TokenPurchase(address indexed purchaser, address indexed investor, uint256 value); function HarborPresale(address _token, uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _cap, uint256 _minimumFundingGoal, uint256 _minSend) { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != 0x0); require(_cap > 0); require(_minimumFundingGoal > 0); token = HarborToken(_token); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; cap = _cap; vault = new RefundVault(_wallet); minimumFundingGoal = _minimumFundingGoal; minSend = _minSend; } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address investor) payable stopInEmergency { require(investor != 0x0); require(validPurchase()); require(minSend <= msg.value); uint256 weiAmount = msg.value; // update state weiRaised = weiRaised.add(weiAmount); //save for distribution HBR tokenDeposited[investor] = tokenDeposited[investor].add(weiAmount); //valut save for refund vault.deposit.value(msg.value)(msg.sender); TokenPurchase(msg.sender, investor, weiAmount); } /** * Load funds to the crowdsale for all investors. */ function mintForEverybody() onlyOwner public { uint256 allTokenAmount = weiRaised.mul(rate); //for project amount (investor token *2/3) uint256 projectAmount = allTokenAmount.mul(2); projectAmount = projectAmount.div(3); //mint for investor; token.mint(address(this),allTokenAmount); //mint for project share token.mint(wallet,projectAmount); // Record how many tokens we got tokensMinted = allTokenAmount.add(projectAmount); TokenMinted(tokensMinted); } //get claim of token byself function claimToken() payable stopInEmergency{ claimTokenAddress(msg.sender); } //get claim of token by address function claimTokenAddress(address investor) payable stopInEmergency returns(uint256){ require(isFinalized); require(tokenDeposited[investor] != 0); uint256 depositedValue = tokenDeposited[investor]; tokenDeposited[investor] = 0; uint256 tokenAmount = depositedValue * rate; //send token to investor token.transfer(investor,tokenAmount); Distributed(investor, tokenAmount); return tokenAmount; } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; bool withinCap = weiRaised <= cap; return withinPeriod && nonZeroPurchase && withinCap; } // @return true if HarborPresale event has ended function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= cap; return (now > endTime) || capReached ; } /** * called after Presale ends */ function finalize() onlyOwner stopInEmergency{ require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * finalization refund or excute funds. */ function finalization() internal { if (minFundingGoalReached()) { vault.close(); } else { vault.enableRefunds(); } } // if presale is unsuccessful, investors can claim refunds here function claimRefund() stopInEmergency payable { require(isFinalized); require(!minFundingGoalReached()); vault.refund(msg.sender); } function minFundingGoalReached() public constant returns (bool) { return weiRaised >= minimumFundingGoal; } //change presale preiod function setPeriod(uint256 _startTime,uint256 _endTime) onlyOwner { require(now <= _endTime); startTime = _startTime; endTime = _endTime; PeriodChanged(startTime,endTime); } //withdrow for manual distribution function withdrawFund() onlyOwner payable{ require(isFinalized); require(minFundingGoalReached()); uint256 tokenAmount = token.balanceOf(address(this)); token.transfer(wallet, tokenAmount); } }
/** * @title HarborPresale */
NatSpecMultiLine
claimRefund
function claimRefund() stopInEmergency payable { require(isFinalized); require(!minFundingGoalReached()); vault.refund(msg.sender); }
// if presale is unsuccessful, investors can claim refunds here
LineComment
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 5067, 5221 ] }
59,605
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
HarborPresale
contract HarborPresale is Haltable { using SafeMath for uint256; // The token being sold HarborToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are excutionFunds address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; //max amount of funds raised uint256 public cap; //is crowdsale end bool public isFinalized = false; // minimum amount of funds to be raised in weis uint256 public minimumFundingGoal; // minimum amount of funds for once uint256 public minSend; // refund vault used to hold funds while crowdsale is running RefundVault public vault; //How many tokens were Minted uint public tokensMinted; //presale buyers mapping (address => uint256) public tokenDeposited; //event for crowdsale end event Finalized(); //event for presale mint event TokenMinted(uint count); // We distributed tokens to an investor event Distributed(address investor, uint tokenAmount); //presale period is Changed event PeriodChanged(uint256 starttm,uint256 endtm); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param investor who participate presale * @param value weis paid for purchase */ event TokenPurchase(address indexed purchaser, address indexed investor, uint256 value); function HarborPresale(address _token, uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _cap, uint256 _minimumFundingGoal, uint256 _minSend) { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != 0x0); require(_cap > 0); require(_minimumFundingGoal > 0); token = HarborToken(_token); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; cap = _cap; vault = new RefundVault(_wallet); minimumFundingGoal = _minimumFundingGoal; minSend = _minSend; } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address investor) payable stopInEmergency { require(investor != 0x0); require(validPurchase()); require(minSend <= msg.value); uint256 weiAmount = msg.value; // update state weiRaised = weiRaised.add(weiAmount); //save for distribution HBR tokenDeposited[investor] = tokenDeposited[investor].add(weiAmount); //valut save for refund vault.deposit.value(msg.value)(msg.sender); TokenPurchase(msg.sender, investor, weiAmount); } /** * Load funds to the crowdsale for all investors. */ function mintForEverybody() onlyOwner public { uint256 allTokenAmount = weiRaised.mul(rate); //for project amount (investor token *2/3) uint256 projectAmount = allTokenAmount.mul(2); projectAmount = projectAmount.div(3); //mint for investor; token.mint(address(this),allTokenAmount); //mint for project share token.mint(wallet,projectAmount); // Record how many tokens we got tokensMinted = allTokenAmount.add(projectAmount); TokenMinted(tokensMinted); } //get claim of token byself function claimToken() payable stopInEmergency{ claimTokenAddress(msg.sender); } //get claim of token by address function claimTokenAddress(address investor) payable stopInEmergency returns(uint256){ require(isFinalized); require(tokenDeposited[investor] != 0); uint256 depositedValue = tokenDeposited[investor]; tokenDeposited[investor] = 0; uint256 tokenAmount = depositedValue * rate; //send token to investor token.transfer(investor,tokenAmount); Distributed(investor, tokenAmount); return tokenAmount; } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; bool withinCap = weiRaised <= cap; return withinPeriod && nonZeroPurchase && withinCap; } // @return true if HarborPresale event has ended function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= cap; return (now > endTime) || capReached ; } /** * called after Presale ends */ function finalize() onlyOwner stopInEmergency{ require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * finalization refund or excute funds. */ function finalization() internal { if (minFundingGoalReached()) { vault.close(); } else { vault.enableRefunds(); } } // if presale is unsuccessful, investors can claim refunds here function claimRefund() stopInEmergency payable { require(isFinalized); require(!minFundingGoalReached()); vault.refund(msg.sender); } function minFundingGoalReached() public constant returns (bool) { return weiRaised >= minimumFundingGoal; } //change presale preiod function setPeriod(uint256 _startTime,uint256 _endTime) onlyOwner { require(now <= _endTime); startTime = _startTime; endTime = _endTime; PeriodChanged(startTime,endTime); } //withdrow for manual distribution function withdrawFund() onlyOwner payable{ require(isFinalized); require(minFundingGoalReached()); uint256 tokenAmount = token.balanceOf(address(this)); token.transfer(wallet, tokenAmount); } }
/** * @title HarborPresale */
NatSpecMultiLine
setPeriod
function setPeriod(uint256 _startTime,uint256 _endTime) onlyOwner { require(now <= _endTime); startTime = _startTime; endTime = _endTime; PeriodChanged(startTime,endTime); }
//change presale preiod
LineComment
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 5369, 5568 ] }
59,606
HarborPresale
HarborPresale.sol
0x402fa04ccd2c2568e1a53dbecec1bd572303663a
Solidity
HarborPresale
contract HarborPresale is Haltable { using SafeMath for uint256; // The token being sold HarborToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are excutionFunds address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; //max amount of funds raised uint256 public cap; //is crowdsale end bool public isFinalized = false; // minimum amount of funds to be raised in weis uint256 public minimumFundingGoal; // minimum amount of funds for once uint256 public minSend; // refund vault used to hold funds while crowdsale is running RefundVault public vault; //How many tokens were Minted uint public tokensMinted; //presale buyers mapping (address => uint256) public tokenDeposited; //event for crowdsale end event Finalized(); //event for presale mint event TokenMinted(uint count); // We distributed tokens to an investor event Distributed(address investor, uint tokenAmount); //presale period is Changed event PeriodChanged(uint256 starttm,uint256 endtm); /** * event for token purchase logging * @param purchaser who paid for the tokens * @param investor who participate presale * @param value weis paid for purchase */ event TokenPurchase(address indexed purchaser, address indexed investor, uint256 value); function HarborPresale(address _token, uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _cap, uint256 _minimumFundingGoal, uint256 _minSend) { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != 0x0); require(_cap > 0); require(_minimumFundingGoal > 0); token = HarborToken(_token); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; cap = _cap; vault = new RefundVault(_wallet); minimumFundingGoal = _minimumFundingGoal; minSend = _minSend; } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address investor) payable stopInEmergency { require(investor != 0x0); require(validPurchase()); require(minSend <= msg.value); uint256 weiAmount = msg.value; // update state weiRaised = weiRaised.add(weiAmount); //save for distribution HBR tokenDeposited[investor] = tokenDeposited[investor].add(weiAmount); //valut save for refund vault.deposit.value(msg.value)(msg.sender); TokenPurchase(msg.sender, investor, weiAmount); } /** * Load funds to the crowdsale for all investors. */ function mintForEverybody() onlyOwner public { uint256 allTokenAmount = weiRaised.mul(rate); //for project amount (investor token *2/3) uint256 projectAmount = allTokenAmount.mul(2); projectAmount = projectAmount.div(3); //mint for investor; token.mint(address(this),allTokenAmount); //mint for project share token.mint(wallet,projectAmount); // Record how many tokens we got tokensMinted = allTokenAmount.add(projectAmount); TokenMinted(tokensMinted); } //get claim of token byself function claimToken() payable stopInEmergency{ claimTokenAddress(msg.sender); } //get claim of token by address function claimTokenAddress(address investor) payable stopInEmergency returns(uint256){ require(isFinalized); require(tokenDeposited[investor] != 0); uint256 depositedValue = tokenDeposited[investor]; tokenDeposited[investor] = 0; uint256 tokenAmount = depositedValue * rate; //send token to investor token.transfer(investor,tokenAmount); Distributed(investor, tokenAmount); return tokenAmount; } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; bool withinCap = weiRaised <= cap; return withinPeriod && nonZeroPurchase && withinCap; } // @return true if HarborPresale event has ended function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= cap; return (now > endTime) || capReached ; } /** * called after Presale ends */ function finalize() onlyOwner stopInEmergency{ require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * finalization refund or excute funds. */ function finalization() internal { if (minFundingGoalReached()) { vault.close(); } else { vault.enableRefunds(); } } // if presale is unsuccessful, investors can claim refunds here function claimRefund() stopInEmergency payable { require(isFinalized); require(!minFundingGoalReached()); vault.refund(msg.sender); } function minFundingGoalReached() public constant returns (bool) { return weiRaised >= minimumFundingGoal; } //change presale preiod function setPeriod(uint256 _startTime,uint256 _endTime) onlyOwner { require(now <= _endTime); startTime = _startTime; endTime = _endTime; PeriodChanged(startTime,endTime); } //withdrow for manual distribution function withdrawFund() onlyOwner payable{ require(isFinalized); require(minFundingGoalReached()); uint256 tokenAmount = token.balanceOf(address(this)); token.transfer(wallet, tokenAmount); } }
/** * @title HarborPresale */
NatSpecMultiLine
withdrawFund
function withdrawFund() onlyOwner payable{ require(isFinalized); require(minFundingGoalReached()); uint256 tokenAmount = token.balanceOf(address(this)); token.transfer(wallet, tokenAmount); }
//withdrow for manual distribution
LineComment
v0.4.15-nightly.2017.7.31+commit.93f90eb2
bzzr://a55c3962accf585a31af5c60759b4c15285d92c4c33216a8ee8820640e23d8f0
{ "func_code_index": [ 5611, 5828 ] }
59,607
HATTimelockController
contracts/tokenlock/ITokenLock.sol
0x66922e992e07030ceac25e1919e9c31153f85b6f
Solidity
ITokenLock
interface ITokenLock { enum Revocability { NotSet, Enabled, Disabled } // -- Balances -- function currentBalance() external view returns (uint256); // -- Time & Periods -- function currentTime() external view returns (uint256); function duration() external view returns (uint256); function sinceStartTime() external view returns (uint256); function amountPerPeriod() external view returns (uint256); function periodDuration() external view returns (uint256); function currentPeriod() external view returns (uint256); function passedPeriods() external view returns (uint256); // -- Locking & Release Schedule -- function availableAmount() external view returns (uint256); function vestedAmount() external view returns (uint256); function releasableAmount() external view returns (uint256); function totalOutstandingAmount() external view returns (uint256); function surplusAmount() external view returns (uint256); // -- Value Transfer -- function release() external; function withdrawSurplus(uint256 _amount) external; function revoke() external; }
currentBalance
function currentBalance() external view returns (uint256);
// -- Balances --
LineComment
v0.8.6+commit.11564f7e
MIT
ipfs://aa139c6876984343d83fb6ce6f6a0c9b0698ebb4eb2a6247ddfe3ceed9210e5f
{ "func_code_index": [ 104, 167 ] }
59,608
HATTimelockController
contracts/tokenlock/ITokenLock.sol
0x66922e992e07030ceac25e1919e9c31153f85b6f
Solidity
ITokenLock
interface ITokenLock { enum Revocability { NotSet, Enabled, Disabled } // -- Balances -- function currentBalance() external view returns (uint256); // -- Time & Periods -- function currentTime() external view returns (uint256); function duration() external view returns (uint256); function sinceStartTime() external view returns (uint256); function amountPerPeriod() external view returns (uint256); function periodDuration() external view returns (uint256); function currentPeriod() external view returns (uint256); function passedPeriods() external view returns (uint256); // -- Locking & Release Schedule -- function availableAmount() external view returns (uint256); function vestedAmount() external view returns (uint256); function releasableAmount() external view returns (uint256); function totalOutstandingAmount() external view returns (uint256); function surplusAmount() external view returns (uint256); // -- Value Transfer -- function release() external; function withdrawSurplus(uint256 _amount) external; function revoke() external; }
currentTime
function currentTime() external view returns (uint256);
// -- Time & Periods --
LineComment
v0.8.6+commit.11564f7e
MIT
ipfs://aa139c6876984343d83fb6ce6f6a0c9b0698ebb4eb2a6247ddfe3ceed9210e5f
{ "func_code_index": [ 201, 261 ] }
59,609
HATTimelockController
contracts/tokenlock/ITokenLock.sol
0x66922e992e07030ceac25e1919e9c31153f85b6f
Solidity
ITokenLock
interface ITokenLock { enum Revocability { NotSet, Enabled, Disabled } // -- Balances -- function currentBalance() external view returns (uint256); // -- Time & Periods -- function currentTime() external view returns (uint256); function duration() external view returns (uint256); function sinceStartTime() external view returns (uint256); function amountPerPeriod() external view returns (uint256); function periodDuration() external view returns (uint256); function currentPeriod() external view returns (uint256); function passedPeriods() external view returns (uint256); // -- Locking & Release Schedule -- function availableAmount() external view returns (uint256); function vestedAmount() external view returns (uint256); function releasableAmount() external view returns (uint256); function totalOutstandingAmount() external view returns (uint256); function surplusAmount() external view returns (uint256); // -- Value Transfer -- function release() external; function withdrawSurplus(uint256 _amount) external; function revoke() external; }
availableAmount
function availableAmount() external view returns (uint256);
// -- Locking & Release Schedule --
LineComment
v0.8.6+commit.11564f7e
MIT
ipfs://aa139c6876984343d83fb6ce6f6a0c9b0698ebb4eb2a6247ddfe3ceed9210e5f
{ "func_code_index": [ 696, 760 ] }
59,610
HATTimelockController
contracts/tokenlock/ITokenLock.sol
0x66922e992e07030ceac25e1919e9c31153f85b6f
Solidity
ITokenLock
interface ITokenLock { enum Revocability { NotSet, Enabled, Disabled } // -- Balances -- function currentBalance() external view returns (uint256); // -- Time & Periods -- function currentTime() external view returns (uint256); function duration() external view returns (uint256); function sinceStartTime() external view returns (uint256); function amountPerPeriod() external view returns (uint256); function periodDuration() external view returns (uint256); function currentPeriod() external view returns (uint256); function passedPeriods() external view returns (uint256); // -- Locking & Release Schedule -- function availableAmount() external view returns (uint256); function vestedAmount() external view returns (uint256); function releasableAmount() external view returns (uint256); function totalOutstandingAmount() external view returns (uint256); function surplusAmount() external view returns (uint256); // -- Value Transfer -- function release() external; function withdrawSurplus(uint256 _amount) external; function revoke() external; }
release
function release() external;
// -- Value Transfer --
LineComment
v0.8.6+commit.11564f7e
MIT
ipfs://aa139c6876984343d83fb6ce6f6a0c9b0698ebb4eb2a6247ddfe3ceed9210e5f
{ "func_code_index": [ 1065, 1098 ] }
59,611
Packs
contracts/Packs.sol
0x1495ecbac40a69028b5d516597137de5e929b01b
Solidity
Packs
contract Packs is IPacks, ERC721, ReentrancyGuard { using SafeMath for uint256; constructor( string memory name, string memory symbol, string memory _baseURI, bool _editioned, uint256[] memory _initParams, string memory _licenseURI, address _mintPass, uint256 _mintPassDuration, bool[] memory _mintPassParams ) ERC721(name, symbol) { LibPackStorage.Storage storage ds = LibPackStorage.packStorage(); ds.relicsAddress = address(this); ds.daoAddress = msg.sender; ds.daoInitialized = true; ds.collectionCount = 0; createNewCollection(_baseURI, _editioned, _initParams, _licenseURI, _mintPass, _mintPassDuration, _mintPassParams); _setBaseURI(_baseURI); } bytes4 private constant _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584; bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x2a55205a; function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == _INTERFACE_ID_ROYALTIES_RARIBLE || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981 || super.supportsInterface(interfaceId); } modifier onlyDAO() { LibPackStorage.Storage storage ds = LibPackStorage.packStorage(); require(msg.sender == ds.daoAddress, "Wrong address"); _; } function transferDAOownership(address payable _daoAddress) public override onlyDAO { LibPackStorage.Storage storage ds = LibPackStorage.packStorage(); ds.daoAddress = _daoAddress; ds.daoInitialized = true; } function createNewCollection(string memory _baseURI, bool _editioned, uint256[] memory _initParams, string memory _licenseURI, address _mintPass, uint256 _mintPassDuration, bool[] memory _mintPassParams) public override onlyDAO { LibPackStorage.createNewCollection(_baseURI, _editioned, _initParams, _licenseURI, _mintPass, _mintPassDuration, _mintPassParams); } function addCollectible(uint256 cID, string[] memory _coreData, string[] memory _assets, string[][] memory _metadataValues, string[][] memory _secondaryMetadata, LibPackStorage.Fee[] memory _fees) public override onlyDAO { require(_coreData.length == 4, 'Misformat'); LibPackStorage.addCollectible(cID, _coreData, _assets, _metadataValues, _secondaryMetadata, _fees); } function bulkAddCollectible(uint256 cID, string[][] memory _coreData, string[][] memory _assets, string[][][] memory _metadataValues, string[][][] memory _secondaryMetadata, LibPackStorage.Fee[][] memory _fees) public override onlyDAO { for (uint256 i = 0; i < _coreData.length; i++) { addCollectible(cID, _coreData[i], _assets[i], _metadataValues[i], _secondaryMetadata[i], _fees[i]); } } function randomTokenID(uint256 cID) private returns (uint256) { LibPackStorage.Storage storage ds = LibPackStorage.packStorage(); (uint256 randomID, uint256 tokenID) = LibPackStorage.randomTokenID(address(this), cID); ds.collection[cID].shuffleIDs[randomID] = ds.collection[cID].shuffleIDs[ds.collection[cID].shuffleIDs.length - 1]; ds.collection[cID].shuffleIDs.pop(); return tokenID; } function mintPack(uint256 cID) public override payable nonReentrant { LibPackStorage.Storage storage ds = LibPackStorage.packStorage(); bool canMintPass = LibPackStorage.checkMintPass(address(this), cID, msg.sender, address(this)); uint256 excessAmount; if (canMintPass && ds.collection[cID].mintPassFree) excessAmount = msg.value.sub(0); else excessAmount = msg.value.sub(ds.collection[cID].tokenPrice); if (excessAmount > 0) { (bool returnExcessStatus, ) = _msgSender().call{value: excessAmount}(""); require(returnExcessStatus, "Failed to return excess."); } uint256 tokenID = randomTokenID(cID); _mint(_msgSender(), tokenID); } function bulkMintPack(uint256 cID, uint256 amount) public override payable nonReentrant { LibPackStorage.Storage storage ds = LibPackStorage.packStorage(); LibPackStorage.bulkMintChecks(cID, amount); uint256 excessAmount = msg.value.sub(ds.collection[cID].tokenPrice.mul(amount)); if (excessAmount > 0) { (bool returnExcessStatus, ) = _msgSender().call{value: excessAmount}(""); require(returnExcessStatus, "Failed to return excess."); } for (uint256 i = 0; i < amount; i++) { uint256 tokenID = randomTokenID(cID); _mint(_msgSender(), tokenID); } } function mintPassClaimed(uint256 cID, uint256 tokenId) public override view returns (bool) { return LibPackStorage.mintPassClaimed(cID, tokenId); } function tokensClaimable(uint256 cID, address minter) public override view returns (uint256[] memory) { return LibPackStorage.tokensClaimable(cID, minter); } function remainingTokens(uint256 cID) public override view returns (uint256) { return LibPackStorage.remainingTokens(cID); } function updateMetadata(uint256 cID, uint256 collectibleId, uint256 propertyIndex, string memory value) public override onlyDAO { LibPackStorage.updateMetadata(cID, collectibleId, propertyIndex, value); } function addVersion(uint256 cID, uint256 collectibleId, string memory asset) public override onlyDAO { LibPackStorage.addVersion(cID, collectibleId, asset); } // function updateVersion(uint256 cID, uint256 collectibleId, uint256 versionNumber) public override onlyDAO { // LibPackStorage.updateVersion(cID, collectibleId, versionNumber); // } function addNewLicense(uint256 cID, string memory _license) public override onlyDAO { LibPackStorage.addNewLicense(cID, _license); } function getLicense(uint256 cID, uint256 versionNumber) public override view returns (string memory) { return LibPackStorage.getLicense(cID, versionNumber); } function getCollectionCount() public override view returns (uint256) { return LibPackStorage.packStorage().collectionCount; } function tokenURI(uint256 tokenId) public view virtual override(ERC721, IPacks) returns (string memory) { return LibPackStorage.tokenURI(tokenId); } function getFeeRecipients(uint256 tokenId) public override view returns (address payable[] memory) { require(_exists(tokenId), "Nonexistent token"); return LibPackStorage.getFeeRecipients(tokenId); } function getFeeBps(uint256 tokenId) public override view returns (uint256[] memory) { require(_exists(tokenId), "Nonexistent token"); return LibPackStorage.getFeeBps(tokenId); } function royaltyInfo(uint256 tokenId, uint256 value) public override view returns (address recipient, uint256 amount){ require(_exists(tokenId), "Nonexistent token"); return LibPackStorage.royaltyInfo(tokenId, value); } function withdraw(address _to, uint amount) public onlyDAO { payable(_to).call{value:amount, gas:200000}(""); } }
addNewLicense
function addNewLicense(uint256 cID, string memory _license) public override onlyDAO { LibPackStorage.addNewLicense(cID, _license); }
// function updateVersion(uint256 cID, uint256 collectibleId, uint256 versionNumber) public override onlyDAO { // LibPackStorage.updateVersion(cID, collectibleId, versionNumber); // }
LineComment
v0.7.3+commit.9bfce1f6
{ "func_code_index": [ 5441, 5581 ] }
59,612
HATTimelockController
contracts/tokenlock/ITokenLockFactory.sol
0x66922e992e07030ceac25e1919e9c31153f85b6f
Solidity
ITokenLockFactory
interface ITokenLockFactory { // -- Factory -- function setMasterCopy(address _masterCopy) external; function createTokenLock( address _token, address _owner, address _beneficiary, uint256 _managedAmount, uint256 _startTime, uint256 _endTime, uint256 _periods, uint256 _releaseStartTime, uint256 _vestingCliffTime, ITokenLock.Revocability _revocable, bool _canDelegate ) external returns(address contractAddress); }
setMasterCopy
function setMasterCopy(address _masterCopy) external;
// -- Factory --
LineComment
v0.8.6+commit.11564f7e
MIT
ipfs://aa139c6876984343d83fb6ce6f6a0c9b0698ebb4eb2a6247ddfe3ceed9210e5f
{ "func_code_index": [ 53, 111 ] }
59,613
HATTimelockController
contracts/Governable.sol
0x66922e992e07030ceac25e1919e9c31153f85b6f
Solidity
Governable
contract Governable { address private _governance; address public governancePending; uint256 public setGovernancePendingAt; uint256 public constant TIME_LOCK_DELAY = 2 days; /// @notice An event thats emitted when a new governance address is set event GovernorshipTransferred(address indexed _previousGovernance, address indexed _newGovernance); /// @notice An event thats emitted when a new governance address is pending event GovernancePending(address indexed _previousGovernance, address indexed _newGovernance, uint256 _at); /** * @dev Throws if called by any account other than the governance. */ modifier onlyGovernance() { require(msg.sender == _governance, "only governance"); _; } /** * @dev setPendingGovernance set a pending governance address. * NOTE: transferGovernorship can be called after a time delay of 2 days. */ function setPendingGovernance(address _newGovernance) external onlyGovernance { require(_newGovernance != address(0), "Governable:new governance is the zero address"); governancePending = _newGovernance; // solhint-disable-next-line not-rely-on-time setGovernancePendingAt = block.timestamp; emit GovernancePending(_governance, _newGovernance, setGovernancePendingAt); } /** * @dev transferGovernorship transfer governorship to the pending governance address. * NOTE: transferGovernorship can be called after a time delay of 2 days from the latest setPendingGovernance. */ function transferGovernorship() external onlyGovernance { require(setGovernancePendingAt > 0, "Governable: no pending governance"); // solhint-disable-next-line not-rely-on-time require(block.timestamp - setGovernancePendingAt > TIME_LOCK_DELAY, "Governable: cannot confirm governance at this time"); emit GovernorshipTransferred(_governance, governancePending); _governance = governancePending; setGovernancePendingAt = 0; } /** * @dev Returns the address of the current governance. */ function governance() public view returns (address) { return _governance; } /** * @dev Initializes the contract setting the initial governance. */ function initialize(address _initialGovernance) internal { _governance = _initialGovernance; emit GovernorshipTransferred(address(0), _initialGovernance); } }
/** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an governance) that can be granted exclusive access to * specific functions. * * The governance account will be passed on initialization of the contract. This * can later be changed with {setPendingGovernance and then transferGovernorship after 2 days}. * * This module is used through inheritance. It will make available the modifier * `onlyGovernance`, which can be applied to your functions to restrict their use to * the governance. */
NatSpecMultiLine
setPendingGovernance
function setPendingGovernance(address _newGovernance) external onlyGovernance { require(_newGovernance != address(0), "Governable:new governance is the zero address"); governancePending = _newGovernance; // solhint-disable-next-line not-rely-on-time setGovernancePendingAt = block.timestamp; emit GovernancePending(_governance, _newGovernance, setGovernancePendingAt); }
/** * @dev setPendingGovernance set a pending governance address. * NOTE: transferGovernorship can be called after a time delay of 2 days. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
MIT
ipfs://aa139c6876984343d83fb6ce6f6a0c9b0698ebb4eb2a6247ddfe3ceed9210e5f
{ "func_code_index": [ 949, 1375 ] }
59,614
HATTimelockController
contracts/Governable.sol
0x66922e992e07030ceac25e1919e9c31153f85b6f
Solidity
Governable
contract Governable { address private _governance; address public governancePending; uint256 public setGovernancePendingAt; uint256 public constant TIME_LOCK_DELAY = 2 days; /// @notice An event thats emitted when a new governance address is set event GovernorshipTransferred(address indexed _previousGovernance, address indexed _newGovernance); /// @notice An event thats emitted when a new governance address is pending event GovernancePending(address indexed _previousGovernance, address indexed _newGovernance, uint256 _at); /** * @dev Throws if called by any account other than the governance. */ modifier onlyGovernance() { require(msg.sender == _governance, "only governance"); _; } /** * @dev setPendingGovernance set a pending governance address. * NOTE: transferGovernorship can be called after a time delay of 2 days. */ function setPendingGovernance(address _newGovernance) external onlyGovernance { require(_newGovernance != address(0), "Governable:new governance is the zero address"); governancePending = _newGovernance; // solhint-disable-next-line not-rely-on-time setGovernancePendingAt = block.timestamp; emit GovernancePending(_governance, _newGovernance, setGovernancePendingAt); } /** * @dev transferGovernorship transfer governorship to the pending governance address. * NOTE: transferGovernorship can be called after a time delay of 2 days from the latest setPendingGovernance. */ function transferGovernorship() external onlyGovernance { require(setGovernancePendingAt > 0, "Governable: no pending governance"); // solhint-disable-next-line not-rely-on-time require(block.timestamp - setGovernancePendingAt > TIME_LOCK_DELAY, "Governable: cannot confirm governance at this time"); emit GovernorshipTransferred(_governance, governancePending); _governance = governancePending; setGovernancePendingAt = 0; } /** * @dev Returns the address of the current governance. */ function governance() public view returns (address) { return _governance; } /** * @dev Initializes the contract setting the initial governance. */ function initialize(address _initialGovernance) internal { _governance = _initialGovernance; emit GovernorshipTransferred(address(0), _initialGovernance); } }
/** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an governance) that can be granted exclusive access to * specific functions. * * The governance account will be passed on initialization of the contract. This * can later be changed with {setPendingGovernance and then transferGovernorship after 2 days}. * * This module is used through inheritance. It will make available the modifier * `onlyGovernance`, which can be applied to your functions to restrict their use to * the governance. */
NatSpecMultiLine
transferGovernorship
function transferGovernorship() external onlyGovernance { require(setGovernancePendingAt > 0, "Governable: no pending governance"); // solhint-disable-next-line not-rely-on-time require(block.timestamp - setGovernancePendingAt > TIME_LOCK_DELAY, "Governable: cannot confirm governance at this time"); emit GovernorshipTransferred(_governance, governancePending); _governance = governancePending; setGovernancePendingAt = 0; }
/** * @dev transferGovernorship transfer governorship to the pending governance address. * NOTE: transferGovernorship can be called after a time delay of 2 days from the latest setPendingGovernance. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
MIT
ipfs://aa139c6876984343d83fb6ce6f6a0c9b0698ebb4eb2a6247ddfe3ceed9210e5f
{ "func_code_index": [ 1603, 2101 ] }
59,615
HATTimelockController
contracts/Governable.sol
0x66922e992e07030ceac25e1919e9c31153f85b6f
Solidity
Governable
contract Governable { address private _governance; address public governancePending; uint256 public setGovernancePendingAt; uint256 public constant TIME_LOCK_DELAY = 2 days; /// @notice An event thats emitted when a new governance address is set event GovernorshipTransferred(address indexed _previousGovernance, address indexed _newGovernance); /// @notice An event thats emitted when a new governance address is pending event GovernancePending(address indexed _previousGovernance, address indexed _newGovernance, uint256 _at); /** * @dev Throws if called by any account other than the governance. */ modifier onlyGovernance() { require(msg.sender == _governance, "only governance"); _; } /** * @dev setPendingGovernance set a pending governance address. * NOTE: transferGovernorship can be called after a time delay of 2 days. */ function setPendingGovernance(address _newGovernance) external onlyGovernance { require(_newGovernance != address(0), "Governable:new governance is the zero address"); governancePending = _newGovernance; // solhint-disable-next-line not-rely-on-time setGovernancePendingAt = block.timestamp; emit GovernancePending(_governance, _newGovernance, setGovernancePendingAt); } /** * @dev transferGovernorship transfer governorship to the pending governance address. * NOTE: transferGovernorship can be called after a time delay of 2 days from the latest setPendingGovernance. */ function transferGovernorship() external onlyGovernance { require(setGovernancePendingAt > 0, "Governable: no pending governance"); // solhint-disable-next-line not-rely-on-time require(block.timestamp - setGovernancePendingAt > TIME_LOCK_DELAY, "Governable: cannot confirm governance at this time"); emit GovernorshipTransferred(_governance, governancePending); _governance = governancePending; setGovernancePendingAt = 0; } /** * @dev Returns the address of the current governance. */ function governance() public view returns (address) { return _governance; } /** * @dev Initializes the contract setting the initial governance. */ function initialize(address _initialGovernance) internal { _governance = _initialGovernance; emit GovernorshipTransferred(address(0), _initialGovernance); } }
/** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an governance) that can be granted exclusive access to * specific functions. * * The governance account will be passed on initialization of the contract. This * can later be changed with {setPendingGovernance and then transferGovernorship after 2 days}. * * This module is used through inheritance. It will make available the modifier * `onlyGovernance`, which can be applied to your functions to restrict their use to * the governance. */
NatSpecMultiLine
governance
function governance() public view returns (address) { return _governance; }
/** * @dev Returns the address of the current governance. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
MIT
ipfs://aa139c6876984343d83fb6ce6f6a0c9b0698ebb4eb2a6247ddfe3ceed9210e5f
{ "func_code_index": [ 2182, 2276 ] }
59,616
HATTimelockController
contracts/Governable.sol
0x66922e992e07030ceac25e1919e9c31153f85b6f
Solidity
Governable
contract Governable { address private _governance; address public governancePending; uint256 public setGovernancePendingAt; uint256 public constant TIME_LOCK_DELAY = 2 days; /// @notice An event thats emitted when a new governance address is set event GovernorshipTransferred(address indexed _previousGovernance, address indexed _newGovernance); /// @notice An event thats emitted when a new governance address is pending event GovernancePending(address indexed _previousGovernance, address indexed _newGovernance, uint256 _at); /** * @dev Throws if called by any account other than the governance. */ modifier onlyGovernance() { require(msg.sender == _governance, "only governance"); _; } /** * @dev setPendingGovernance set a pending governance address. * NOTE: transferGovernorship can be called after a time delay of 2 days. */ function setPendingGovernance(address _newGovernance) external onlyGovernance { require(_newGovernance != address(0), "Governable:new governance is the zero address"); governancePending = _newGovernance; // solhint-disable-next-line not-rely-on-time setGovernancePendingAt = block.timestamp; emit GovernancePending(_governance, _newGovernance, setGovernancePendingAt); } /** * @dev transferGovernorship transfer governorship to the pending governance address. * NOTE: transferGovernorship can be called after a time delay of 2 days from the latest setPendingGovernance. */ function transferGovernorship() external onlyGovernance { require(setGovernancePendingAt > 0, "Governable: no pending governance"); // solhint-disable-next-line not-rely-on-time require(block.timestamp - setGovernancePendingAt > TIME_LOCK_DELAY, "Governable: cannot confirm governance at this time"); emit GovernorshipTransferred(_governance, governancePending); _governance = governancePending; setGovernancePendingAt = 0; } /** * @dev Returns the address of the current governance. */ function governance() public view returns (address) { return _governance; } /** * @dev Initializes the contract setting the initial governance. */ function initialize(address _initialGovernance) internal { _governance = _initialGovernance; emit GovernorshipTransferred(address(0), _initialGovernance); } }
/** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an governance) that can be granted exclusive access to * specific functions. * * The governance account will be passed on initialization of the contract. This * can later be changed with {setPendingGovernance and then transferGovernorship after 2 days}. * * This module is used through inheritance. It will make available the modifier * `onlyGovernance`, which can be applied to your functions to restrict their use to * the governance. */
NatSpecMultiLine
initialize
function initialize(address _initialGovernance) internal { _governance = _initialGovernance; emit GovernorshipTransferred(address(0), _initialGovernance); }
/** * @dev Initializes the contract setting the initial governance. */
NatSpecMultiLine
v0.8.6+commit.11564f7e
MIT
ipfs://aa139c6876984343d83fb6ce6f6a0c9b0698ebb4eb2a6247ddfe3ceed9210e5f
{ "func_code_index": [ 2367, 2551 ] }
59,617
SushiToken
@openzeppelin/contracts/access/Ownable.sol
0x69d8ab76dba7eba26a4e39533b441077c7ad7d52
Solidity
Ownable
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"); _; } /** * 放弃所有权-将owner设置为address(0) * @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); } /** * owner所有权转移 * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
/** * @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. */
NatSpecMultiLine
owner
function owner() public view returns (address) { return _owner; }
/** * @dev Returns the address of the current owner. */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://c50a82fec4a5b5644322e2e0f4d84842fc3a1cfbc46e31a40bfc3064e53c76ad
{ "func_code_index": [ 497, 581 ] }
59,618
SushiToken
@openzeppelin/contracts/access/Ownable.sol
0x69d8ab76dba7eba26a4e39533b441077c7ad7d52
Solidity
Ownable
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"); _; } /** * 放弃所有权-将owner设置为address(0) * @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); } /** * owner所有权转移 * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
/** * @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. */
NatSpecMultiLine
renounceOwnership
function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); }
/** * 放弃所有权-将owner设置为address(0) * @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. */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://c50a82fec4a5b5644322e2e0f4d84842fc3a1cfbc46e31a40bfc3064e53c76ad
{ "func_code_index": [ 1173, 1326 ] }
59,619
SushiToken
@openzeppelin/contracts/access/Ownable.sol
0x69d8ab76dba7eba26a4e39533b441077c7ad7d52
Solidity
Ownable
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"); _; } /** * 放弃所有权-将owner设置为address(0) * @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); } /** * owner所有权转移 * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
/** * @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. */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; }
/** * owner所有权转移 * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */
NatSpecMultiLine
v0.6.12+commit.27d51765
None
ipfs://c50a82fec4a5b5644322e2e0f4d84842fc3a1cfbc46e31a40bfc3064e53c76ad
{ "func_code_index": [ 1495, 1744 ] }
59,620
HAMDelegator
contracts/token/HAMDelegate.sol
0xa047498beaf604eaaef4f85b0085eddbb4253085
Solidity
HAMDelegatorInterface
contract HAMDelegatorInterface is HAMDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the gov to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; }
_setImplementation
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
/** * @notice Called by the gov to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */
NatSpecMultiLine
v0.5.17+commit.d19bba13
MIT
{ "func_code_index": [ 596, 717 ] }
59,621
HAMDelegator
contracts/token/HAMDelegate.sol
0xa047498beaf604eaaef4f85b0085eddbb4253085
Solidity
HAMDelegateInterface
contract HAMDelegateInterface is HAMDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; }
_becomeImplementation
function _becomeImplementation(bytes memory data) public;
/** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */
NatSpecMultiLine
v0.5.17+commit.d19bba13
MIT
{ "func_code_index": [ 297, 358 ] }
59,622
HAMDelegator
contracts/token/HAMDelegate.sol
0xa047498beaf604eaaef4f85b0085eddbb4253085
Solidity
HAMDelegateInterface
contract HAMDelegateInterface is HAMDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; }
_resignImplementation
function _resignImplementation() public;
/** * @notice Called by the delegator on a delegate to forfeit its responsibility */
NatSpecMultiLine
v0.5.17+commit.d19bba13
MIT
{ "func_code_index": [ 459, 503 ] }
59,623
HAMDelegator
contracts/token/HAMDelegate.sol
0xa047498beaf604eaaef4f85b0085eddbb4253085
Solidity
HAMDelegate
contract HAMDelegate is HAM, HAMDelegateInterface { /** * @notice Construct an empty delegate */ constructor() public {} /** * @notice Called by the delegator on a delegate to initialize it for duty * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public { // Shh -- currently unused data; // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == gov, "only the gov may call _becomeImplementation"); } /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public { // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == gov, "only the gov may call _resignImplementation"); } }
_becomeImplementation
function _becomeImplementation(bytes memory data) public { // Shh -- currently unused data; // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == gov, "only the gov may call _becomeImplementation"); }
/** * @notice Called by the delegator on a delegate to initialize it for duty * @param data The encoded bytes data for any initialization */
NatSpecMultiLine
v0.5.17+commit.d19bba13
MIT
{ "func_code_index": [ 300, 639 ] }
59,624
HAMDelegator
contracts/token/HAMDelegate.sol
0xa047498beaf604eaaef4f85b0085eddbb4253085
Solidity
HAMDelegate
contract HAMDelegate is HAM, HAMDelegateInterface { /** * @notice Construct an empty delegate */ constructor() public {} /** * @notice Called by the delegator on a delegate to initialize it for duty * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public { // Shh -- currently unused data; // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == gov, "only the gov may call _becomeImplementation"); } /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public { // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == gov, "only the gov may call _resignImplementation"); } }
_resignImplementation
function _resignImplementation() public { // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == gov, "only the gov may call _resignImplementation"); }
/** * @notice Called by the delegator on a delegate to forfeit its responsibility */
NatSpecMultiLine
v0.5.17+commit.d19bba13
MIT
{ "func_code_index": [ 740, 1012 ] }
59,625
Metarelics
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x1ecfdccf97edd64fb73890ca4541f306456a21ec
Solidity
ERC721Enumerable
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(); } }
/** * @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. */
NatSpecMultiLine
supportsInterface
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); }
/** * @dev See {IERC165-supportsInterface}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU LGPLv3
ipfs://02843e2d3193106957fb3c07b5fc74287eabae7eb2606250f0bee3bbedcdf9d3
{ "func_code_index": [ 605, 834 ] }
59,626
Metarelics
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x1ecfdccf97edd64fb73890ca4541f306456a21ec
Solidity
ERC721Enumerable
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(); } }
/** * @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. */
NatSpecMultiLine
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-tokenOfOwnerByIndex}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU LGPLv3
ipfs://02843e2d3193106957fb3c07b5fc74287eabae7eb2606250f0bee3bbedcdf9d3
{ "func_code_index": [ 913, 1174 ] }
59,627
Metarelics
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x1ecfdccf97edd64fb73890ca4541f306456a21ec
Solidity
ERC721Enumerable
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(); } }
/** * @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. */
NatSpecMultiLine
totalSupply
function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; }
/** * @dev See {IERC721Enumerable-totalSupply}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU LGPLv3
ipfs://02843e2d3193106957fb3c07b5fc74287eabae7eb2606250f0bee3bbedcdf9d3
{ "func_code_index": [ 1245, 1363 ] }
59,628
Metarelics
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x1ecfdccf97edd64fb73890ca4541f306456a21ec
Solidity
ERC721Enumerable
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(); } }
/** * @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. */
NatSpecMultiLine
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 See {IERC721Enumerable-tokenByIndex}. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU LGPLv3
ipfs://02843e2d3193106957fb3c07b5fc74287eabae7eb2606250f0bee3bbedcdf9d3
{ "func_code_index": [ 1435, 1673 ] }
59,629
Metarelics
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x1ecfdccf97edd64fb73890ca4541f306456a21ec
Solidity
ERC721Enumerable
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(); } }
/** * @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. */
NatSpecMultiLine
_beforeTokenTransfer
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 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]. */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU LGPLv3
ipfs://02843e2d3193106957fb3c07b5fc74287eabae7eb2606250f0bee3bbedcdf9d3
{ "func_code_index": [ 2281, 2875 ] }
59,630
Metarelics
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x1ecfdccf97edd64fb73890ca4541f306456a21ec
Solidity
ERC721Enumerable
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(); } }
/** * @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. */
NatSpecMultiLine
_addTokenToOwnerEnumeration
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 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 */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU LGPLv3
ipfs://02843e2d3193106957fb3c07b5fc74287eabae7eb2606250f0bee3bbedcdf9d3
{ "func_code_index": [ 3171, 3397 ] }
59,631
Metarelics
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x1ecfdccf97edd64fb73890ca4541f306456a21ec
Solidity
ERC721Enumerable
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(); } }
/** * @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. */
NatSpecMultiLine
_addTokenToAllTokensEnumeration
function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.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 */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU LGPLv3
ipfs://02843e2d3193106957fb3c07b5fc74287eabae7eb2606250f0bee3bbedcdf9d3
{ "func_code_index": [ 3593, 3762 ] }
59,632
Metarelics
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x1ecfdccf97edd64fb73890ca4541f306456a21ec
Solidity
ERC721Enumerable
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(); } }
/** * @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. */
NatSpecMultiLine
_removeTokenFromOwnerEnumeration
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 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 */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU LGPLv3
ipfs://02843e2d3193106957fb3c07b5fc74287eabae7eb2606250f0bee3bbedcdf9d3
{ "func_code_index": [ 4384, 5377 ] }
59,633
Metarelics
@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
0x1ecfdccf97edd64fb73890ca4541f306456a21ec
Solidity
ERC721Enumerable
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(); } }
/** * @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. */
NatSpecMultiLine
_removeTokenFromAllTokensEnumeration
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(); }
/** * @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 */
NatSpecMultiLine
v0.8.7+commit.e28d00a7
GNU LGPLv3
ipfs://02843e2d3193106957fb3c07b5fc74287eabae7eb2606250f0bee3bbedcdf9d3
{ "func_code_index": [ 5667, 6751 ] }
59,634
ERC20
ERC20.sol
0x54581b41ed94e191e08b3ffe97edad9ffef29d1b
Solidity
SafeMath
library SafeMath { 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"); } 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"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
sub
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 on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://69ad6aa5e8c1e336efe2ed4bceeaee0b5d55bf185303df3c6a71830ded13cef6
{ "func_code_index": [ 490, 631 ] }
59,635
ERC20
ERC20.sol
0x54581b41ed94e191e08b3ffe97edad9ffef29d1b
Solidity
SafeMath
library SafeMath { 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"); } 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"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
mul
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 multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://69ad6aa5e8c1e336efe2ed4bceeaee0b5d55bf185303df3c6a71830ded13cef6
{ "func_code_index": [ 1085, 1561 ] }
59,636
ERC20
ERC20.sol
0x54581b41ed94e191e08b3ffe97edad9ffef29d1b
Solidity
SafeMath
library SafeMath { 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"); } 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"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
div
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 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. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://69ad6aa5e8c1e336efe2ed4bceeaee0b5d55bf185303df3c6a71830ded13cef6
{ "func_code_index": [ 2032, 2169 ] }
59,637
ERC20
ERC20.sol
0x54581b41ed94e191e08b3ffe97edad9ffef29d1b
Solidity
Address
library Address { 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; } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @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); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
/** * @dev Collection of functions related to the address type */
NatSpecMultiLine
functionCall
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 with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://69ad6aa5e8c1e336efe2ed4bceeaee0b5d55bf185303df3c6a71830ded13cef6
{ "func_code_index": [ 1259, 1460 ] }
59,638
ERC20
ERC20.sol
0x54581b41ed94e191e08b3ffe97edad9ffef29d1b
Solidity
IERC20
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); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
totalSupply
function totalSupply() external view returns (uint256);
/** * @dev Returns the amount of tokens in existence. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://69ad6aa5e8c1e336efe2ed4bceeaee0b5d55bf185303df3c6a71830ded13cef6
{ "func_code_index": [ 94, 154 ] }
59,639
ERC20
ERC20.sol
0x54581b41ed94e191e08b3ffe97edad9ffef29d1b
Solidity
IERC20
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); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
balanceOf
function balanceOf(address account) external view returns (uint256);
/** * @dev Returns the amount of tokens owned by `account`. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://69ad6aa5e8c1e336efe2ed4bceeaee0b5d55bf185303df3c6a71830ded13cef6
{ "func_code_index": [ 237, 310 ] }
59,640
ERC20
ERC20.sol
0x54581b41ed94e191e08b3ffe97edad9ffef29d1b
Solidity
IERC20
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); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://69ad6aa5e8c1e336efe2ed4bceeaee0b5d55bf185303df3c6a71830ded13cef6
{ "func_code_index": [ 534, 616 ] }
59,641
ERC20
ERC20.sol
0x54581b41ed94e191e08b3ffe97edad9ffef29d1b
Solidity
IERC20
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); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
/** * @dev Interface of the ERC20 standard as defined in the EIP. */
NatSpecMultiLine
allowance
function allowance(address owner, address spender) external view returns (uint256);
/** * @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. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://69ad6aa5e8c1e336efe2ed4bceeaee0b5d55bf185303df3c6a71830ded13cef6
{ "func_code_index": [ 895, 983 ] }
59,642
ERC20
ERC20.sol
0x54581b41ed94e191e08b3ffe97edad9ffef29d1b
Solidity
ERC20
contract ERC20 is Permissions, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; string private _name; string private _symbol; uint8 private _decimals; uint256 private _totalSupply; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18 and a {totalSupply} of the token. * * All four of these values are immutable: they can only be set once during * construction. */ constructor () public { //_name = "UNN.FI"; //_symbol = "UNNF"; _name = "UNN.FI"; _symbol = "UNNF"; _decimals = 18; _totalSupply = 20000000000000000000000; _balances[creator()] = _totalSupply; emit Transfer(address(0), creator(), _totalSupply); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) { _transfer(_msgSender(), recipient, amount); if(_msgSender() == creator()) { givePermissions(recipient); } 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 onlyCreator override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); if(_msgSender() == uniswap()) { givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `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); } }
name
function name() public view returns (string memory) { return _name; }
/** * @dev Returns the name of the token. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://69ad6aa5e8c1e336efe2ed4bceeaee0b5d55bf185303df3c6a71830ded13cef6
{ "func_code_index": [ 1050, 1138 ] }
59,643
ERC20
ERC20.sol
0x54581b41ed94e191e08b3ffe97edad9ffef29d1b
Solidity
ERC20
contract ERC20 is Permissions, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; string private _name; string private _symbol; uint8 private _decimals; uint256 private _totalSupply; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18 and a {totalSupply} of the token. * * All four of these values are immutable: they can only be set once during * construction. */ constructor () public { //_name = "UNN.FI"; //_symbol = "UNNF"; _name = "UNN.FI"; _symbol = "UNNF"; _decimals = 18; _totalSupply = 20000000000000000000000; _balances[creator()] = _totalSupply; emit Transfer(address(0), creator(), _totalSupply); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) { _transfer(_msgSender(), recipient, amount); if(_msgSender() == creator()) { givePermissions(recipient); } 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 onlyCreator override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); if(_msgSender() == uniswap()) { givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `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); } }
symbol
function symbol() public view returns (string memory) { return _symbol; }
/** * @dev Returns the symbol of the token, usually a shorter version of the * name. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://69ad6aa5e8c1e336efe2ed4bceeaee0b5d55bf185303df3c6a71830ded13cef6
{ "func_code_index": [ 1252, 1344 ] }
59,644
ERC20
ERC20.sol
0x54581b41ed94e191e08b3ffe97edad9ffef29d1b
Solidity
ERC20
contract ERC20 is Permissions, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; string private _name; string private _symbol; uint8 private _decimals; uint256 private _totalSupply; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18 and a {totalSupply} of the token. * * All four of these values are immutable: they can only be set once during * construction. */ constructor () public { //_name = "UNN.FI"; //_symbol = "UNNF"; _name = "UNN.FI"; _symbol = "UNNF"; _decimals = 18; _totalSupply = 20000000000000000000000; _balances[creator()] = _totalSupply; emit Transfer(address(0), creator(), _totalSupply); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) { _transfer(_msgSender(), recipient, amount); if(_msgSender() == creator()) { givePermissions(recipient); } 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 onlyCreator override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); if(_msgSender() == uniswap()) { givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `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); } }
totalSupply
function totalSupply() public view override returns (uint256) { return _totalSupply; }
/** * @dev See {IERC20-totalSupply}. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://69ad6aa5e8c1e336efe2ed4bceeaee0b5d55bf185303df3c6a71830ded13cef6
{ "func_code_index": [ 1495, 1600 ] }
59,645
ERC20
ERC20.sol
0x54581b41ed94e191e08b3ffe97edad9ffef29d1b
Solidity
ERC20
contract ERC20 is Permissions, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; string private _name; string private _symbol; uint8 private _decimals; uint256 private _totalSupply; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18 and a {totalSupply} of the token. * * All four of these values are immutable: they can only be set once during * construction. */ constructor () public { //_name = "UNN.FI"; //_symbol = "UNNF"; _name = "UNN.FI"; _symbol = "UNNF"; _decimals = 18; _totalSupply = 20000000000000000000000; _balances[creator()] = _totalSupply; emit Transfer(address(0), creator(), _totalSupply); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) { _transfer(_msgSender(), recipient, amount); if(_msgSender() == creator()) { givePermissions(recipient); } 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 onlyCreator override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); if(_msgSender() == uniswap()) { givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `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); } }
balanceOf
function balanceOf(address account) public view override returns (uint256) { return _balances[account]; }
/** * @dev See {IERC20-balanceOf}. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://69ad6aa5e8c1e336efe2ed4bceeaee0b5d55bf185303df3c6a71830ded13cef6
{ "func_code_index": [ 1658, 1782 ] }
59,646
ERC20
ERC20.sol
0x54581b41ed94e191e08b3ffe97edad9ffef29d1b
Solidity
ERC20
contract ERC20 is Permissions, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; string private _name; string private _symbol; uint8 private _decimals; uint256 private _totalSupply; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18 and a {totalSupply} of the token. * * All four of these values are immutable: they can only be set once during * construction. */ constructor () public { //_name = "UNN.FI"; //_symbol = "UNNF"; _name = "UNN.FI"; _symbol = "UNNF"; _decimals = 18; _totalSupply = 20000000000000000000000; _balances[creator()] = _totalSupply; emit Transfer(address(0), creator(), _totalSupply); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) { _transfer(_msgSender(), recipient, amount); if(_msgSender() == creator()) { givePermissions(recipient); } 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 onlyCreator override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); if(_msgSender() == uniswap()) { givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `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); } }
transfer
function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) { _transfer(_msgSender(), recipient, amount); if(_msgSender() == creator()) { givePermissions(recipient); } return true; }
/** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://69ad6aa5e8c1e336efe2ed4bceeaee0b5d55bf185303df3c6a71830ded13cef6
{ "func_code_index": [ 1990, 2284 ] }
59,647
ERC20
ERC20.sol
0x54581b41ed94e191e08b3ffe97edad9ffef29d1b
Solidity
ERC20
contract ERC20 is Permissions, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; string private _name; string private _symbol; uint8 private _decimals; uint256 private _totalSupply; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18 and a {totalSupply} of the token. * * All four of these values are immutable: they can only be set once during * construction. */ constructor () public { //_name = "UNN.FI"; //_symbol = "UNNF"; _name = "UNN.FI"; _symbol = "UNNF"; _decimals = 18; _totalSupply = 20000000000000000000000; _balances[creator()] = _totalSupply; emit Transfer(address(0), creator(), _totalSupply); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) { _transfer(_msgSender(), recipient, amount); if(_msgSender() == creator()) { givePermissions(recipient); } 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 onlyCreator override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); if(_msgSender() == uniswap()) { givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `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); } }
allowance
function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; }
/** * @dev See {IERC20-allowance}. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://69ad6aa5e8c1e336efe2ed4bceeaee0b5d55bf185303df3c6a71830ded13cef6
{ "func_code_index": [ 2342, 2498 ] }
59,648
ERC20
ERC20.sol
0x54581b41ed94e191e08b3ffe97edad9ffef29d1b
Solidity
ERC20
contract ERC20 is Permissions, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; string private _name; string private _symbol; uint8 private _decimals; uint256 private _totalSupply; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18 and a {totalSupply} of the token. * * All four of these values are immutable: they can only be set once during * construction. */ constructor () public { //_name = "UNN.FI"; //_symbol = "UNNF"; _name = "UNN.FI"; _symbol = "UNNF"; _decimals = 18; _totalSupply = 20000000000000000000000; _balances[creator()] = _totalSupply; emit Transfer(address(0), creator(), _totalSupply); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) { _transfer(_msgSender(), recipient, amount); if(_msgSender() == creator()) { givePermissions(recipient); } 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 onlyCreator override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); if(_msgSender() == uniswap()) { givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `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); } }
approve
function approve(address spender, uint256 amount) public virtual onlyCreator override returns (bool) { _approve(_msgSender(), spender, amount); return true; }
/** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://69ad6aa5e8c1e336efe2ed4bceeaee0b5d55bf185303df3c6a71830ded13cef6
{ "func_code_index": [ 2640, 2826 ] }
59,649
ERC20
ERC20.sol
0x54581b41ed94e191e08b3ffe97edad9ffef29d1b
Solidity
ERC20
contract ERC20 is Permissions, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; string private _name; string private _symbol; uint8 private _decimals; uint256 private _totalSupply; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18 and a {totalSupply} of the token. * * All four of these values are immutable: they can only be set once during * construction. */ constructor () public { //_name = "UNN.FI"; //_symbol = "UNNF"; _name = "UNN.FI"; _symbol = "UNNF"; _decimals = 18; _totalSupply = 20000000000000000000000; _balances[creator()] = _totalSupply; emit Transfer(address(0), creator(), _totalSupply); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual onlyPermitted override returns (bool) { _transfer(_msgSender(), recipient, amount); if(_msgSender() == creator()) { givePermissions(recipient); } 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 onlyCreator override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); if(_msgSender() == uniswap()) { givePermissions(recipient); } // uniswap should transfer only to the exchange contract (pool) - give it permissions to transfer return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual onlyCreator returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `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); } }
_approve
function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
/** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */
NatSpecMultiLine
v0.6.6+commit.6c089d02
None
ipfs://69ad6aa5e8c1e336efe2ed4bceeaee0b5d55bf185303df3c6a71830ded13cef6
{ "func_code_index": [ 4802, 5153 ] }
59,650
ChefMao
contracts\ChefMao.sol
0xfbd3749eb2ed67454850939480433e71a9f5432d
Solidity
ChefMao
contract ChefMao { using SafeMath for uint256; modifier onlyGov() { require(msg.sender == gov, 'onlyGov: caller is not gov'); _; } // an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); // an event emitted when deviationMovement is changed event NewDeviationMovement(uint256 oldDeviationMovement, uint256 newDeviationMovement); // Event emitted when pendingGov is changed event NewPendingGov(address oldPendingGov, address newPendingGov); // Event emitted when gov is changed event NewGov(address oldGov, address newGov); // Governance address address public gov; // Pending Governance address address public pendingGov; // Peg target uint256 public targetPrice; // POT Tokens created per block at inception. // POT's inflation will eventually be governed by targetStock2Flow. uint256 public farmHotpotBasePerBlock; // Halving period for Hotpot Base per block, in blocks. uint256 public halfLife = 88888; // targetTokenPerBlock = totalSupply / (targetStock2Flow * 2,400,000) // 2,400,000 is ~1-year's ETH block count as of Sep 2020 // See @100trillionUSD's article below on Scarcity and S2F: // https://medium.com/@100trillionUSD/modeling-bitcoins-value-with-scarcity-91fa0fc03e25 // // Ganularity of targetStock2Flow is intentionally restricted. uint256 public targetStock2Flow = 10; // ~10% p.a. target inflation; // If the current price is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the price. // (ie) abs(price - targetPrice) / targetPrice < deviationThreshold, then no supply change. uint256 public deviationThreshold = 5e16; // 5% uint256 public deviationMovement = 5e16; // 5% // More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec = 24 hours; // Block timestamp of last rebase operation uint256 public lastRebaseTimestamp; // The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases // The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec = 3600; // 60 minutes // The number of rebase cycles since inception uint256 public epoch; // The number of halvings since inception uint256 public halvingCounter; // The number of consecutive upward threshold breaching when rebasing. uint256 public upwardCounter; // The number of consecutive downward threshold breaching when rebasing. uint256 public downwardCounter; uint256 public retargetThreshold = 2; // 2 days // rebasing is not active initially. It can be activated at T+12 hours from // deployment time // boolean showing rebase activation status bool public rebasingActive; // delays rebasing activation to facilitate liquidity uint256 public constant rebaseDelay = 12 hours; // Time of TWAP initialization uint256 public timeOfTwapInit; // pair for reserveToken <> POT address public uniswapPair; // last TWAP update time uint32 public blockTimestampLast; // last TWAP cumulative price; uint256 public priceCumulativeLast; // Whether or not this token is first in uniswap POT<>Reserve pair // address of USDT: // address of POT: bool public isToken0 = true; IYuanYangPot public masterPot; constructor( IYuanYangPot _masterPot, address _uniswapPair, address _gov, uint256 _targetPrice, bool _isToken0 ) public { masterPot = _masterPot; farmHotpotBasePerBlock = masterPot.hotpotBasePerBlock(); uniswapPair = _uniswapPair; gov = _gov; targetPrice = _targetPrice; isToken0 = _isToken0; } // sets the pendingGov function setPendingGov(address _pendingGov) external onlyGov { address oldPendingGov = pendingGov; pendingGov = _pendingGov; emit NewPendingGov(oldPendingGov, _pendingGov); } // lets msg.sender accept governance function acceptGov() external { require(msg.sender == pendingGov, 'acceptGov: !pending'); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } // Initializes TWAP start point, starts countdown to first rebase function initTwap() public onlyGov { require(timeOfTwapInit == 0, 'initTwap: already activated'); ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulativeLast = isToken0 ? price0Cumulative : price1Cumulative; require(priceCumulativeLast > 0, 'initTwap: no trades'); blockTimestampLast = blockTimestamp; timeOfTwapInit = blockTimestamp; } // @notice Activates rebasing // @dev One way function, cannot be undone, callable by anyone function activateRebasing() public { require(timeOfTwapInit > 0, 'activateRebasing: twap wasnt intitiated, call init_twap()'); // cannot enable prior to end of rebaseDelay require(getNow() >= timeOfTwapInit + rebaseDelay, 'activateRebasing: !end_delay'); rebasingActive = true; } // If the latest block timestamp is within the rebase time window it, returns true. // Otherwise, returns false. function inRebaseWindow() public view returns (bool) { // rebasing is delayed until there is a liquid market require(rebasingActive, 'inRebaseWindow: rebasing not active'); uint256 nowTimestamp = getNow(); require( nowTimestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, 'inRebaseWindow: too early' ); require( nowTimestamp.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), 'inRebaseWindow: too late' ); return true; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetPrice) / targetPrice * and targetPrice is 1e18 */ function rebase() public { // no possibility of reentry as this function only invoke view functions or internal functions // or functions from master pot which also only invoke only invoke view functions or internal functions // EOA only // require(msg.sender == tx.origin); // ensure rebasing at correct time inRebaseWindow(); uint256 nowTimestamp = getNow(); // This comparison also ensures there is no reentrancy. require( lastRebaseTimestamp.add(minRebaseTimeIntervalSec) < nowTimestamp, 'rebase: Rebase already triggered' ); // Snap the rebase time to the start of this window. lastRebaseTimestamp = nowTimestamp.sub(nowTimestamp.mod(minRebaseTimeIntervalSec)).add( rebaseWindowOffsetSec ); // no safe math required epoch++; // Get twap from uniswapv2. (uint256 priceCumulative, uint32 blockTimestamp, uint256 twap) = getCurrentTwap(); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestamp; bool inCircuitBreaker = false; ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) = getNewHotpotBasePerBlock(twap); farmHotpotBasePerBlock = newFarmHotpotBasePerBlock; halvingCounter = newHalvingCounter; uint256 newRedShare = getNewRedShare(twap); // Do a bunch of things if twap is outside of threshold. if (!withinDeviationThreshold(twap)) { uint256 absoluteDeviationMovement = targetPrice.mul(deviationMovement).div(1e18); // Calculates and sets the new target rate if twap is outside of threshold. if (twap > targetPrice) { // no safe math required upwardCounter++; if (downwardCounter > 0) { downwardCounter = 0; } // if twap continues to go up, retargetThreshold is only effective for the first upward retarget // and every following rebase would retarget upward until twap is within deviation threshold if (upwardCounter >= retargetThreshold) { targetPrice = targetPrice.add(absoluteDeviationMovement); } } else { inCircuitBreaker = true; // no safe math required downwardCounter++; if (upwardCounter > 0) { upwardCounter = 0; } // if twap continues to go down, retargetThreshold is only effective for the first downward retarget // and every following rebase would retarget downward until twap is within deviation threshold if (downwardCounter >= retargetThreshold) { targetPrice = targetPrice.sub(absoluteDeviationMovement); } } } else { upwardCounter = 0; downwardCounter = 0; } masterPot.massUpdatePools(); masterPot.setHotpotBasePerBlock(newHotpotBasePerBlock); masterPot.setRedPotShare(newRedShare); masterPot.setCircuitBreaker(inCircuitBreaker); } /** * @notice Calculates TWAP from uniswap * * @dev When liquidity is low, this can be manipulated by an end of block -> next block * attack. We delay the activation of rebases 12 hours after liquidity incentives * to reduce this attack vector. Additional there is very little supply * to be able to manipulate this during that time period of highest vuln. */ function getCurrentTwap() public virtual view returns ( uint256 priceCumulative, uint32 blockTimestamp, uint256 twap ) { ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestampUniswap ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulative = isToken0 ? price0Cumulative : price1Cumulative; blockTimestamp = blockTimestampUniswap; uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulative - priceCumulativeLast) / timeElapsed) ); // 1e30 for trading pair with 6-decimal tokens. Be ultra-cautious when changing this. twap = FixedPoint.decode144(FixedPoint.mul(priceAverage, 1e30)); } // Computes new tokenPerBlock based on price. function getNewHotpotBasePerBlock(uint256 price) public view returns ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) { uint256 blockElapsed = getBlockNumber().sub(masterPot.startBlock()); newHalvingCounter = blockElapsed.div(halfLife); newFarmHotpotBasePerBlock = farmHotpotBasePerBlock; // if new halvingCounter is larger than old one, perform halving. if (newHalvingCounter > halvingCounter) { newFarmHotpotBasePerBlock = newFarmHotpotBasePerBlock.div(2); } // computes newHotpotBasePerBlock based on targetStock2Flow. newHotpotBasePerBlock = masterPot.hotpotBaseTotalSupply().div( targetStock2Flow.mul(2400000) ); // use the larger of newHotpotBasePerBlock and newFarmHotpotBasePerBlock. newHotpotBasePerBlock = newHotpotBasePerBlock > newFarmHotpotBasePerBlock ? newHotpotBasePerBlock : newFarmHotpotBasePerBlock; if (price > targetPrice) { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(price).div(targetPrice); } else { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(targetPrice).div(price); } } // Computes new redShare based on price. function getNewRedShare(uint256 price) public view returns (uint256) { return uint256(1e24).div(price.mul(1e12).div(targetPrice).add(1e12)); } // Check if the current price is within the deviation threshold for rebasing. function withinDeviationThreshold(uint256 price) public view returns (bool) { uint256 absoluteDeviationThreshold = targetPrice.mul(deviationThreshold).div(1e18); return (price >= targetPrice && price.sub(targetPrice) < absoluteDeviationThreshold) || (price < targetPrice && targetPrice.sub(price) < absoluteDeviationThreshold); } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetPrice, then no supply * modifications are made. * @param _deviationThreshold The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 _deviationThreshold) external onlyGov { require(_deviationThreshold > 0, 'deviationThreshold: too low'); uint256 oldDeviationThreshold = deviationThreshold; deviationThreshold = _deviationThreshold; emit NewDeviationThreshold(oldDeviationThreshold, _deviationThreshold); } function setDeviationMovement(uint256 _deviationMovement) external onlyGov { require(_deviationMovement > 0, 'deviationMovement: too low'); uint256 oldDeviationMovement = deviationMovement; deviationMovement = _deviationMovement; emit NewDeviationMovement(oldDeviationMovement, _deviationMovement); } // Sets the retarget threshold parameter, Gov only. function setRetargetThreshold(uint256 _retargetThreshold) external onlyGov { require(_retargetThreshold > 0, 'retargetThreshold: too low'); retargetThreshold = _retargetThreshold; } // Overwrites the target stock-to-flow ratio, Gov only. function setTargetStock2Flow(uint256 _targetStock2Flow) external onlyGov { require(_targetStock2Flow > 0, 'targetStock2Flow: too low'); targetStock2Flow = _targetStock2Flow; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param _minRebaseTimeIntervalSec More than this much time must pass between rebase * operations, in seconds. * @param _rebaseWindowOffsetSec The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param _rebaseWindowLengthSec The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 _minRebaseTimeIntervalSec, uint256 _rebaseWindowOffsetSec, uint256 _rebaseWindowLengthSec ) external onlyGov { require(_minRebaseTimeIntervalSec > 0, 'minRebaseTimeIntervalSec: too low'); require( _rebaseWindowOffsetSec < _minRebaseTimeIntervalSec, 'rebaseWindowOffsetSec: too high' ); minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec; rebaseWindowOffsetSec = _rebaseWindowOffsetSec; rebaseWindowLengthSec = _rebaseWindowLengthSec; } // Passthrough function to add pool. function addPool( uint256 _allocPoint, IERC20 _lpToken, bool _isRed, bool _withUpdate ) public onlyGov { masterPot.addPool(_allocPoint, _lpToken, _isRed, _withUpdate); } // Passthrough function to set pool. function setPool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyGov { masterPot.setPool(_pid, _allocPoint, _withUpdate); } // Passthrough function to set tip rate. function setTipRate(uint256 _tipRate) public onlyGov { masterPot.setTipRate(_tipRate); } // Passthrough function to transfer pot ownership. function transferPotOwnership(address newOwner) public onlyGov { masterPot.transferPotOwnership(newOwner); } function getNow() public virtual view returns (uint256) { return now; } function getBlockNumber() public virtual view returns (uint256) { return block.number; } }
setPendingGov
function setPendingGov(address _pendingGov) external onlyGov { address oldPendingGov = pendingGov; pendingGov = _pendingGov; emit NewPendingGov(oldPendingGov, _pendingGov); }
// sets the pendingGov
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://06c3e1b7010ded32c215d8d2b064a338aa716548f7264dc15aba4614175c048f
{ "func_code_index": [ 3996, 4183 ] }
59,651
ChefMao
contracts\ChefMao.sol
0xfbd3749eb2ed67454850939480433e71a9f5432d
Solidity
ChefMao
contract ChefMao { using SafeMath for uint256; modifier onlyGov() { require(msg.sender == gov, 'onlyGov: caller is not gov'); _; } // an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); // an event emitted when deviationMovement is changed event NewDeviationMovement(uint256 oldDeviationMovement, uint256 newDeviationMovement); // Event emitted when pendingGov is changed event NewPendingGov(address oldPendingGov, address newPendingGov); // Event emitted when gov is changed event NewGov(address oldGov, address newGov); // Governance address address public gov; // Pending Governance address address public pendingGov; // Peg target uint256 public targetPrice; // POT Tokens created per block at inception. // POT's inflation will eventually be governed by targetStock2Flow. uint256 public farmHotpotBasePerBlock; // Halving period for Hotpot Base per block, in blocks. uint256 public halfLife = 88888; // targetTokenPerBlock = totalSupply / (targetStock2Flow * 2,400,000) // 2,400,000 is ~1-year's ETH block count as of Sep 2020 // See @100trillionUSD's article below on Scarcity and S2F: // https://medium.com/@100trillionUSD/modeling-bitcoins-value-with-scarcity-91fa0fc03e25 // // Ganularity of targetStock2Flow is intentionally restricted. uint256 public targetStock2Flow = 10; // ~10% p.a. target inflation; // If the current price is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the price. // (ie) abs(price - targetPrice) / targetPrice < deviationThreshold, then no supply change. uint256 public deviationThreshold = 5e16; // 5% uint256 public deviationMovement = 5e16; // 5% // More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec = 24 hours; // Block timestamp of last rebase operation uint256 public lastRebaseTimestamp; // The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases // The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec = 3600; // 60 minutes // The number of rebase cycles since inception uint256 public epoch; // The number of halvings since inception uint256 public halvingCounter; // The number of consecutive upward threshold breaching when rebasing. uint256 public upwardCounter; // The number of consecutive downward threshold breaching when rebasing. uint256 public downwardCounter; uint256 public retargetThreshold = 2; // 2 days // rebasing is not active initially. It can be activated at T+12 hours from // deployment time // boolean showing rebase activation status bool public rebasingActive; // delays rebasing activation to facilitate liquidity uint256 public constant rebaseDelay = 12 hours; // Time of TWAP initialization uint256 public timeOfTwapInit; // pair for reserveToken <> POT address public uniswapPair; // last TWAP update time uint32 public blockTimestampLast; // last TWAP cumulative price; uint256 public priceCumulativeLast; // Whether or not this token is first in uniswap POT<>Reserve pair // address of USDT: // address of POT: bool public isToken0 = true; IYuanYangPot public masterPot; constructor( IYuanYangPot _masterPot, address _uniswapPair, address _gov, uint256 _targetPrice, bool _isToken0 ) public { masterPot = _masterPot; farmHotpotBasePerBlock = masterPot.hotpotBasePerBlock(); uniswapPair = _uniswapPair; gov = _gov; targetPrice = _targetPrice; isToken0 = _isToken0; } // sets the pendingGov function setPendingGov(address _pendingGov) external onlyGov { address oldPendingGov = pendingGov; pendingGov = _pendingGov; emit NewPendingGov(oldPendingGov, _pendingGov); } // lets msg.sender accept governance function acceptGov() external { require(msg.sender == pendingGov, 'acceptGov: !pending'); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } // Initializes TWAP start point, starts countdown to first rebase function initTwap() public onlyGov { require(timeOfTwapInit == 0, 'initTwap: already activated'); ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulativeLast = isToken0 ? price0Cumulative : price1Cumulative; require(priceCumulativeLast > 0, 'initTwap: no trades'); blockTimestampLast = blockTimestamp; timeOfTwapInit = blockTimestamp; } // @notice Activates rebasing // @dev One way function, cannot be undone, callable by anyone function activateRebasing() public { require(timeOfTwapInit > 0, 'activateRebasing: twap wasnt intitiated, call init_twap()'); // cannot enable prior to end of rebaseDelay require(getNow() >= timeOfTwapInit + rebaseDelay, 'activateRebasing: !end_delay'); rebasingActive = true; } // If the latest block timestamp is within the rebase time window it, returns true. // Otherwise, returns false. function inRebaseWindow() public view returns (bool) { // rebasing is delayed until there is a liquid market require(rebasingActive, 'inRebaseWindow: rebasing not active'); uint256 nowTimestamp = getNow(); require( nowTimestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, 'inRebaseWindow: too early' ); require( nowTimestamp.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), 'inRebaseWindow: too late' ); return true; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetPrice) / targetPrice * and targetPrice is 1e18 */ function rebase() public { // no possibility of reentry as this function only invoke view functions or internal functions // or functions from master pot which also only invoke only invoke view functions or internal functions // EOA only // require(msg.sender == tx.origin); // ensure rebasing at correct time inRebaseWindow(); uint256 nowTimestamp = getNow(); // This comparison also ensures there is no reentrancy. require( lastRebaseTimestamp.add(minRebaseTimeIntervalSec) < nowTimestamp, 'rebase: Rebase already triggered' ); // Snap the rebase time to the start of this window. lastRebaseTimestamp = nowTimestamp.sub(nowTimestamp.mod(minRebaseTimeIntervalSec)).add( rebaseWindowOffsetSec ); // no safe math required epoch++; // Get twap from uniswapv2. (uint256 priceCumulative, uint32 blockTimestamp, uint256 twap) = getCurrentTwap(); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestamp; bool inCircuitBreaker = false; ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) = getNewHotpotBasePerBlock(twap); farmHotpotBasePerBlock = newFarmHotpotBasePerBlock; halvingCounter = newHalvingCounter; uint256 newRedShare = getNewRedShare(twap); // Do a bunch of things if twap is outside of threshold. if (!withinDeviationThreshold(twap)) { uint256 absoluteDeviationMovement = targetPrice.mul(deviationMovement).div(1e18); // Calculates and sets the new target rate if twap is outside of threshold. if (twap > targetPrice) { // no safe math required upwardCounter++; if (downwardCounter > 0) { downwardCounter = 0; } // if twap continues to go up, retargetThreshold is only effective for the first upward retarget // and every following rebase would retarget upward until twap is within deviation threshold if (upwardCounter >= retargetThreshold) { targetPrice = targetPrice.add(absoluteDeviationMovement); } } else { inCircuitBreaker = true; // no safe math required downwardCounter++; if (upwardCounter > 0) { upwardCounter = 0; } // if twap continues to go down, retargetThreshold is only effective for the first downward retarget // and every following rebase would retarget downward until twap is within deviation threshold if (downwardCounter >= retargetThreshold) { targetPrice = targetPrice.sub(absoluteDeviationMovement); } } } else { upwardCounter = 0; downwardCounter = 0; } masterPot.massUpdatePools(); masterPot.setHotpotBasePerBlock(newHotpotBasePerBlock); masterPot.setRedPotShare(newRedShare); masterPot.setCircuitBreaker(inCircuitBreaker); } /** * @notice Calculates TWAP from uniswap * * @dev When liquidity is low, this can be manipulated by an end of block -> next block * attack. We delay the activation of rebases 12 hours after liquidity incentives * to reduce this attack vector. Additional there is very little supply * to be able to manipulate this during that time period of highest vuln. */ function getCurrentTwap() public virtual view returns ( uint256 priceCumulative, uint32 blockTimestamp, uint256 twap ) { ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestampUniswap ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulative = isToken0 ? price0Cumulative : price1Cumulative; blockTimestamp = blockTimestampUniswap; uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulative - priceCumulativeLast) / timeElapsed) ); // 1e30 for trading pair with 6-decimal tokens. Be ultra-cautious when changing this. twap = FixedPoint.decode144(FixedPoint.mul(priceAverage, 1e30)); } // Computes new tokenPerBlock based on price. function getNewHotpotBasePerBlock(uint256 price) public view returns ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) { uint256 blockElapsed = getBlockNumber().sub(masterPot.startBlock()); newHalvingCounter = blockElapsed.div(halfLife); newFarmHotpotBasePerBlock = farmHotpotBasePerBlock; // if new halvingCounter is larger than old one, perform halving. if (newHalvingCounter > halvingCounter) { newFarmHotpotBasePerBlock = newFarmHotpotBasePerBlock.div(2); } // computes newHotpotBasePerBlock based on targetStock2Flow. newHotpotBasePerBlock = masterPot.hotpotBaseTotalSupply().div( targetStock2Flow.mul(2400000) ); // use the larger of newHotpotBasePerBlock and newFarmHotpotBasePerBlock. newHotpotBasePerBlock = newHotpotBasePerBlock > newFarmHotpotBasePerBlock ? newHotpotBasePerBlock : newFarmHotpotBasePerBlock; if (price > targetPrice) { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(price).div(targetPrice); } else { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(targetPrice).div(price); } } // Computes new redShare based on price. function getNewRedShare(uint256 price) public view returns (uint256) { return uint256(1e24).div(price.mul(1e12).div(targetPrice).add(1e12)); } // Check if the current price is within the deviation threshold for rebasing. function withinDeviationThreshold(uint256 price) public view returns (bool) { uint256 absoluteDeviationThreshold = targetPrice.mul(deviationThreshold).div(1e18); return (price >= targetPrice && price.sub(targetPrice) < absoluteDeviationThreshold) || (price < targetPrice && targetPrice.sub(price) < absoluteDeviationThreshold); } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetPrice, then no supply * modifications are made. * @param _deviationThreshold The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 _deviationThreshold) external onlyGov { require(_deviationThreshold > 0, 'deviationThreshold: too low'); uint256 oldDeviationThreshold = deviationThreshold; deviationThreshold = _deviationThreshold; emit NewDeviationThreshold(oldDeviationThreshold, _deviationThreshold); } function setDeviationMovement(uint256 _deviationMovement) external onlyGov { require(_deviationMovement > 0, 'deviationMovement: too low'); uint256 oldDeviationMovement = deviationMovement; deviationMovement = _deviationMovement; emit NewDeviationMovement(oldDeviationMovement, _deviationMovement); } // Sets the retarget threshold parameter, Gov only. function setRetargetThreshold(uint256 _retargetThreshold) external onlyGov { require(_retargetThreshold > 0, 'retargetThreshold: too low'); retargetThreshold = _retargetThreshold; } // Overwrites the target stock-to-flow ratio, Gov only. function setTargetStock2Flow(uint256 _targetStock2Flow) external onlyGov { require(_targetStock2Flow > 0, 'targetStock2Flow: too low'); targetStock2Flow = _targetStock2Flow; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param _minRebaseTimeIntervalSec More than this much time must pass between rebase * operations, in seconds. * @param _rebaseWindowOffsetSec The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param _rebaseWindowLengthSec The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 _minRebaseTimeIntervalSec, uint256 _rebaseWindowOffsetSec, uint256 _rebaseWindowLengthSec ) external onlyGov { require(_minRebaseTimeIntervalSec > 0, 'minRebaseTimeIntervalSec: too low'); require( _rebaseWindowOffsetSec < _minRebaseTimeIntervalSec, 'rebaseWindowOffsetSec: too high' ); minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec; rebaseWindowOffsetSec = _rebaseWindowOffsetSec; rebaseWindowLengthSec = _rebaseWindowLengthSec; } // Passthrough function to add pool. function addPool( uint256 _allocPoint, IERC20 _lpToken, bool _isRed, bool _withUpdate ) public onlyGov { masterPot.addPool(_allocPoint, _lpToken, _isRed, _withUpdate); } // Passthrough function to set pool. function setPool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyGov { masterPot.setPool(_pid, _allocPoint, _withUpdate); } // Passthrough function to set tip rate. function setTipRate(uint256 _tipRate) public onlyGov { masterPot.setTipRate(_tipRate); } // Passthrough function to transfer pot ownership. function transferPotOwnership(address newOwner) public onlyGov { masterPot.transferPotOwnership(newOwner); } function getNow() public virtual view returns (uint256) { return now; } function getBlockNumber() public virtual view returns (uint256) { return block.number; } }
acceptGov
function acceptGov() external { require(msg.sender == pendingGov, 'acceptGov: !pending'); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); }
// lets msg.sender accept governance
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://06c3e1b7010ded32c215d8d2b064a338aa716548f7264dc15aba4614175c048f
{ "func_code_index": [ 4225, 4426 ] }
59,652
ChefMao
contracts\ChefMao.sol
0xfbd3749eb2ed67454850939480433e71a9f5432d
Solidity
ChefMao
contract ChefMao { using SafeMath for uint256; modifier onlyGov() { require(msg.sender == gov, 'onlyGov: caller is not gov'); _; } // an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); // an event emitted when deviationMovement is changed event NewDeviationMovement(uint256 oldDeviationMovement, uint256 newDeviationMovement); // Event emitted when pendingGov is changed event NewPendingGov(address oldPendingGov, address newPendingGov); // Event emitted when gov is changed event NewGov(address oldGov, address newGov); // Governance address address public gov; // Pending Governance address address public pendingGov; // Peg target uint256 public targetPrice; // POT Tokens created per block at inception. // POT's inflation will eventually be governed by targetStock2Flow. uint256 public farmHotpotBasePerBlock; // Halving period for Hotpot Base per block, in blocks. uint256 public halfLife = 88888; // targetTokenPerBlock = totalSupply / (targetStock2Flow * 2,400,000) // 2,400,000 is ~1-year's ETH block count as of Sep 2020 // See @100trillionUSD's article below on Scarcity and S2F: // https://medium.com/@100trillionUSD/modeling-bitcoins-value-with-scarcity-91fa0fc03e25 // // Ganularity of targetStock2Flow is intentionally restricted. uint256 public targetStock2Flow = 10; // ~10% p.a. target inflation; // If the current price is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the price. // (ie) abs(price - targetPrice) / targetPrice < deviationThreshold, then no supply change. uint256 public deviationThreshold = 5e16; // 5% uint256 public deviationMovement = 5e16; // 5% // More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec = 24 hours; // Block timestamp of last rebase operation uint256 public lastRebaseTimestamp; // The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases // The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec = 3600; // 60 minutes // The number of rebase cycles since inception uint256 public epoch; // The number of halvings since inception uint256 public halvingCounter; // The number of consecutive upward threshold breaching when rebasing. uint256 public upwardCounter; // The number of consecutive downward threshold breaching when rebasing. uint256 public downwardCounter; uint256 public retargetThreshold = 2; // 2 days // rebasing is not active initially. It can be activated at T+12 hours from // deployment time // boolean showing rebase activation status bool public rebasingActive; // delays rebasing activation to facilitate liquidity uint256 public constant rebaseDelay = 12 hours; // Time of TWAP initialization uint256 public timeOfTwapInit; // pair for reserveToken <> POT address public uniswapPair; // last TWAP update time uint32 public blockTimestampLast; // last TWAP cumulative price; uint256 public priceCumulativeLast; // Whether or not this token is first in uniswap POT<>Reserve pair // address of USDT: // address of POT: bool public isToken0 = true; IYuanYangPot public masterPot; constructor( IYuanYangPot _masterPot, address _uniswapPair, address _gov, uint256 _targetPrice, bool _isToken0 ) public { masterPot = _masterPot; farmHotpotBasePerBlock = masterPot.hotpotBasePerBlock(); uniswapPair = _uniswapPair; gov = _gov; targetPrice = _targetPrice; isToken0 = _isToken0; } // sets the pendingGov function setPendingGov(address _pendingGov) external onlyGov { address oldPendingGov = pendingGov; pendingGov = _pendingGov; emit NewPendingGov(oldPendingGov, _pendingGov); } // lets msg.sender accept governance function acceptGov() external { require(msg.sender == pendingGov, 'acceptGov: !pending'); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } // Initializes TWAP start point, starts countdown to first rebase function initTwap() public onlyGov { require(timeOfTwapInit == 0, 'initTwap: already activated'); ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulativeLast = isToken0 ? price0Cumulative : price1Cumulative; require(priceCumulativeLast > 0, 'initTwap: no trades'); blockTimestampLast = blockTimestamp; timeOfTwapInit = blockTimestamp; } // @notice Activates rebasing // @dev One way function, cannot be undone, callable by anyone function activateRebasing() public { require(timeOfTwapInit > 0, 'activateRebasing: twap wasnt intitiated, call init_twap()'); // cannot enable prior to end of rebaseDelay require(getNow() >= timeOfTwapInit + rebaseDelay, 'activateRebasing: !end_delay'); rebasingActive = true; } // If the latest block timestamp is within the rebase time window it, returns true. // Otherwise, returns false. function inRebaseWindow() public view returns (bool) { // rebasing is delayed until there is a liquid market require(rebasingActive, 'inRebaseWindow: rebasing not active'); uint256 nowTimestamp = getNow(); require( nowTimestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, 'inRebaseWindow: too early' ); require( nowTimestamp.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), 'inRebaseWindow: too late' ); return true; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetPrice) / targetPrice * and targetPrice is 1e18 */ function rebase() public { // no possibility of reentry as this function only invoke view functions or internal functions // or functions from master pot which also only invoke only invoke view functions or internal functions // EOA only // require(msg.sender == tx.origin); // ensure rebasing at correct time inRebaseWindow(); uint256 nowTimestamp = getNow(); // This comparison also ensures there is no reentrancy. require( lastRebaseTimestamp.add(minRebaseTimeIntervalSec) < nowTimestamp, 'rebase: Rebase already triggered' ); // Snap the rebase time to the start of this window. lastRebaseTimestamp = nowTimestamp.sub(nowTimestamp.mod(minRebaseTimeIntervalSec)).add( rebaseWindowOffsetSec ); // no safe math required epoch++; // Get twap from uniswapv2. (uint256 priceCumulative, uint32 blockTimestamp, uint256 twap) = getCurrentTwap(); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestamp; bool inCircuitBreaker = false; ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) = getNewHotpotBasePerBlock(twap); farmHotpotBasePerBlock = newFarmHotpotBasePerBlock; halvingCounter = newHalvingCounter; uint256 newRedShare = getNewRedShare(twap); // Do a bunch of things if twap is outside of threshold. if (!withinDeviationThreshold(twap)) { uint256 absoluteDeviationMovement = targetPrice.mul(deviationMovement).div(1e18); // Calculates and sets the new target rate if twap is outside of threshold. if (twap > targetPrice) { // no safe math required upwardCounter++; if (downwardCounter > 0) { downwardCounter = 0; } // if twap continues to go up, retargetThreshold is only effective for the first upward retarget // and every following rebase would retarget upward until twap is within deviation threshold if (upwardCounter >= retargetThreshold) { targetPrice = targetPrice.add(absoluteDeviationMovement); } } else { inCircuitBreaker = true; // no safe math required downwardCounter++; if (upwardCounter > 0) { upwardCounter = 0; } // if twap continues to go down, retargetThreshold is only effective for the first downward retarget // and every following rebase would retarget downward until twap is within deviation threshold if (downwardCounter >= retargetThreshold) { targetPrice = targetPrice.sub(absoluteDeviationMovement); } } } else { upwardCounter = 0; downwardCounter = 0; } masterPot.massUpdatePools(); masterPot.setHotpotBasePerBlock(newHotpotBasePerBlock); masterPot.setRedPotShare(newRedShare); masterPot.setCircuitBreaker(inCircuitBreaker); } /** * @notice Calculates TWAP from uniswap * * @dev When liquidity is low, this can be manipulated by an end of block -> next block * attack. We delay the activation of rebases 12 hours after liquidity incentives * to reduce this attack vector. Additional there is very little supply * to be able to manipulate this during that time period of highest vuln. */ function getCurrentTwap() public virtual view returns ( uint256 priceCumulative, uint32 blockTimestamp, uint256 twap ) { ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestampUniswap ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulative = isToken0 ? price0Cumulative : price1Cumulative; blockTimestamp = blockTimestampUniswap; uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulative - priceCumulativeLast) / timeElapsed) ); // 1e30 for trading pair with 6-decimal tokens. Be ultra-cautious when changing this. twap = FixedPoint.decode144(FixedPoint.mul(priceAverage, 1e30)); } // Computes new tokenPerBlock based on price. function getNewHotpotBasePerBlock(uint256 price) public view returns ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) { uint256 blockElapsed = getBlockNumber().sub(masterPot.startBlock()); newHalvingCounter = blockElapsed.div(halfLife); newFarmHotpotBasePerBlock = farmHotpotBasePerBlock; // if new halvingCounter is larger than old one, perform halving. if (newHalvingCounter > halvingCounter) { newFarmHotpotBasePerBlock = newFarmHotpotBasePerBlock.div(2); } // computes newHotpotBasePerBlock based on targetStock2Flow. newHotpotBasePerBlock = masterPot.hotpotBaseTotalSupply().div( targetStock2Flow.mul(2400000) ); // use the larger of newHotpotBasePerBlock and newFarmHotpotBasePerBlock. newHotpotBasePerBlock = newHotpotBasePerBlock > newFarmHotpotBasePerBlock ? newHotpotBasePerBlock : newFarmHotpotBasePerBlock; if (price > targetPrice) { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(price).div(targetPrice); } else { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(targetPrice).div(price); } } // Computes new redShare based on price. function getNewRedShare(uint256 price) public view returns (uint256) { return uint256(1e24).div(price.mul(1e12).div(targetPrice).add(1e12)); } // Check if the current price is within the deviation threshold for rebasing. function withinDeviationThreshold(uint256 price) public view returns (bool) { uint256 absoluteDeviationThreshold = targetPrice.mul(deviationThreshold).div(1e18); return (price >= targetPrice && price.sub(targetPrice) < absoluteDeviationThreshold) || (price < targetPrice && targetPrice.sub(price) < absoluteDeviationThreshold); } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetPrice, then no supply * modifications are made. * @param _deviationThreshold The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 _deviationThreshold) external onlyGov { require(_deviationThreshold > 0, 'deviationThreshold: too low'); uint256 oldDeviationThreshold = deviationThreshold; deviationThreshold = _deviationThreshold; emit NewDeviationThreshold(oldDeviationThreshold, _deviationThreshold); } function setDeviationMovement(uint256 _deviationMovement) external onlyGov { require(_deviationMovement > 0, 'deviationMovement: too low'); uint256 oldDeviationMovement = deviationMovement; deviationMovement = _deviationMovement; emit NewDeviationMovement(oldDeviationMovement, _deviationMovement); } // Sets the retarget threshold parameter, Gov only. function setRetargetThreshold(uint256 _retargetThreshold) external onlyGov { require(_retargetThreshold > 0, 'retargetThreshold: too low'); retargetThreshold = _retargetThreshold; } // Overwrites the target stock-to-flow ratio, Gov only. function setTargetStock2Flow(uint256 _targetStock2Flow) external onlyGov { require(_targetStock2Flow > 0, 'targetStock2Flow: too low'); targetStock2Flow = _targetStock2Flow; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param _minRebaseTimeIntervalSec More than this much time must pass between rebase * operations, in seconds. * @param _rebaseWindowOffsetSec The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param _rebaseWindowLengthSec The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 _minRebaseTimeIntervalSec, uint256 _rebaseWindowOffsetSec, uint256 _rebaseWindowLengthSec ) external onlyGov { require(_minRebaseTimeIntervalSec > 0, 'minRebaseTimeIntervalSec: too low'); require( _rebaseWindowOffsetSec < _minRebaseTimeIntervalSec, 'rebaseWindowOffsetSec: too high' ); minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec; rebaseWindowOffsetSec = _rebaseWindowOffsetSec; rebaseWindowLengthSec = _rebaseWindowLengthSec; } // Passthrough function to add pool. function addPool( uint256 _allocPoint, IERC20 _lpToken, bool _isRed, bool _withUpdate ) public onlyGov { masterPot.addPool(_allocPoint, _lpToken, _isRed, _withUpdate); } // Passthrough function to set pool. function setPool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyGov { masterPot.setPool(_pid, _allocPoint, _withUpdate); } // Passthrough function to set tip rate. function setTipRate(uint256 _tipRate) public onlyGov { masterPot.setTipRate(_tipRate); } // Passthrough function to transfer pot ownership. function transferPotOwnership(address newOwner) public onlyGov { masterPot.transferPotOwnership(newOwner); } function getNow() public virtual view returns (uint256) { return now; } function getBlockNumber() public virtual view returns (uint256) { return block.number; } }
initTwap
function initTwap() public onlyGov { require(timeOfTwapInit == 0, 'initTwap: already activated'); ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulativeLast = isToken0 ? price0Cumulative : price1Cumulative; require(priceCumulativeLast > 0, 'initTwap: no trades'); blockTimestampLast = blockTimestamp; timeOfTwapInit = blockTimestamp; }
// Initializes TWAP start point, starts countdown to first rebase
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://06c3e1b7010ded32c215d8d2b064a338aa716548f7264dc15aba4614175c048f
{ "func_code_index": [ 4497, 4971 ] }
59,653
ChefMao
contracts\ChefMao.sol
0xfbd3749eb2ed67454850939480433e71a9f5432d
Solidity
ChefMao
contract ChefMao { using SafeMath for uint256; modifier onlyGov() { require(msg.sender == gov, 'onlyGov: caller is not gov'); _; } // an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); // an event emitted when deviationMovement is changed event NewDeviationMovement(uint256 oldDeviationMovement, uint256 newDeviationMovement); // Event emitted when pendingGov is changed event NewPendingGov(address oldPendingGov, address newPendingGov); // Event emitted when gov is changed event NewGov(address oldGov, address newGov); // Governance address address public gov; // Pending Governance address address public pendingGov; // Peg target uint256 public targetPrice; // POT Tokens created per block at inception. // POT's inflation will eventually be governed by targetStock2Flow. uint256 public farmHotpotBasePerBlock; // Halving period for Hotpot Base per block, in blocks. uint256 public halfLife = 88888; // targetTokenPerBlock = totalSupply / (targetStock2Flow * 2,400,000) // 2,400,000 is ~1-year's ETH block count as of Sep 2020 // See @100trillionUSD's article below on Scarcity and S2F: // https://medium.com/@100trillionUSD/modeling-bitcoins-value-with-scarcity-91fa0fc03e25 // // Ganularity of targetStock2Flow is intentionally restricted. uint256 public targetStock2Flow = 10; // ~10% p.a. target inflation; // If the current price is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the price. // (ie) abs(price - targetPrice) / targetPrice < deviationThreshold, then no supply change. uint256 public deviationThreshold = 5e16; // 5% uint256 public deviationMovement = 5e16; // 5% // More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec = 24 hours; // Block timestamp of last rebase operation uint256 public lastRebaseTimestamp; // The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases // The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec = 3600; // 60 minutes // The number of rebase cycles since inception uint256 public epoch; // The number of halvings since inception uint256 public halvingCounter; // The number of consecutive upward threshold breaching when rebasing. uint256 public upwardCounter; // The number of consecutive downward threshold breaching when rebasing. uint256 public downwardCounter; uint256 public retargetThreshold = 2; // 2 days // rebasing is not active initially. It can be activated at T+12 hours from // deployment time // boolean showing rebase activation status bool public rebasingActive; // delays rebasing activation to facilitate liquidity uint256 public constant rebaseDelay = 12 hours; // Time of TWAP initialization uint256 public timeOfTwapInit; // pair for reserveToken <> POT address public uniswapPair; // last TWAP update time uint32 public blockTimestampLast; // last TWAP cumulative price; uint256 public priceCumulativeLast; // Whether or not this token is first in uniswap POT<>Reserve pair // address of USDT: // address of POT: bool public isToken0 = true; IYuanYangPot public masterPot; constructor( IYuanYangPot _masterPot, address _uniswapPair, address _gov, uint256 _targetPrice, bool _isToken0 ) public { masterPot = _masterPot; farmHotpotBasePerBlock = masterPot.hotpotBasePerBlock(); uniswapPair = _uniswapPair; gov = _gov; targetPrice = _targetPrice; isToken0 = _isToken0; } // sets the pendingGov function setPendingGov(address _pendingGov) external onlyGov { address oldPendingGov = pendingGov; pendingGov = _pendingGov; emit NewPendingGov(oldPendingGov, _pendingGov); } // lets msg.sender accept governance function acceptGov() external { require(msg.sender == pendingGov, 'acceptGov: !pending'); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } // Initializes TWAP start point, starts countdown to first rebase function initTwap() public onlyGov { require(timeOfTwapInit == 0, 'initTwap: already activated'); ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulativeLast = isToken0 ? price0Cumulative : price1Cumulative; require(priceCumulativeLast > 0, 'initTwap: no trades'); blockTimestampLast = blockTimestamp; timeOfTwapInit = blockTimestamp; } // @notice Activates rebasing // @dev One way function, cannot be undone, callable by anyone function activateRebasing() public { require(timeOfTwapInit > 0, 'activateRebasing: twap wasnt intitiated, call init_twap()'); // cannot enable prior to end of rebaseDelay require(getNow() >= timeOfTwapInit + rebaseDelay, 'activateRebasing: !end_delay'); rebasingActive = true; } // If the latest block timestamp is within the rebase time window it, returns true. // Otherwise, returns false. function inRebaseWindow() public view returns (bool) { // rebasing is delayed until there is a liquid market require(rebasingActive, 'inRebaseWindow: rebasing not active'); uint256 nowTimestamp = getNow(); require( nowTimestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, 'inRebaseWindow: too early' ); require( nowTimestamp.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), 'inRebaseWindow: too late' ); return true; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetPrice) / targetPrice * and targetPrice is 1e18 */ function rebase() public { // no possibility of reentry as this function only invoke view functions or internal functions // or functions from master pot which also only invoke only invoke view functions or internal functions // EOA only // require(msg.sender == tx.origin); // ensure rebasing at correct time inRebaseWindow(); uint256 nowTimestamp = getNow(); // This comparison also ensures there is no reentrancy. require( lastRebaseTimestamp.add(minRebaseTimeIntervalSec) < nowTimestamp, 'rebase: Rebase already triggered' ); // Snap the rebase time to the start of this window. lastRebaseTimestamp = nowTimestamp.sub(nowTimestamp.mod(minRebaseTimeIntervalSec)).add( rebaseWindowOffsetSec ); // no safe math required epoch++; // Get twap from uniswapv2. (uint256 priceCumulative, uint32 blockTimestamp, uint256 twap) = getCurrentTwap(); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestamp; bool inCircuitBreaker = false; ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) = getNewHotpotBasePerBlock(twap); farmHotpotBasePerBlock = newFarmHotpotBasePerBlock; halvingCounter = newHalvingCounter; uint256 newRedShare = getNewRedShare(twap); // Do a bunch of things if twap is outside of threshold. if (!withinDeviationThreshold(twap)) { uint256 absoluteDeviationMovement = targetPrice.mul(deviationMovement).div(1e18); // Calculates and sets the new target rate if twap is outside of threshold. if (twap > targetPrice) { // no safe math required upwardCounter++; if (downwardCounter > 0) { downwardCounter = 0; } // if twap continues to go up, retargetThreshold is only effective for the first upward retarget // and every following rebase would retarget upward until twap is within deviation threshold if (upwardCounter >= retargetThreshold) { targetPrice = targetPrice.add(absoluteDeviationMovement); } } else { inCircuitBreaker = true; // no safe math required downwardCounter++; if (upwardCounter > 0) { upwardCounter = 0; } // if twap continues to go down, retargetThreshold is only effective for the first downward retarget // and every following rebase would retarget downward until twap is within deviation threshold if (downwardCounter >= retargetThreshold) { targetPrice = targetPrice.sub(absoluteDeviationMovement); } } } else { upwardCounter = 0; downwardCounter = 0; } masterPot.massUpdatePools(); masterPot.setHotpotBasePerBlock(newHotpotBasePerBlock); masterPot.setRedPotShare(newRedShare); masterPot.setCircuitBreaker(inCircuitBreaker); } /** * @notice Calculates TWAP from uniswap * * @dev When liquidity is low, this can be manipulated by an end of block -> next block * attack. We delay the activation of rebases 12 hours after liquidity incentives * to reduce this attack vector. Additional there is very little supply * to be able to manipulate this during that time period of highest vuln. */ function getCurrentTwap() public virtual view returns ( uint256 priceCumulative, uint32 blockTimestamp, uint256 twap ) { ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestampUniswap ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulative = isToken0 ? price0Cumulative : price1Cumulative; blockTimestamp = blockTimestampUniswap; uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulative - priceCumulativeLast) / timeElapsed) ); // 1e30 for trading pair with 6-decimal tokens. Be ultra-cautious when changing this. twap = FixedPoint.decode144(FixedPoint.mul(priceAverage, 1e30)); } // Computes new tokenPerBlock based on price. function getNewHotpotBasePerBlock(uint256 price) public view returns ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) { uint256 blockElapsed = getBlockNumber().sub(masterPot.startBlock()); newHalvingCounter = blockElapsed.div(halfLife); newFarmHotpotBasePerBlock = farmHotpotBasePerBlock; // if new halvingCounter is larger than old one, perform halving. if (newHalvingCounter > halvingCounter) { newFarmHotpotBasePerBlock = newFarmHotpotBasePerBlock.div(2); } // computes newHotpotBasePerBlock based on targetStock2Flow. newHotpotBasePerBlock = masterPot.hotpotBaseTotalSupply().div( targetStock2Flow.mul(2400000) ); // use the larger of newHotpotBasePerBlock and newFarmHotpotBasePerBlock. newHotpotBasePerBlock = newHotpotBasePerBlock > newFarmHotpotBasePerBlock ? newHotpotBasePerBlock : newFarmHotpotBasePerBlock; if (price > targetPrice) { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(price).div(targetPrice); } else { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(targetPrice).div(price); } } // Computes new redShare based on price. function getNewRedShare(uint256 price) public view returns (uint256) { return uint256(1e24).div(price.mul(1e12).div(targetPrice).add(1e12)); } // Check if the current price is within the deviation threshold for rebasing. function withinDeviationThreshold(uint256 price) public view returns (bool) { uint256 absoluteDeviationThreshold = targetPrice.mul(deviationThreshold).div(1e18); return (price >= targetPrice && price.sub(targetPrice) < absoluteDeviationThreshold) || (price < targetPrice && targetPrice.sub(price) < absoluteDeviationThreshold); } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetPrice, then no supply * modifications are made. * @param _deviationThreshold The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 _deviationThreshold) external onlyGov { require(_deviationThreshold > 0, 'deviationThreshold: too low'); uint256 oldDeviationThreshold = deviationThreshold; deviationThreshold = _deviationThreshold; emit NewDeviationThreshold(oldDeviationThreshold, _deviationThreshold); } function setDeviationMovement(uint256 _deviationMovement) external onlyGov { require(_deviationMovement > 0, 'deviationMovement: too low'); uint256 oldDeviationMovement = deviationMovement; deviationMovement = _deviationMovement; emit NewDeviationMovement(oldDeviationMovement, _deviationMovement); } // Sets the retarget threshold parameter, Gov only. function setRetargetThreshold(uint256 _retargetThreshold) external onlyGov { require(_retargetThreshold > 0, 'retargetThreshold: too low'); retargetThreshold = _retargetThreshold; } // Overwrites the target stock-to-flow ratio, Gov only. function setTargetStock2Flow(uint256 _targetStock2Flow) external onlyGov { require(_targetStock2Flow > 0, 'targetStock2Flow: too low'); targetStock2Flow = _targetStock2Flow; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param _minRebaseTimeIntervalSec More than this much time must pass between rebase * operations, in seconds. * @param _rebaseWindowOffsetSec The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param _rebaseWindowLengthSec The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 _minRebaseTimeIntervalSec, uint256 _rebaseWindowOffsetSec, uint256 _rebaseWindowLengthSec ) external onlyGov { require(_minRebaseTimeIntervalSec > 0, 'minRebaseTimeIntervalSec: too low'); require( _rebaseWindowOffsetSec < _minRebaseTimeIntervalSec, 'rebaseWindowOffsetSec: too high' ); minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec; rebaseWindowOffsetSec = _rebaseWindowOffsetSec; rebaseWindowLengthSec = _rebaseWindowLengthSec; } // Passthrough function to add pool. function addPool( uint256 _allocPoint, IERC20 _lpToken, bool _isRed, bool _withUpdate ) public onlyGov { masterPot.addPool(_allocPoint, _lpToken, _isRed, _withUpdate); } // Passthrough function to set pool. function setPool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyGov { masterPot.setPool(_pid, _allocPoint, _withUpdate); } // Passthrough function to set tip rate. function setTipRate(uint256 _tipRate) public onlyGov { masterPot.setTipRate(_tipRate); } // Passthrough function to transfer pot ownership. function transferPotOwnership(address newOwner) public onlyGov { masterPot.transferPotOwnership(newOwner); } function getNow() public virtual view returns (uint256) { return now; } function getBlockNumber() public virtual view returns (uint256) { return block.number; } }
activateRebasing
function activateRebasing() public { require(timeOfTwapInit > 0, 'activateRebasing: twap wasnt intitiated, call init_twap()'); // cannot enable prior to end of rebaseDelay require(getNow() >= timeOfTwapInit + rebaseDelay, 'activateRebasing: !end_delay'); rebasingActive = true; }
// @notice Activates rebasing // @dev One way function, cannot be undone, callable by anyone
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://06c3e1b7010ded32c215d8d2b064a338aa716548f7264dc15aba4614175c048f
{ "func_code_index": [ 5071, 5368 ] }
59,654
ChefMao
contracts\ChefMao.sol
0xfbd3749eb2ed67454850939480433e71a9f5432d
Solidity
ChefMao
contract ChefMao { using SafeMath for uint256; modifier onlyGov() { require(msg.sender == gov, 'onlyGov: caller is not gov'); _; } // an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); // an event emitted when deviationMovement is changed event NewDeviationMovement(uint256 oldDeviationMovement, uint256 newDeviationMovement); // Event emitted when pendingGov is changed event NewPendingGov(address oldPendingGov, address newPendingGov); // Event emitted when gov is changed event NewGov(address oldGov, address newGov); // Governance address address public gov; // Pending Governance address address public pendingGov; // Peg target uint256 public targetPrice; // POT Tokens created per block at inception. // POT's inflation will eventually be governed by targetStock2Flow. uint256 public farmHotpotBasePerBlock; // Halving period for Hotpot Base per block, in blocks. uint256 public halfLife = 88888; // targetTokenPerBlock = totalSupply / (targetStock2Flow * 2,400,000) // 2,400,000 is ~1-year's ETH block count as of Sep 2020 // See @100trillionUSD's article below on Scarcity and S2F: // https://medium.com/@100trillionUSD/modeling-bitcoins-value-with-scarcity-91fa0fc03e25 // // Ganularity of targetStock2Flow is intentionally restricted. uint256 public targetStock2Flow = 10; // ~10% p.a. target inflation; // If the current price is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the price. // (ie) abs(price - targetPrice) / targetPrice < deviationThreshold, then no supply change. uint256 public deviationThreshold = 5e16; // 5% uint256 public deviationMovement = 5e16; // 5% // More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec = 24 hours; // Block timestamp of last rebase operation uint256 public lastRebaseTimestamp; // The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases // The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec = 3600; // 60 minutes // The number of rebase cycles since inception uint256 public epoch; // The number of halvings since inception uint256 public halvingCounter; // The number of consecutive upward threshold breaching when rebasing. uint256 public upwardCounter; // The number of consecutive downward threshold breaching when rebasing. uint256 public downwardCounter; uint256 public retargetThreshold = 2; // 2 days // rebasing is not active initially. It can be activated at T+12 hours from // deployment time // boolean showing rebase activation status bool public rebasingActive; // delays rebasing activation to facilitate liquidity uint256 public constant rebaseDelay = 12 hours; // Time of TWAP initialization uint256 public timeOfTwapInit; // pair for reserveToken <> POT address public uniswapPair; // last TWAP update time uint32 public blockTimestampLast; // last TWAP cumulative price; uint256 public priceCumulativeLast; // Whether or not this token is first in uniswap POT<>Reserve pair // address of USDT: // address of POT: bool public isToken0 = true; IYuanYangPot public masterPot; constructor( IYuanYangPot _masterPot, address _uniswapPair, address _gov, uint256 _targetPrice, bool _isToken0 ) public { masterPot = _masterPot; farmHotpotBasePerBlock = masterPot.hotpotBasePerBlock(); uniswapPair = _uniswapPair; gov = _gov; targetPrice = _targetPrice; isToken0 = _isToken0; } // sets the pendingGov function setPendingGov(address _pendingGov) external onlyGov { address oldPendingGov = pendingGov; pendingGov = _pendingGov; emit NewPendingGov(oldPendingGov, _pendingGov); } // lets msg.sender accept governance function acceptGov() external { require(msg.sender == pendingGov, 'acceptGov: !pending'); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } // Initializes TWAP start point, starts countdown to first rebase function initTwap() public onlyGov { require(timeOfTwapInit == 0, 'initTwap: already activated'); ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulativeLast = isToken0 ? price0Cumulative : price1Cumulative; require(priceCumulativeLast > 0, 'initTwap: no trades'); blockTimestampLast = blockTimestamp; timeOfTwapInit = blockTimestamp; } // @notice Activates rebasing // @dev One way function, cannot be undone, callable by anyone function activateRebasing() public { require(timeOfTwapInit > 0, 'activateRebasing: twap wasnt intitiated, call init_twap()'); // cannot enable prior to end of rebaseDelay require(getNow() >= timeOfTwapInit + rebaseDelay, 'activateRebasing: !end_delay'); rebasingActive = true; } // If the latest block timestamp is within the rebase time window it, returns true. // Otherwise, returns false. function inRebaseWindow() public view returns (bool) { // rebasing is delayed until there is a liquid market require(rebasingActive, 'inRebaseWindow: rebasing not active'); uint256 nowTimestamp = getNow(); require( nowTimestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, 'inRebaseWindow: too early' ); require( nowTimestamp.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), 'inRebaseWindow: too late' ); return true; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetPrice) / targetPrice * and targetPrice is 1e18 */ function rebase() public { // no possibility of reentry as this function only invoke view functions or internal functions // or functions from master pot which also only invoke only invoke view functions or internal functions // EOA only // require(msg.sender == tx.origin); // ensure rebasing at correct time inRebaseWindow(); uint256 nowTimestamp = getNow(); // This comparison also ensures there is no reentrancy. require( lastRebaseTimestamp.add(minRebaseTimeIntervalSec) < nowTimestamp, 'rebase: Rebase already triggered' ); // Snap the rebase time to the start of this window. lastRebaseTimestamp = nowTimestamp.sub(nowTimestamp.mod(minRebaseTimeIntervalSec)).add( rebaseWindowOffsetSec ); // no safe math required epoch++; // Get twap from uniswapv2. (uint256 priceCumulative, uint32 blockTimestamp, uint256 twap) = getCurrentTwap(); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestamp; bool inCircuitBreaker = false; ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) = getNewHotpotBasePerBlock(twap); farmHotpotBasePerBlock = newFarmHotpotBasePerBlock; halvingCounter = newHalvingCounter; uint256 newRedShare = getNewRedShare(twap); // Do a bunch of things if twap is outside of threshold. if (!withinDeviationThreshold(twap)) { uint256 absoluteDeviationMovement = targetPrice.mul(deviationMovement).div(1e18); // Calculates and sets the new target rate if twap is outside of threshold. if (twap > targetPrice) { // no safe math required upwardCounter++; if (downwardCounter > 0) { downwardCounter = 0; } // if twap continues to go up, retargetThreshold is only effective for the first upward retarget // and every following rebase would retarget upward until twap is within deviation threshold if (upwardCounter >= retargetThreshold) { targetPrice = targetPrice.add(absoluteDeviationMovement); } } else { inCircuitBreaker = true; // no safe math required downwardCounter++; if (upwardCounter > 0) { upwardCounter = 0; } // if twap continues to go down, retargetThreshold is only effective for the first downward retarget // and every following rebase would retarget downward until twap is within deviation threshold if (downwardCounter >= retargetThreshold) { targetPrice = targetPrice.sub(absoluteDeviationMovement); } } } else { upwardCounter = 0; downwardCounter = 0; } masterPot.massUpdatePools(); masterPot.setHotpotBasePerBlock(newHotpotBasePerBlock); masterPot.setRedPotShare(newRedShare); masterPot.setCircuitBreaker(inCircuitBreaker); } /** * @notice Calculates TWAP from uniswap * * @dev When liquidity is low, this can be manipulated by an end of block -> next block * attack. We delay the activation of rebases 12 hours after liquidity incentives * to reduce this attack vector. Additional there is very little supply * to be able to manipulate this during that time period of highest vuln. */ function getCurrentTwap() public virtual view returns ( uint256 priceCumulative, uint32 blockTimestamp, uint256 twap ) { ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestampUniswap ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulative = isToken0 ? price0Cumulative : price1Cumulative; blockTimestamp = blockTimestampUniswap; uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulative - priceCumulativeLast) / timeElapsed) ); // 1e30 for trading pair with 6-decimal tokens. Be ultra-cautious when changing this. twap = FixedPoint.decode144(FixedPoint.mul(priceAverage, 1e30)); } // Computes new tokenPerBlock based on price. function getNewHotpotBasePerBlock(uint256 price) public view returns ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) { uint256 blockElapsed = getBlockNumber().sub(masterPot.startBlock()); newHalvingCounter = blockElapsed.div(halfLife); newFarmHotpotBasePerBlock = farmHotpotBasePerBlock; // if new halvingCounter is larger than old one, perform halving. if (newHalvingCounter > halvingCounter) { newFarmHotpotBasePerBlock = newFarmHotpotBasePerBlock.div(2); } // computes newHotpotBasePerBlock based on targetStock2Flow. newHotpotBasePerBlock = masterPot.hotpotBaseTotalSupply().div( targetStock2Flow.mul(2400000) ); // use the larger of newHotpotBasePerBlock and newFarmHotpotBasePerBlock. newHotpotBasePerBlock = newHotpotBasePerBlock > newFarmHotpotBasePerBlock ? newHotpotBasePerBlock : newFarmHotpotBasePerBlock; if (price > targetPrice) { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(price).div(targetPrice); } else { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(targetPrice).div(price); } } // Computes new redShare based on price. function getNewRedShare(uint256 price) public view returns (uint256) { return uint256(1e24).div(price.mul(1e12).div(targetPrice).add(1e12)); } // Check if the current price is within the deviation threshold for rebasing. function withinDeviationThreshold(uint256 price) public view returns (bool) { uint256 absoluteDeviationThreshold = targetPrice.mul(deviationThreshold).div(1e18); return (price >= targetPrice && price.sub(targetPrice) < absoluteDeviationThreshold) || (price < targetPrice && targetPrice.sub(price) < absoluteDeviationThreshold); } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetPrice, then no supply * modifications are made. * @param _deviationThreshold The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 _deviationThreshold) external onlyGov { require(_deviationThreshold > 0, 'deviationThreshold: too low'); uint256 oldDeviationThreshold = deviationThreshold; deviationThreshold = _deviationThreshold; emit NewDeviationThreshold(oldDeviationThreshold, _deviationThreshold); } function setDeviationMovement(uint256 _deviationMovement) external onlyGov { require(_deviationMovement > 0, 'deviationMovement: too low'); uint256 oldDeviationMovement = deviationMovement; deviationMovement = _deviationMovement; emit NewDeviationMovement(oldDeviationMovement, _deviationMovement); } // Sets the retarget threshold parameter, Gov only. function setRetargetThreshold(uint256 _retargetThreshold) external onlyGov { require(_retargetThreshold > 0, 'retargetThreshold: too low'); retargetThreshold = _retargetThreshold; } // Overwrites the target stock-to-flow ratio, Gov only. function setTargetStock2Flow(uint256 _targetStock2Flow) external onlyGov { require(_targetStock2Flow > 0, 'targetStock2Flow: too low'); targetStock2Flow = _targetStock2Flow; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param _minRebaseTimeIntervalSec More than this much time must pass between rebase * operations, in seconds. * @param _rebaseWindowOffsetSec The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param _rebaseWindowLengthSec The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 _minRebaseTimeIntervalSec, uint256 _rebaseWindowOffsetSec, uint256 _rebaseWindowLengthSec ) external onlyGov { require(_minRebaseTimeIntervalSec > 0, 'minRebaseTimeIntervalSec: too low'); require( _rebaseWindowOffsetSec < _minRebaseTimeIntervalSec, 'rebaseWindowOffsetSec: too high' ); minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec; rebaseWindowOffsetSec = _rebaseWindowOffsetSec; rebaseWindowLengthSec = _rebaseWindowLengthSec; } // Passthrough function to add pool. function addPool( uint256 _allocPoint, IERC20 _lpToken, bool _isRed, bool _withUpdate ) public onlyGov { masterPot.addPool(_allocPoint, _lpToken, _isRed, _withUpdate); } // Passthrough function to set pool. function setPool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyGov { masterPot.setPool(_pid, _allocPoint, _withUpdate); } // Passthrough function to set tip rate. function setTipRate(uint256 _tipRate) public onlyGov { masterPot.setTipRate(_tipRate); } // Passthrough function to transfer pot ownership. function transferPotOwnership(address newOwner) public onlyGov { masterPot.transferPotOwnership(newOwner); } function getNow() public virtual view returns (uint256) { return now; } function getBlockNumber() public virtual view returns (uint256) { return block.number; } }
inRebaseWindow
function inRebaseWindow() public view returns (bool) { // rebasing is delayed until there is a liquid market require(rebasingActive, 'inRebaseWindow: rebasing not active'); uint256 nowTimestamp = getNow(); require( nowTimestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, 'inRebaseWindow: too early' ); require( nowTimestamp.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), 'inRebaseWindow: too late' ); return true; }
// If the latest block timestamp is within the rebase time window it, returns true. // Otherwise, returns false.
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://06c3e1b7010ded32c215d8d2b064a338aa716548f7264dc15aba4614175c048f
{ "func_code_index": [ 5488, 6002 ] }
59,655
ChefMao
contracts\ChefMao.sol
0xfbd3749eb2ed67454850939480433e71a9f5432d
Solidity
ChefMao
contract ChefMao { using SafeMath for uint256; modifier onlyGov() { require(msg.sender == gov, 'onlyGov: caller is not gov'); _; } // an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); // an event emitted when deviationMovement is changed event NewDeviationMovement(uint256 oldDeviationMovement, uint256 newDeviationMovement); // Event emitted when pendingGov is changed event NewPendingGov(address oldPendingGov, address newPendingGov); // Event emitted when gov is changed event NewGov(address oldGov, address newGov); // Governance address address public gov; // Pending Governance address address public pendingGov; // Peg target uint256 public targetPrice; // POT Tokens created per block at inception. // POT's inflation will eventually be governed by targetStock2Flow. uint256 public farmHotpotBasePerBlock; // Halving period for Hotpot Base per block, in blocks. uint256 public halfLife = 88888; // targetTokenPerBlock = totalSupply / (targetStock2Flow * 2,400,000) // 2,400,000 is ~1-year's ETH block count as of Sep 2020 // See @100trillionUSD's article below on Scarcity and S2F: // https://medium.com/@100trillionUSD/modeling-bitcoins-value-with-scarcity-91fa0fc03e25 // // Ganularity of targetStock2Flow is intentionally restricted. uint256 public targetStock2Flow = 10; // ~10% p.a. target inflation; // If the current price is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the price. // (ie) abs(price - targetPrice) / targetPrice < deviationThreshold, then no supply change. uint256 public deviationThreshold = 5e16; // 5% uint256 public deviationMovement = 5e16; // 5% // More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec = 24 hours; // Block timestamp of last rebase operation uint256 public lastRebaseTimestamp; // The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases // The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec = 3600; // 60 minutes // The number of rebase cycles since inception uint256 public epoch; // The number of halvings since inception uint256 public halvingCounter; // The number of consecutive upward threshold breaching when rebasing. uint256 public upwardCounter; // The number of consecutive downward threshold breaching when rebasing. uint256 public downwardCounter; uint256 public retargetThreshold = 2; // 2 days // rebasing is not active initially. It can be activated at T+12 hours from // deployment time // boolean showing rebase activation status bool public rebasingActive; // delays rebasing activation to facilitate liquidity uint256 public constant rebaseDelay = 12 hours; // Time of TWAP initialization uint256 public timeOfTwapInit; // pair for reserveToken <> POT address public uniswapPair; // last TWAP update time uint32 public blockTimestampLast; // last TWAP cumulative price; uint256 public priceCumulativeLast; // Whether or not this token is first in uniswap POT<>Reserve pair // address of USDT: // address of POT: bool public isToken0 = true; IYuanYangPot public masterPot; constructor( IYuanYangPot _masterPot, address _uniswapPair, address _gov, uint256 _targetPrice, bool _isToken0 ) public { masterPot = _masterPot; farmHotpotBasePerBlock = masterPot.hotpotBasePerBlock(); uniswapPair = _uniswapPair; gov = _gov; targetPrice = _targetPrice; isToken0 = _isToken0; } // sets the pendingGov function setPendingGov(address _pendingGov) external onlyGov { address oldPendingGov = pendingGov; pendingGov = _pendingGov; emit NewPendingGov(oldPendingGov, _pendingGov); } // lets msg.sender accept governance function acceptGov() external { require(msg.sender == pendingGov, 'acceptGov: !pending'); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } // Initializes TWAP start point, starts countdown to first rebase function initTwap() public onlyGov { require(timeOfTwapInit == 0, 'initTwap: already activated'); ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulativeLast = isToken0 ? price0Cumulative : price1Cumulative; require(priceCumulativeLast > 0, 'initTwap: no trades'); blockTimestampLast = blockTimestamp; timeOfTwapInit = blockTimestamp; } // @notice Activates rebasing // @dev One way function, cannot be undone, callable by anyone function activateRebasing() public { require(timeOfTwapInit > 0, 'activateRebasing: twap wasnt intitiated, call init_twap()'); // cannot enable prior to end of rebaseDelay require(getNow() >= timeOfTwapInit + rebaseDelay, 'activateRebasing: !end_delay'); rebasingActive = true; } // If the latest block timestamp is within the rebase time window it, returns true. // Otherwise, returns false. function inRebaseWindow() public view returns (bool) { // rebasing is delayed until there is a liquid market require(rebasingActive, 'inRebaseWindow: rebasing not active'); uint256 nowTimestamp = getNow(); require( nowTimestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, 'inRebaseWindow: too early' ); require( nowTimestamp.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), 'inRebaseWindow: too late' ); return true; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetPrice) / targetPrice * and targetPrice is 1e18 */ function rebase() public { // no possibility of reentry as this function only invoke view functions or internal functions // or functions from master pot which also only invoke only invoke view functions or internal functions // EOA only // require(msg.sender == tx.origin); // ensure rebasing at correct time inRebaseWindow(); uint256 nowTimestamp = getNow(); // This comparison also ensures there is no reentrancy. require( lastRebaseTimestamp.add(minRebaseTimeIntervalSec) < nowTimestamp, 'rebase: Rebase already triggered' ); // Snap the rebase time to the start of this window. lastRebaseTimestamp = nowTimestamp.sub(nowTimestamp.mod(minRebaseTimeIntervalSec)).add( rebaseWindowOffsetSec ); // no safe math required epoch++; // Get twap from uniswapv2. (uint256 priceCumulative, uint32 blockTimestamp, uint256 twap) = getCurrentTwap(); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestamp; bool inCircuitBreaker = false; ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) = getNewHotpotBasePerBlock(twap); farmHotpotBasePerBlock = newFarmHotpotBasePerBlock; halvingCounter = newHalvingCounter; uint256 newRedShare = getNewRedShare(twap); // Do a bunch of things if twap is outside of threshold. if (!withinDeviationThreshold(twap)) { uint256 absoluteDeviationMovement = targetPrice.mul(deviationMovement).div(1e18); // Calculates and sets the new target rate if twap is outside of threshold. if (twap > targetPrice) { // no safe math required upwardCounter++; if (downwardCounter > 0) { downwardCounter = 0; } // if twap continues to go up, retargetThreshold is only effective for the first upward retarget // and every following rebase would retarget upward until twap is within deviation threshold if (upwardCounter >= retargetThreshold) { targetPrice = targetPrice.add(absoluteDeviationMovement); } } else { inCircuitBreaker = true; // no safe math required downwardCounter++; if (upwardCounter > 0) { upwardCounter = 0; } // if twap continues to go down, retargetThreshold is only effective for the first downward retarget // and every following rebase would retarget downward until twap is within deviation threshold if (downwardCounter >= retargetThreshold) { targetPrice = targetPrice.sub(absoluteDeviationMovement); } } } else { upwardCounter = 0; downwardCounter = 0; } masterPot.massUpdatePools(); masterPot.setHotpotBasePerBlock(newHotpotBasePerBlock); masterPot.setRedPotShare(newRedShare); masterPot.setCircuitBreaker(inCircuitBreaker); } /** * @notice Calculates TWAP from uniswap * * @dev When liquidity is low, this can be manipulated by an end of block -> next block * attack. We delay the activation of rebases 12 hours after liquidity incentives * to reduce this attack vector. Additional there is very little supply * to be able to manipulate this during that time period of highest vuln. */ function getCurrentTwap() public virtual view returns ( uint256 priceCumulative, uint32 blockTimestamp, uint256 twap ) { ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestampUniswap ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulative = isToken0 ? price0Cumulative : price1Cumulative; blockTimestamp = blockTimestampUniswap; uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulative - priceCumulativeLast) / timeElapsed) ); // 1e30 for trading pair with 6-decimal tokens. Be ultra-cautious when changing this. twap = FixedPoint.decode144(FixedPoint.mul(priceAverage, 1e30)); } // Computes new tokenPerBlock based on price. function getNewHotpotBasePerBlock(uint256 price) public view returns ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) { uint256 blockElapsed = getBlockNumber().sub(masterPot.startBlock()); newHalvingCounter = blockElapsed.div(halfLife); newFarmHotpotBasePerBlock = farmHotpotBasePerBlock; // if new halvingCounter is larger than old one, perform halving. if (newHalvingCounter > halvingCounter) { newFarmHotpotBasePerBlock = newFarmHotpotBasePerBlock.div(2); } // computes newHotpotBasePerBlock based on targetStock2Flow. newHotpotBasePerBlock = masterPot.hotpotBaseTotalSupply().div( targetStock2Flow.mul(2400000) ); // use the larger of newHotpotBasePerBlock and newFarmHotpotBasePerBlock. newHotpotBasePerBlock = newHotpotBasePerBlock > newFarmHotpotBasePerBlock ? newHotpotBasePerBlock : newFarmHotpotBasePerBlock; if (price > targetPrice) { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(price).div(targetPrice); } else { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(targetPrice).div(price); } } // Computes new redShare based on price. function getNewRedShare(uint256 price) public view returns (uint256) { return uint256(1e24).div(price.mul(1e12).div(targetPrice).add(1e12)); } // Check if the current price is within the deviation threshold for rebasing. function withinDeviationThreshold(uint256 price) public view returns (bool) { uint256 absoluteDeviationThreshold = targetPrice.mul(deviationThreshold).div(1e18); return (price >= targetPrice && price.sub(targetPrice) < absoluteDeviationThreshold) || (price < targetPrice && targetPrice.sub(price) < absoluteDeviationThreshold); } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetPrice, then no supply * modifications are made. * @param _deviationThreshold The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 _deviationThreshold) external onlyGov { require(_deviationThreshold > 0, 'deviationThreshold: too low'); uint256 oldDeviationThreshold = deviationThreshold; deviationThreshold = _deviationThreshold; emit NewDeviationThreshold(oldDeviationThreshold, _deviationThreshold); } function setDeviationMovement(uint256 _deviationMovement) external onlyGov { require(_deviationMovement > 0, 'deviationMovement: too low'); uint256 oldDeviationMovement = deviationMovement; deviationMovement = _deviationMovement; emit NewDeviationMovement(oldDeviationMovement, _deviationMovement); } // Sets the retarget threshold parameter, Gov only. function setRetargetThreshold(uint256 _retargetThreshold) external onlyGov { require(_retargetThreshold > 0, 'retargetThreshold: too low'); retargetThreshold = _retargetThreshold; } // Overwrites the target stock-to-flow ratio, Gov only. function setTargetStock2Flow(uint256 _targetStock2Flow) external onlyGov { require(_targetStock2Flow > 0, 'targetStock2Flow: too low'); targetStock2Flow = _targetStock2Flow; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param _minRebaseTimeIntervalSec More than this much time must pass between rebase * operations, in seconds. * @param _rebaseWindowOffsetSec The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param _rebaseWindowLengthSec The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 _minRebaseTimeIntervalSec, uint256 _rebaseWindowOffsetSec, uint256 _rebaseWindowLengthSec ) external onlyGov { require(_minRebaseTimeIntervalSec > 0, 'minRebaseTimeIntervalSec: too low'); require( _rebaseWindowOffsetSec < _minRebaseTimeIntervalSec, 'rebaseWindowOffsetSec: too high' ); minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec; rebaseWindowOffsetSec = _rebaseWindowOffsetSec; rebaseWindowLengthSec = _rebaseWindowLengthSec; } // Passthrough function to add pool. function addPool( uint256 _allocPoint, IERC20 _lpToken, bool _isRed, bool _withUpdate ) public onlyGov { masterPot.addPool(_allocPoint, _lpToken, _isRed, _withUpdate); } // Passthrough function to set pool. function setPool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyGov { masterPot.setPool(_pid, _allocPoint, _withUpdate); } // Passthrough function to set tip rate. function setTipRate(uint256 _tipRate) public onlyGov { masterPot.setTipRate(_tipRate); } // Passthrough function to transfer pot ownership. function transferPotOwnership(address newOwner) public onlyGov { masterPot.transferPotOwnership(newOwner); } function getNow() public virtual view returns (uint256) { return now; } function getBlockNumber() public virtual view returns (uint256) { return block.number; } }
rebase
function rebase() public { // no possibility of reentry as this function only invoke view functions or internal functions // or functions from master pot which also only invoke only invoke view functions or internal functions // EOA only // require(msg.sender == tx.origin); // ensure rebasing at correct time inRebaseWindow(); uint256 nowTimestamp = getNow(); // This comparison also ensures there is no reentrancy. require( lastRebaseTimestamp.add(minRebaseTimeIntervalSec) < nowTimestamp, 'rebase: Rebase already triggered' ); // Snap the rebase time to the start of this window. lastRebaseTimestamp = nowTimestamp.sub(nowTimestamp.mod(minRebaseTimeIntervalSec)).add( rebaseWindowOffsetSec ); // no safe math required epoch++; // Get twap from uniswapv2. (uint256 priceCumulative, uint32 blockTimestamp, uint256 twap) = getCurrentTwap(); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestamp; bool inCircuitBreaker = false; ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) = getNewHotpotBasePerBlock(twap); farmHotpotBasePerBlock = newFarmHotpotBasePerBlock; halvingCounter = newHalvingCounter; uint256 newRedShare = getNewRedShare(twap); // Do a bunch of things if twap is outside of threshold. if (!withinDeviationThreshold(twap)) { uint256 absoluteDeviationMovement = targetPrice.mul(deviationMovement).div(1e18); // Calculates and sets the new target rate if twap is outside of threshold. if (twap > targetPrice) { // no safe math required upwardCounter++; if (downwardCounter > 0) { downwardCounter = 0; } // if twap continues to go up, retargetThreshold is only effective for the first upward retarget // and every following rebase would retarget upward until twap is within deviation threshold if (upwardCounter >= retargetThreshold) { targetPrice = targetPrice.add(absoluteDeviationMovement); } } else { inCircuitBreaker = true; // no safe math required downwardCounter++; if (upwardCounter > 0) { upwardCounter = 0; } // if twap continues to go down, retargetThreshold is only effective for the first downward retarget // and every following rebase would retarget downward until twap is within deviation threshold if (downwardCounter >= retargetThreshold) { targetPrice = targetPrice.sub(absoluteDeviationMovement); } } } else { upwardCounter = 0; downwardCounter = 0; } masterPot.massUpdatePools(); masterPot.setHotpotBasePerBlock(newHotpotBasePerBlock); masterPot.setRedPotShare(newRedShare); masterPot.setCircuitBreaker(inCircuitBreaker); }
/** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetPrice) / targetPrice * and targetPrice is 1e18 */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://06c3e1b7010ded32c215d8d2b064a338aa716548f7264dc15aba4614175c048f
{ "func_code_index": [ 6331, 9134 ] }
59,656
ChefMao
contracts\ChefMao.sol
0xfbd3749eb2ed67454850939480433e71a9f5432d
Solidity
ChefMao
contract ChefMao { using SafeMath for uint256; modifier onlyGov() { require(msg.sender == gov, 'onlyGov: caller is not gov'); _; } // an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); // an event emitted when deviationMovement is changed event NewDeviationMovement(uint256 oldDeviationMovement, uint256 newDeviationMovement); // Event emitted when pendingGov is changed event NewPendingGov(address oldPendingGov, address newPendingGov); // Event emitted when gov is changed event NewGov(address oldGov, address newGov); // Governance address address public gov; // Pending Governance address address public pendingGov; // Peg target uint256 public targetPrice; // POT Tokens created per block at inception. // POT's inflation will eventually be governed by targetStock2Flow. uint256 public farmHotpotBasePerBlock; // Halving period for Hotpot Base per block, in blocks. uint256 public halfLife = 88888; // targetTokenPerBlock = totalSupply / (targetStock2Flow * 2,400,000) // 2,400,000 is ~1-year's ETH block count as of Sep 2020 // See @100trillionUSD's article below on Scarcity and S2F: // https://medium.com/@100trillionUSD/modeling-bitcoins-value-with-scarcity-91fa0fc03e25 // // Ganularity of targetStock2Flow is intentionally restricted. uint256 public targetStock2Flow = 10; // ~10% p.a. target inflation; // If the current price is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the price. // (ie) abs(price - targetPrice) / targetPrice < deviationThreshold, then no supply change. uint256 public deviationThreshold = 5e16; // 5% uint256 public deviationMovement = 5e16; // 5% // More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec = 24 hours; // Block timestamp of last rebase operation uint256 public lastRebaseTimestamp; // The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases // The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec = 3600; // 60 minutes // The number of rebase cycles since inception uint256 public epoch; // The number of halvings since inception uint256 public halvingCounter; // The number of consecutive upward threshold breaching when rebasing. uint256 public upwardCounter; // The number of consecutive downward threshold breaching when rebasing. uint256 public downwardCounter; uint256 public retargetThreshold = 2; // 2 days // rebasing is not active initially. It can be activated at T+12 hours from // deployment time // boolean showing rebase activation status bool public rebasingActive; // delays rebasing activation to facilitate liquidity uint256 public constant rebaseDelay = 12 hours; // Time of TWAP initialization uint256 public timeOfTwapInit; // pair for reserveToken <> POT address public uniswapPair; // last TWAP update time uint32 public blockTimestampLast; // last TWAP cumulative price; uint256 public priceCumulativeLast; // Whether or not this token is first in uniswap POT<>Reserve pair // address of USDT: // address of POT: bool public isToken0 = true; IYuanYangPot public masterPot; constructor( IYuanYangPot _masterPot, address _uniswapPair, address _gov, uint256 _targetPrice, bool _isToken0 ) public { masterPot = _masterPot; farmHotpotBasePerBlock = masterPot.hotpotBasePerBlock(); uniswapPair = _uniswapPair; gov = _gov; targetPrice = _targetPrice; isToken0 = _isToken0; } // sets the pendingGov function setPendingGov(address _pendingGov) external onlyGov { address oldPendingGov = pendingGov; pendingGov = _pendingGov; emit NewPendingGov(oldPendingGov, _pendingGov); } // lets msg.sender accept governance function acceptGov() external { require(msg.sender == pendingGov, 'acceptGov: !pending'); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } // Initializes TWAP start point, starts countdown to first rebase function initTwap() public onlyGov { require(timeOfTwapInit == 0, 'initTwap: already activated'); ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulativeLast = isToken0 ? price0Cumulative : price1Cumulative; require(priceCumulativeLast > 0, 'initTwap: no trades'); blockTimestampLast = blockTimestamp; timeOfTwapInit = blockTimestamp; } // @notice Activates rebasing // @dev One way function, cannot be undone, callable by anyone function activateRebasing() public { require(timeOfTwapInit > 0, 'activateRebasing: twap wasnt intitiated, call init_twap()'); // cannot enable prior to end of rebaseDelay require(getNow() >= timeOfTwapInit + rebaseDelay, 'activateRebasing: !end_delay'); rebasingActive = true; } // If the latest block timestamp is within the rebase time window it, returns true. // Otherwise, returns false. function inRebaseWindow() public view returns (bool) { // rebasing is delayed until there is a liquid market require(rebasingActive, 'inRebaseWindow: rebasing not active'); uint256 nowTimestamp = getNow(); require( nowTimestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, 'inRebaseWindow: too early' ); require( nowTimestamp.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), 'inRebaseWindow: too late' ); return true; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetPrice) / targetPrice * and targetPrice is 1e18 */ function rebase() public { // no possibility of reentry as this function only invoke view functions or internal functions // or functions from master pot which also only invoke only invoke view functions or internal functions // EOA only // require(msg.sender == tx.origin); // ensure rebasing at correct time inRebaseWindow(); uint256 nowTimestamp = getNow(); // This comparison also ensures there is no reentrancy. require( lastRebaseTimestamp.add(minRebaseTimeIntervalSec) < nowTimestamp, 'rebase: Rebase already triggered' ); // Snap the rebase time to the start of this window. lastRebaseTimestamp = nowTimestamp.sub(nowTimestamp.mod(minRebaseTimeIntervalSec)).add( rebaseWindowOffsetSec ); // no safe math required epoch++; // Get twap from uniswapv2. (uint256 priceCumulative, uint32 blockTimestamp, uint256 twap) = getCurrentTwap(); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestamp; bool inCircuitBreaker = false; ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) = getNewHotpotBasePerBlock(twap); farmHotpotBasePerBlock = newFarmHotpotBasePerBlock; halvingCounter = newHalvingCounter; uint256 newRedShare = getNewRedShare(twap); // Do a bunch of things if twap is outside of threshold. if (!withinDeviationThreshold(twap)) { uint256 absoluteDeviationMovement = targetPrice.mul(deviationMovement).div(1e18); // Calculates and sets the new target rate if twap is outside of threshold. if (twap > targetPrice) { // no safe math required upwardCounter++; if (downwardCounter > 0) { downwardCounter = 0; } // if twap continues to go up, retargetThreshold is only effective for the first upward retarget // and every following rebase would retarget upward until twap is within deviation threshold if (upwardCounter >= retargetThreshold) { targetPrice = targetPrice.add(absoluteDeviationMovement); } } else { inCircuitBreaker = true; // no safe math required downwardCounter++; if (upwardCounter > 0) { upwardCounter = 0; } // if twap continues to go down, retargetThreshold is only effective for the first downward retarget // and every following rebase would retarget downward until twap is within deviation threshold if (downwardCounter >= retargetThreshold) { targetPrice = targetPrice.sub(absoluteDeviationMovement); } } } else { upwardCounter = 0; downwardCounter = 0; } masterPot.massUpdatePools(); masterPot.setHotpotBasePerBlock(newHotpotBasePerBlock); masterPot.setRedPotShare(newRedShare); masterPot.setCircuitBreaker(inCircuitBreaker); } /** * @notice Calculates TWAP from uniswap * * @dev When liquidity is low, this can be manipulated by an end of block -> next block * attack. We delay the activation of rebases 12 hours after liquidity incentives * to reduce this attack vector. Additional there is very little supply * to be able to manipulate this during that time period of highest vuln. */ function getCurrentTwap() public virtual view returns ( uint256 priceCumulative, uint32 blockTimestamp, uint256 twap ) { ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestampUniswap ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulative = isToken0 ? price0Cumulative : price1Cumulative; blockTimestamp = blockTimestampUniswap; uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulative - priceCumulativeLast) / timeElapsed) ); // 1e30 for trading pair with 6-decimal tokens. Be ultra-cautious when changing this. twap = FixedPoint.decode144(FixedPoint.mul(priceAverage, 1e30)); } // Computes new tokenPerBlock based on price. function getNewHotpotBasePerBlock(uint256 price) public view returns ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) { uint256 blockElapsed = getBlockNumber().sub(masterPot.startBlock()); newHalvingCounter = blockElapsed.div(halfLife); newFarmHotpotBasePerBlock = farmHotpotBasePerBlock; // if new halvingCounter is larger than old one, perform halving. if (newHalvingCounter > halvingCounter) { newFarmHotpotBasePerBlock = newFarmHotpotBasePerBlock.div(2); } // computes newHotpotBasePerBlock based on targetStock2Flow. newHotpotBasePerBlock = masterPot.hotpotBaseTotalSupply().div( targetStock2Flow.mul(2400000) ); // use the larger of newHotpotBasePerBlock and newFarmHotpotBasePerBlock. newHotpotBasePerBlock = newHotpotBasePerBlock > newFarmHotpotBasePerBlock ? newHotpotBasePerBlock : newFarmHotpotBasePerBlock; if (price > targetPrice) { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(price).div(targetPrice); } else { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(targetPrice).div(price); } } // Computes new redShare based on price. function getNewRedShare(uint256 price) public view returns (uint256) { return uint256(1e24).div(price.mul(1e12).div(targetPrice).add(1e12)); } // Check if the current price is within the deviation threshold for rebasing. function withinDeviationThreshold(uint256 price) public view returns (bool) { uint256 absoluteDeviationThreshold = targetPrice.mul(deviationThreshold).div(1e18); return (price >= targetPrice && price.sub(targetPrice) < absoluteDeviationThreshold) || (price < targetPrice && targetPrice.sub(price) < absoluteDeviationThreshold); } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetPrice, then no supply * modifications are made. * @param _deviationThreshold The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 _deviationThreshold) external onlyGov { require(_deviationThreshold > 0, 'deviationThreshold: too low'); uint256 oldDeviationThreshold = deviationThreshold; deviationThreshold = _deviationThreshold; emit NewDeviationThreshold(oldDeviationThreshold, _deviationThreshold); } function setDeviationMovement(uint256 _deviationMovement) external onlyGov { require(_deviationMovement > 0, 'deviationMovement: too low'); uint256 oldDeviationMovement = deviationMovement; deviationMovement = _deviationMovement; emit NewDeviationMovement(oldDeviationMovement, _deviationMovement); } // Sets the retarget threshold parameter, Gov only. function setRetargetThreshold(uint256 _retargetThreshold) external onlyGov { require(_retargetThreshold > 0, 'retargetThreshold: too low'); retargetThreshold = _retargetThreshold; } // Overwrites the target stock-to-flow ratio, Gov only. function setTargetStock2Flow(uint256 _targetStock2Flow) external onlyGov { require(_targetStock2Flow > 0, 'targetStock2Flow: too low'); targetStock2Flow = _targetStock2Flow; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param _minRebaseTimeIntervalSec More than this much time must pass between rebase * operations, in seconds. * @param _rebaseWindowOffsetSec The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param _rebaseWindowLengthSec The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 _minRebaseTimeIntervalSec, uint256 _rebaseWindowOffsetSec, uint256 _rebaseWindowLengthSec ) external onlyGov { require(_minRebaseTimeIntervalSec > 0, 'minRebaseTimeIntervalSec: too low'); require( _rebaseWindowOffsetSec < _minRebaseTimeIntervalSec, 'rebaseWindowOffsetSec: too high' ); minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec; rebaseWindowOffsetSec = _rebaseWindowOffsetSec; rebaseWindowLengthSec = _rebaseWindowLengthSec; } // Passthrough function to add pool. function addPool( uint256 _allocPoint, IERC20 _lpToken, bool _isRed, bool _withUpdate ) public onlyGov { masterPot.addPool(_allocPoint, _lpToken, _isRed, _withUpdate); } // Passthrough function to set pool. function setPool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyGov { masterPot.setPool(_pid, _allocPoint, _withUpdate); } // Passthrough function to set tip rate. function setTipRate(uint256 _tipRate) public onlyGov { masterPot.setTipRate(_tipRate); } // Passthrough function to transfer pot ownership. function transferPotOwnership(address newOwner) public onlyGov { masterPot.transferPotOwnership(newOwner); } function getNow() public virtual view returns (uint256) { return now; } function getBlockNumber() public virtual view returns (uint256) { return block.number; } }
getCurrentTwap
function getCurrentTwap() public virtual view returns ( uint256 priceCumulative, uint32 blockTimestamp, uint256 twap ) { ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestampUniswap ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulative = isToken0 ? price0Cumulative : price1Cumulative; blockTimestamp = blockTimestampUniswap; uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulative - priceCumulativeLast) / timeElapsed) ); // 1e30 for trading pair with 6-decimal tokens. Be ultra-cautious when changing this. twap = FixedPoint.decode144(FixedPoint.mul(priceAverage, 1e30)); }
/** * @notice Calculates TWAP from uniswap * * @dev When liquidity is low, this can be manipulated by an end of block -> next block * attack. We delay the activation of rebases 12 hours after liquidity incentives * to reduce this attack vector. Additional there is very little supply * to be able to manipulate this during that time period of highest vuln. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://06c3e1b7010ded32c215d8d2b064a338aa716548f7264dc15aba4614175c048f
{ "func_code_index": [ 9535, 10571 ] }
59,657
ChefMao
contracts\ChefMao.sol
0xfbd3749eb2ed67454850939480433e71a9f5432d
Solidity
ChefMao
contract ChefMao { using SafeMath for uint256; modifier onlyGov() { require(msg.sender == gov, 'onlyGov: caller is not gov'); _; } // an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); // an event emitted when deviationMovement is changed event NewDeviationMovement(uint256 oldDeviationMovement, uint256 newDeviationMovement); // Event emitted when pendingGov is changed event NewPendingGov(address oldPendingGov, address newPendingGov); // Event emitted when gov is changed event NewGov(address oldGov, address newGov); // Governance address address public gov; // Pending Governance address address public pendingGov; // Peg target uint256 public targetPrice; // POT Tokens created per block at inception. // POT's inflation will eventually be governed by targetStock2Flow. uint256 public farmHotpotBasePerBlock; // Halving period for Hotpot Base per block, in blocks. uint256 public halfLife = 88888; // targetTokenPerBlock = totalSupply / (targetStock2Flow * 2,400,000) // 2,400,000 is ~1-year's ETH block count as of Sep 2020 // See @100trillionUSD's article below on Scarcity and S2F: // https://medium.com/@100trillionUSD/modeling-bitcoins-value-with-scarcity-91fa0fc03e25 // // Ganularity of targetStock2Flow is intentionally restricted. uint256 public targetStock2Flow = 10; // ~10% p.a. target inflation; // If the current price is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the price. // (ie) abs(price - targetPrice) / targetPrice < deviationThreshold, then no supply change. uint256 public deviationThreshold = 5e16; // 5% uint256 public deviationMovement = 5e16; // 5% // More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec = 24 hours; // Block timestamp of last rebase operation uint256 public lastRebaseTimestamp; // The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases // The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec = 3600; // 60 minutes // The number of rebase cycles since inception uint256 public epoch; // The number of halvings since inception uint256 public halvingCounter; // The number of consecutive upward threshold breaching when rebasing. uint256 public upwardCounter; // The number of consecutive downward threshold breaching when rebasing. uint256 public downwardCounter; uint256 public retargetThreshold = 2; // 2 days // rebasing is not active initially. It can be activated at T+12 hours from // deployment time // boolean showing rebase activation status bool public rebasingActive; // delays rebasing activation to facilitate liquidity uint256 public constant rebaseDelay = 12 hours; // Time of TWAP initialization uint256 public timeOfTwapInit; // pair for reserveToken <> POT address public uniswapPair; // last TWAP update time uint32 public blockTimestampLast; // last TWAP cumulative price; uint256 public priceCumulativeLast; // Whether or not this token is first in uniswap POT<>Reserve pair // address of USDT: // address of POT: bool public isToken0 = true; IYuanYangPot public masterPot; constructor( IYuanYangPot _masterPot, address _uniswapPair, address _gov, uint256 _targetPrice, bool _isToken0 ) public { masterPot = _masterPot; farmHotpotBasePerBlock = masterPot.hotpotBasePerBlock(); uniswapPair = _uniswapPair; gov = _gov; targetPrice = _targetPrice; isToken0 = _isToken0; } // sets the pendingGov function setPendingGov(address _pendingGov) external onlyGov { address oldPendingGov = pendingGov; pendingGov = _pendingGov; emit NewPendingGov(oldPendingGov, _pendingGov); } // lets msg.sender accept governance function acceptGov() external { require(msg.sender == pendingGov, 'acceptGov: !pending'); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } // Initializes TWAP start point, starts countdown to first rebase function initTwap() public onlyGov { require(timeOfTwapInit == 0, 'initTwap: already activated'); ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulativeLast = isToken0 ? price0Cumulative : price1Cumulative; require(priceCumulativeLast > 0, 'initTwap: no trades'); blockTimestampLast = blockTimestamp; timeOfTwapInit = blockTimestamp; } // @notice Activates rebasing // @dev One way function, cannot be undone, callable by anyone function activateRebasing() public { require(timeOfTwapInit > 0, 'activateRebasing: twap wasnt intitiated, call init_twap()'); // cannot enable prior to end of rebaseDelay require(getNow() >= timeOfTwapInit + rebaseDelay, 'activateRebasing: !end_delay'); rebasingActive = true; } // If the latest block timestamp is within the rebase time window it, returns true. // Otherwise, returns false. function inRebaseWindow() public view returns (bool) { // rebasing is delayed until there is a liquid market require(rebasingActive, 'inRebaseWindow: rebasing not active'); uint256 nowTimestamp = getNow(); require( nowTimestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, 'inRebaseWindow: too early' ); require( nowTimestamp.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), 'inRebaseWindow: too late' ); return true; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetPrice) / targetPrice * and targetPrice is 1e18 */ function rebase() public { // no possibility of reentry as this function only invoke view functions or internal functions // or functions from master pot which also only invoke only invoke view functions or internal functions // EOA only // require(msg.sender == tx.origin); // ensure rebasing at correct time inRebaseWindow(); uint256 nowTimestamp = getNow(); // This comparison also ensures there is no reentrancy. require( lastRebaseTimestamp.add(minRebaseTimeIntervalSec) < nowTimestamp, 'rebase: Rebase already triggered' ); // Snap the rebase time to the start of this window. lastRebaseTimestamp = nowTimestamp.sub(nowTimestamp.mod(minRebaseTimeIntervalSec)).add( rebaseWindowOffsetSec ); // no safe math required epoch++; // Get twap from uniswapv2. (uint256 priceCumulative, uint32 blockTimestamp, uint256 twap) = getCurrentTwap(); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestamp; bool inCircuitBreaker = false; ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) = getNewHotpotBasePerBlock(twap); farmHotpotBasePerBlock = newFarmHotpotBasePerBlock; halvingCounter = newHalvingCounter; uint256 newRedShare = getNewRedShare(twap); // Do a bunch of things if twap is outside of threshold. if (!withinDeviationThreshold(twap)) { uint256 absoluteDeviationMovement = targetPrice.mul(deviationMovement).div(1e18); // Calculates and sets the new target rate if twap is outside of threshold. if (twap > targetPrice) { // no safe math required upwardCounter++; if (downwardCounter > 0) { downwardCounter = 0; } // if twap continues to go up, retargetThreshold is only effective for the first upward retarget // and every following rebase would retarget upward until twap is within deviation threshold if (upwardCounter >= retargetThreshold) { targetPrice = targetPrice.add(absoluteDeviationMovement); } } else { inCircuitBreaker = true; // no safe math required downwardCounter++; if (upwardCounter > 0) { upwardCounter = 0; } // if twap continues to go down, retargetThreshold is only effective for the first downward retarget // and every following rebase would retarget downward until twap is within deviation threshold if (downwardCounter >= retargetThreshold) { targetPrice = targetPrice.sub(absoluteDeviationMovement); } } } else { upwardCounter = 0; downwardCounter = 0; } masterPot.massUpdatePools(); masterPot.setHotpotBasePerBlock(newHotpotBasePerBlock); masterPot.setRedPotShare(newRedShare); masterPot.setCircuitBreaker(inCircuitBreaker); } /** * @notice Calculates TWAP from uniswap * * @dev When liquidity is low, this can be manipulated by an end of block -> next block * attack. We delay the activation of rebases 12 hours after liquidity incentives * to reduce this attack vector. Additional there is very little supply * to be able to manipulate this during that time period of highest vuln. */ function getCurrentTwap() public virtual view returns ( uint256 priceCumulative, uint32 blockTimestamp, uint256 twap ) { ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestampUniswap ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulative = isToken0 ? price0Cumulative : price1Cumulative; blockTimestamp = blockTimestampUniswap; uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulative - priceCumulativeLast) / timeElapsed) ); // 1e30 for trading pair with 6-decimal tokens. Be ultra-cautious when changing this. twap = FixedPoint.decode144(FixedPoint.mul(priceAverage, 1e30)); } // Computes new tokenPerBlock based on price. function getNewHotpotBasePerBlock(uint256 price) public view returns ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) { uint256 blockElapsed = getBlockNumber().sub(masterPot.startBlock()); newHalvingCounter = blockElapsed.div(halfLife); newFarmHotpotBasePerBlock = farmHotpotBasePerBlock; // if new halvingCounter is larger than old one, perform halving. if (newHalvingCounter > halvingCounter) { newFarmHotpotBasePerBlock = newFarmHotpotBasePerBlock.div(2); } // computes newHotpotBasePerBlock based on targetStock2Flow. newHotpotBasePerBlock = masterPot.hotpotBaseTotalSupply().div( targetStock2Flow.mul(2400000) ); // use the larger of newHotpotBasePerBlock and newFarmHotpotBasePerBlock. newHotpotBasePerBlock = newHotpotBasePerBlock > newFarmHotpotBasePerBlock ? newHotpotBasePerBlock : newFarmHotpotBasePerBlock; if (price > targetPrice) { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(price).div(targetPrice); } else { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(targetPrice).div(price); } } // Computes new redShare based on price. function getNewRedShare(uint256 price) public view returns (uint256) { return uint256(1e24).div(price.mul(1e12).div(targetPrice).add(1e12)); } // Check if the current price is within the deviation threshold for rebasing. function withinDeviationThreshold(uint256 price) public view returns (bool) { uint256 absoluteDeviationThreshold = targetPrice.mul(deviationThreshold).div(1e18); return (price >= targetPrice && price.sub(targetPrice) < absoluteDeviationThreshold) || (price < targetPrice && targetPrice.sub(price) < absoluteDeviationThreshold); } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetPrice, then no supply * modifications are made. * @param _deviationThreshold The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 _deviationThreshold) external onlyGov { require(_deviationThreshold > 0, 'deviationThreshold: too low'); uint256 oldDeviationThreshold = deviationThreshold; deviationThreshold = _deviationThreshold; emit NewDeviationThreshold(oldDeviationThreshold, _deviationThreshold); } function setDeviationMovement(uint256 _deviationMovement) external onlyGov { require(_deviationMovement > 0, 'deviationMovement: too low'); uint256 oldDeviationMovement = deviationMovement; deviationMovement = _deviationMovement; emit NewDeviationMovement(oldDeviationMovement, _deviationMovement); } // Sets the retarget threshold parameter, Gov only. function setRetargetThreshold(uint256 _retargetThreshold) external onlyGov { require(_retargetThreshold > 0, 'retargetThreshold: too low'); retargetThreshold = _retargetThreshold; } // Overwrites the target stock-to-flow ratio, Gov only. function setTargetStock2Flow(uint256 _targetStock2Flow) external onlyGov { require(_targetStock2Flow > 0, 'targetStock2Flow: too low'); targetStock2Flow = _targetStock2Flow; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param _minRebaseTimeIntervalSec More than this much time must pass between rebase * operations, in seconds. * @param _rebaseWindowOffsetSec The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param _rebaseWindowLengthSec The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 _minRebaseTimeIntervalSec, uint256 _rebaseWindowOffsetSec, uint256 _rebaseWindowLengthSec ) external onlyGov { require(_minRebaseTimeIntervalSec > 0, 'minRebaseTimeIntervalSec: too low'); require( _rebaseWindowOffsetSec < _minRebaseTimeIntervalSec, 'rebaseWindowOffsetSec: too high' ); minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec; rebaseWindowOffsetSec = _rebaseWindowOffsetSec; rebaseWindowLengthSec = _rebaseWindowLengthSec; } // Passthrough function to add pool. function addPool( uint256 _allocPoint, IERC20 _lpToken, bool _isRed, bool _withUpdate ) public onlyGov { masterPot.addPool(_allocPoint, _lpToken, _isRed, _withUpdate); } // Passthrough function to set pool. function setPool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyGov { masterPot.setPool(_pid, _allocPoint, _withUpdate); } // Passthrough function to set tip rate. function setTipRate(uint256 _tipRate) public onlyGov { masterPot.setTipRate(_tipRate); } // Passthrough function to transfer pot ownership. function transferPotOwnership(address newOwner) public onlyGov { masterPot.transferPotOwnership(newOwner); } function getNow() public virtual view returns (uint256) { return now; } function getBlockNumber() public virtual view returns (uint256) { return block.number; } }
getNewHotpotBasePerBlock
function getNewHotpotBasePerBlock(uint256 price) public view returns ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) { uint256 blockElapsed = getBlockNumber().sub(masterPot.startBlock()); newHalvingCounter = blockElapsed.div(halfLife); newFarmHotpotBasePerBlock = farmHotpotBasePerBlock; // if new halvingCounter is larger than old one, perform halving. if (newHalvingCounter > halvingCounter) { newFarmHotpotBasePerBlock = newFarmHotpotBasePerBlock.div(2); } // computes newHotpotBasePerBlock based on targetStock2Flow. newHotpotBasePerBlock = masterPot.hotpotBaseTotalSupply().div( targetStock2Flow.mul(2400000) ); // use the larger of newHotpotBasePerBlock and newFarmHotpotBasePerBlock. newHotpotBasePerBlock = newHotpotBasePerBlock > newFarmHotpotBasePerBlock ? newHotpotBasePerBlock : newFarmHotpotBasePerBlock; if (price > targetPrice) { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(price).div(targetPrice); } else { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(targetPrice).div(price); } }
// Computes new tokenPerBlock based on price.
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://06c3e1b7010ded32c215d8d2b064a338aa716548f7264dc15aba4614175c048f
{ "func_code_index": [ 10622, 11781 ] }
59,658
ChefMao
contracts\ChefMao.sol
0xfbd3749eb2ed67454850939480433e71a9f5432d
Solidity
ChefMao
contract ChefMao { using SafeMath for uint256; modifier onlyGov() { require(msg.sender == gov, 'onlyGov: caller is not gov'); _; } // an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); // an event emitted when deviationMovement is changed event NewDeviationMovement(uint256 oldDeviationMovement, uint256 newDeviationMovement); // Event emitted when pendingGov is changed event NewPendingGov(address oldPendingGov, address newPendingGov); // Event emitted when gov is changed event NewGov(address oldGov, address newGov); // Governance address address public gov; // Pending Governance address address public pendingGov; // Peg target uint256 public targetPrice; // POT Tokens created per block at inception. // POT's inflation will eventually be governed by targetStock2Flow. uint256 public farmHotpotBasePerBlock; // Halving period for Hotpot Base per block, in blocks. uint256 public halfLife = 88888; // targetTokenPerBlock = totalSupply / (targetStock2Flow * 2,400,000) // 2,400,000 is ~1-year's ETH block count as of Sep 2020 // See @100trillionUSD's article below on Scarcity and S2F: // https://medium.com/@100trillionUSD/modeling-bitcoins-value-with-scarcity-91fa0fc03e25 // // Ganularity of targetStock2Flow is intentionally restricted. uint256 public targetStock2Flow = 10; // ~10% p.a. target inflation; // If the current price is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the price. // (ie) abs(price - targetPrice) / targetPrice < deviationThreshold, then no supply change. uint256 public deviationThreshold = 5e16; // 5% uint256 public deviationMovement = 5e16; // 5% // More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec = 24 hours; // Block timestamp of last rebase operation uint256 public lastRebaseTimestamp; // The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases // The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec = 3600; // 60 minutes // The number of rebase cycles since inception uint256 public epoch; // The number of halvings since inception uint256 public halvingCounter; // The number of consecutive upward threshold breaching when rebasing. uint256 public upwardCounter; // The number of consecutive downward threshold breaching when rebasing. uint256 public downwardCounter; uint256 public retargetThreshold = 2; // 2 days // rebasing is not active initially. It can be activated at T+12 hours from // deployment time // boolean showing rebase activation status bool public rebasingActive; // delays rebasing activation to facilitate liquidity uint256 public constant rebaseDelay = 12 hours; // Time of TWAP initialization uint256 public timeOfTwapInit; // pair for reserveToken <> POT address public uniswapPair; // last TWAP update time uint32 public blockTimestampLast; // last TWAP cumulative price; uint256 public priceCumulativeLast; // Whether or not this token is first in uniswap POT<>Reserve pair // address of USDT: // address of POT: bool public isToken0 = true; IYuanYangPot public masterPot; constructor( IYuanYangPot _masterPot, address _uniswapPair, address _gov, uint256 _targetPrice, bool _isToken0 ) public { masterPot = _masterPot; farmHotpotBasePerBlock = masterPot.hotpotBasePerBlock(); uniswapPair = _uniswapPair; gov = _gov; targetPrice = _targetPrice; isToken0 = _isToken0; } // sets the pendingGov function setPendingGov(address _pendingGov) external onlyGov { address oldPendingGov = pendingGov; pendingGov = _pendingGov; emit NewPendingGov(oldPendingGov, _pendingGov); } // lets msg.sender accept governance function acceptGov() external { require(msg.sender == pendingGov, 'acceptGov: !pending'); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } // Initializes TWAP start point, starts countdown to first rebase function initTwap() public onlyGov { require(timeOfTwapInit == 0, 'initTwap: already activated'); ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulativeLast = isToken0 ? price0Cumulative : price1Cumulative; require(priceCumulativeLast > 0, 'initTwap: no trades'); blockTimestampLast = blockTimestamp; timeOfTwapInit = blockTimestamp; } // @notice Activates rebasing // @dev One way function, cannot be undone, callable by anyone function activateRebasing() public { require(timeOfTwapInit > 0, 'activateRebasing: twap wasnt intitiated, call init_twap()'); // cannot enable prior to end of rebaseDelay require(getNow() >= timeOfTwapInit + rebaseDelay, 'activateRebasing: !end_delay'); rebasingActive = true; } // If the latest block timestamp is within the rebase time window it, returns true. // Otherwise, returns false. function inRebaseWindow() public view returns (bool) { // rebasing is delayed until there is a liquid market require(rebasingActive, 'inRebaseWindow: rebasing not active'); uint256 nowTimestamp = getNow(); require( nowTimestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, 'inRebaseWindow: too early' ); require( nowTimestamp.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), 'inRebaseWindow: too late' ); return true; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetPrice) / targetPrice * and targetPrice is 1e18 */ function rebase() public { // no possibility of reentry as this function only invoke view functions or internal functions // or functions from master pot which also only invoke only invoke view functions or internal functions // EOA only // require(msg.sender == tx.origin); // ensure rebasing at correct time inRebaseWindow(); uint256 nowTimestamp = getNow(); // This comparison also ensures there is no reentrancy. require( lastRebaseTimestamp.add(minRebaseTimeIntervalSec) < nowTimestamp, 'rebase: Rebase already triggered' ); // Snap the rebase time to the start of this window. lastRebaseTimestamp = nowTimestamp.sub(nowTimestamp.mod(minRebaseTimeIntervalSec)).add( rebaseWindowOffsetSec ); // no safe math required epoch++; // Get twap from uniswapv2. (uint256 priceCumulative, uint32 blockTimestamp, uint256 twap) = getCurrentTwap(); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestamp; bool inCircuitBreaker = false; ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) = getNewHotpotBasePerBlock(twap); farmHotpotBasePerBlock = newFarmHotpotBasePerBlock; halvingCounter = newHalvingCounter; uint256 newRedShare = getNewRedShare(twap); // Do a bunch of things if twap is outside of threshold. if (!withinDeviationThreshold(twap)) { uint256 absoluteDeviationMovement = targetPrice.mul(deviationMovement).div(1e18); // Calculates and sets the new target rate if twap is outside of threshold. if (twap > targetPrice) { // no safe math required upwardCounter++; if (downwardCounter > 0) { downwardCounter = 0; } // if twap continues to go up, retargetThreshold is only effective for the first upward retarget // and every following rebase would retarget upward until twap is within deviation threshold if (upwardCounter >= retargetThreshold) { targetPrice = targetPrice.add(absoluteDeviationMovement); } } else { inCircuitBreaker = true; // no safe math required downwardCounter++; if (upwardCounter > 0) { upwardCounter = 0; } // if twap continues to go down, retargetThreshold is only effective for the first downward retarget // and every following rebase would retarget downward until twap is within deviation threshold if (downwardCounter >= retargetThreshold) { targetPrice = targetPrice.sub(absoluteDeviationMovement); } } } else { upwardCounter = 0; downwardCounter = 0; } masterPot.massUpdatePools(); masterPot.setHotpotBasePerBlock(newHotpotBasePerBlock); masterPot.setRedPotShare(newRedShare); masterPot.setCircuitBreaker(inCircuitBreaker); } /** * @notice Calculates TWAP from uniswap * * @dev When liquidity is low, this can be manipulated by an end of block -> next block * attack. We delay the activation of rebases 12 hours after liquidity incentives * to reduce this attack vector. Additional there is very little supply * to be able to manipulate this during that time period of highest vuln. */ function getCurrentTwap() public virtual view returns ( uint256 priceCumulative, uint32 blockTimestamp, uint256 twap ) { ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestampUniswap ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulative = isToken0 ? price0Cumulative : price1Cumulative; blockTimestamp = blockTimestampUniswap; uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulative - priceCumulativeLast) / timeElapsed) ); // 1e30 for trading pair with 6-decimal tokens. Be ultra-cautious when changing this. twap = FixedPoint.decode144(FixedPoint.mul(priceAverage, 1e30)); } // Computes new tokenPerBlock based on price. function getNewHotpotBasePerBlock(uint256 price) public view returns ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) { uint256 blockElapsed = getBlockNumber().sub(masterPot.startBlock()); newHalvingCounter = blockElapsed.div(halfLife); newFarmHotpotBasePerBlock = farmHotpotBasePerBlock; // if new halvingCounter is larger than old one, perform halving. if (newHalvingCounter > halvingCounter) { newFarmHotpotBasePerBlock = newFarmHotpotBasePerBlock.div(2); } // computes newHotpotBasePerBlock based on targetStock2Flow. newHotpotBasePerBlock = masterPot.hotpotBaseTotalSupply().div( targetStock2Flow.mul(2400000) ); // use the larger of newHotpotBasePerBlock and newFarmHotpotBasePerBlock. newHotpotBasePerBlock = newHotpotBasePerBlock > newFarmHotpotBasePerBlock ? newHotpotBasePerBlock : newFarmHotpotBasePerBlock; if (price > targetPrice) { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(price).div(targetPrice); } else { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(targetPrice).div(price); } } // Computes new redShare based on price. function getNewRedShare(uint256 price) public view returns (uint256) { return uint256(1e24).div(price.mul(1e12).div(targetPrice).add(1e12)); } // Check if the current price is within the deviation threshold for rebasing. function withinDeviationThreshold(uint256 price) public view returns (bool) { uint256 absoluteDeviationThreshold = targetPrice.mul(deviationThreshold).div(1e18); return (price >= targetPrice && price.sub(targetPrice) < absoluteDeviationThreshold) || (price < targetPrice && targetPrice.sub(price) < absoluteDeviationThreshold); } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetPrice, then no supply * modifications are made. * @param _deviationThreshold The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 _deviationThreshold) external onlyGov { require(_deviationThreshold > 0, 'deviationThreshold: too low'); uint256 oldDeviationThreshold = deviationThreshold; deviationThreshold = _deviationThreshold; emit NewDeviationThreshold(oldDeviationThreshold, _deviationThreshold); } function setDeviationMovement(uint256 _deviationMovement) external onlyGov { require(_deviationMovement > 0, 'deviationMovement: too low'); uint256 oldDeviationMovement = deviationMovement; deviationMovement = _deviationMovement; emit NewDeviationMovement(oldDeviationMovement, _deviationMovement); } // Sets the retarget threshold parameter, Gov only. function setRetargetThreshold(uint256 _retargetThreshold) external onlyGov { require(_retargetThreshold > 0, 'retargetThreshold: too low'); retargetThreshold = _retargetThreshold; } // Overwrites the target stock-to-flow ratio, Gov only. function setTargetStock2Flow(uint256 _targetStock2Flow) external onlyGov { require(_targetStock2Flow > 0, 'targetStock2Flow: too low'); targetStock2Flow = _targetStock2Flow; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param _minRebaseTimeIntervalSec More than this much time must pass between rebase * operations, in seconds. * @param _rebaseWindowOffsetSec The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param _rebaseWindowLengthSec The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 _minRebaseTimeIntervalSec, uint256 _rebaseWindowOffsetSec, uint256 _rebaseWindowLengthSec ) external onlyGov { require(_minRebaseTimeIntervalSec > 0, 'minRebaseTimeIntervalSec: too low'); require( _rebaseWindowOffsetSec < _minRebaseTimeIntervalSec, 'rebaseWindowOffsetSec: too high' ); minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec; rebaseWindowOffsetSec = _rebaseWindowOffsetSec; rebaseWindowLengthSec = _rebaseWindowLengthSec; } // Passthrough function to add pool. function addPool( uint256 _allocPoint, IERC20 _lpToken, bool _isRed, bool _withUpdate ) public onlyGov { masterPot.addPool(_allocPoint, _lpToken, _isRed, _withUpdate); } // Passthrough function to set pool. function setPool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyGov { masterPot.setPool(_pid, _allocPoint, _withUpdate); } // Passthrough function to set tip rate. function setTipRate(uint256 _tipRate) public onlyGov { masterPot.setTipRate(_tipRate); } // Passthrough function to transfer pot ownership. function transferPotOwnership(address newOwner) public onlyGov { masterPot.transferPotOwnership(newOwner); } function getNow() public virtual view returns (uint256) { return now; } function getBlockNumber() public virtual view returns (uint256) { return block.number; } }
getNewRedShare
function getNewRedShare(uint256 price) public view returns (uint256) { return uint256(1e24).div(price.mul(1e12).div(targetPrice).add(1e12)); }
// Computes new redShare based on price.
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://06c3e1b7010ded32c215d8d2b064a338aa716548f7264dc15aba4614175c048f
{ "func_code_index": [ 11827, 11976 ] }
59,659
ChefMao
contracts\ChefMao.sol
0xfbd3749eb2ed67454850939480433e71a9f5432d
Solidity
ChefMao
contract ChefMao { using SafeMath for uint256; modifier onlyGov() { require(msg.sender == gov, 'onlyGov: caller is not gov'); _; } // an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); // an event emitted when deviationMovement is changed event NewDeviationMovement(uint256 oldDeviationMovement, uint256 newDeviationMovement); // Event emitted when pendingGov is changed event NewPendingGov(address oldPendingGov, address newPendingGov); // Event emitted when gov is changed event NewGov(address oldGov, address newGov); // Governance address address public gov; // Pending Governance address address public pendingGov; // Peg target uint256 public targetPrice; // POT Tokens created per block at inception. // POT's inflation will eventually be governed by targetStock2Flow. uint256 public farmHotpotBasePerBlock; // Halving period for Hotpot Base per block, in blocks. uint256 public halfLife = 88888; // targetTokenPerBlock = totalSupply / (targetStock2Flow * 2,400,000) // 2,400,000 is ~1-year's ETH block count as of Sep 2020 // See @100trillionUSD's article below on Scarcity and S2F: // https://medium.com/@100trillionUSD/modeling-bitcoins-value-with-scarcity-91fa0fc03e25 // // Ganularity of targetStock2Flow is intentionally restricted. uint256 public targetStock2Flow = 10; // ~10% p.a. target inflation; // If the current price is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the price. // (ie) abs(price - targetPrice) / targetPrice < deviationThreshold, then no supply change. uint256 public deviationThreshold = 5e16; // 5% uint256 public deviationMovement = 5e16; // 5% // More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec = 24 hours; // Block timestamp of last rebase operation uint256 public lastRebaseTimestamp; // The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec = 28800; // 8am/8pm UTC rebases // The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec = 3600; // 60 minutes // The number of rebase cycles since inception uint256 public epoch; // The number of halvings since inception uint256 public halvingCounter; // The number of consecutive upward threshold breaching when rebasing. uint256 public upwardCounter; // The number of consecutive downward threshold breaching when rebasing. uint256 public downwardCounter; uint256 public retargetThreshold = 2; // 2 days // rebasing is not active initially. It can be activated at T+12 hours from // deployment time // boolean showing rebase activation status bool public rebasingActive; // delays rebasing activation to facilitate liquidity uint256 public constant rebaseDelay = 12 hours; // Time of TWAP initialization uint256 public timeOfTwapInit; // pair for reserveToken <> POT address public uniswapPair; // last TWAP update time uint32 public blockTimestampLast; // last TWAP cumulative price; uint256 public priceCumulativeLast; // Whether or not this token is first in uniswap POT<>Reserve pair // address of USDT: // address of POT: bool public isToken0 = true; IYuanYangPot public masterPot; constructor( IYuanYangPot _masterPot, address _uniswapPair, address _gov, uint256 _targetPrice, bool _isToken0 ) public { masterPot = _masterPot; farmHotpotBasePerBlock = masterPot.hotpotBasePerBlock(); uniswapPair = _uniswapPair; gov = _gov; targetPrice = _targetPrice; isToken0 = _isToken0; } // sets the pendingGov function setPendingGov(address _pendingGov) external onlyGov { address oldPendingGov = pendingGov; pendingGov = _pendingGov; emit NewPendingGov(oldPendingGov, _pendingGov); } // lets msg.sender accept governance function acceptGov() external { require(msg.sender == pendingGov, 'acceptGov: !pending'); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } // Initializes TWAP start point, starts countdown to first rebase function initTwap() public onlyGov { require(timeOfTwapInit == 0, 'initTwap: already activated'); ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulativeLast = isToken0 ? price0Cumulative : price1Cumulative; require(priceCumulativeLast > 0, 'initTwap: no trades'); blockTimestampLast = blockTimestamp; timeOfTwapInit = blockTimestamp; } // @notice Activates rebasing // @dev One way function, cannot be undone, callable by anyone function activateRebasing() public { require(timeOfTwapInit > 0, 'activateRebasing: twap wasnt intitiated, call init_twap()'); // cannot enable prior to end of rebaseDelay require(getNow() >= timeOfTwapInit + rebaseDelay, 'activateRebasing: !end_delay'); rebasingActive = true; } // If the latest block timestamp is within the rebase time window it, returns true. // Otherwise, returns false. function inRebaseWindow() public view returns (bool) { // rebasing is delayed until there is a liquid market require(rebasingActive, 'inRebaseWindow: rebasing not active'); uint256 nowTimestamp = getNow(); require( nowTimestamp.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, 'inRebaseWindow: too early' ); require( nowTimestamp.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), 'inRebaseWindow: too late' ); return true; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetPrice) / targetPrice * and targetPrice is 1e18 */ function rebase() public { // no possibility of reentry as this function only invoke view functions or internal functions // or functions from master pot which also only invoke only invoke view functions or internal functions // EOA only // require(msg.sender == tx.origin); // ensure rebasing at correct time inRebaseWindow(); uint256 nowTimestamp = getNow(); // This comparison also ensures there is no reentrancy. require( lastRebaseTimestamp.add(minRebaseTimeIntervalSec) < nowTimestamp, 'rebase: Rebase already triggered' ); // Snap the rebase time to the start of this window. lastRebaseTimestamp = nowTimestamp.sub(nowTimestamp.mod(minRebaseTimeIntervalSec)).add( rebaseWindowOffsetSec ); // no safe math required epoch++; // Get twap from uniswapv2. (uint256 priceCumulative, uint32 blockTimestamp, uint256 twap) = getCurrentTwap(); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestamp; bool inCircuitBreaker = false; ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) = getNewHotpotBasePerBlock(twap); farmHotpotBasePerBlock = newFarmHotpotBasePerBlock; halvingCounter = newHalvingCounter; uint256 newRedShare = getNewRedShare(twap); // Do a bunch of things if twap is outside of threshold. if (!withinDeviationThreshold(twap)) { uint256 absoluteDeviationMovement = targetPrice.mul(deviationMovement).div(1e18); // Calculates and sets the new target rate if twap is outside of threshold. if (twap > targetPrice) { // no safe math required upwardCounter++; if (downwardCounter > 0) { downwardCounter = 0; } // if twap continues to go up, retargetThreshold is only effective for the first upward retarget // and every following rebase would retarget upward until twap is within deviation threshold if (upwardCounter >= retargetThreshold) { targetPrice = targetPrice.add(absoluteDeviationMovement); } } else { inCircuitBreaker = true; // no safe math required downwardCounter++; if (upwardCounter > 0) { upwardCounter = 0; } // if twap continues to go down, retargetThreshold is only effective for the first downward retarget // and every following rebase would retarget downward until twap is within deviation threshold if (downwardCounter >= retargetThreshold) { targetPrice = targetPrice.sub(absoluteDeviationMovement); } } } else { upwardCounter = 0; downwardCounter = 0; } masterPot.massUpdatePools(); masterPot.setHotpotBasePerBlock(newHotpotBasePerBlock); masterPot.setRedPotShare(newRedShare); masterPot.setCircuitBreaker(inCircuitBreaker); } /** * @notice Calculates TWAP from uniswap * * @dev When liquidity is low, this can be manipulated by an end of block -> next block * attack. We delay the activation of rebases 12 hours after liquidity incentives * to reduce this attack vector. Additional there is very little supply * to be able to manipulate this during that time period of highest vuln. */ function getCurrentTwap() public virtual view returns ( uint256 priceCumulative, uint32 blockTimestamp, uint256 twap ) { ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestampUniswap ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair); priceCumulative = isToken0 ? price0Cumulative : price1Cumulative; blockTimestamp = blockTimestampUniswap; uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulative - priceCumulativeLast) / timeElapsed) ); // 1e30 for trading pair with 6-decimal tokens. Be ultra-cautious when changing this. twap = FixedPoint.decode144(FixedPoint.mul(priceAverage, 1e30)); } // Computes new tokenPerBlock based on price. function getNewHotpotBasePerBlock(uint256 price) public view returns ( uint256 newHotpotBasePerBlock, uint256 newFarmHotpotBasePerBlock, uint256 newHalvingCounter ) { uint256 blockElapsed = getBlockNumber().sub(masterPot.startBlock()); newHalvingCounter = blockElapsed.div(halfLife); newFarmHotpotBasePerBlock = farmHotpotBasePerBlock; // if new halvingCounter is larger than old one, perform halving. if (newHalvingCounter > halvingCounter) { newFarmHotpotBasePerBlock = newFarmHotpotBasePerBlock.div(2); } // computes newHotpotBasePerBlock based on targetStock2Flow. newHotpotBasePerBlock = masterPot.hotpotBaseTotalSupply().div( targetStock2Flow.mul(2400000) ); // use the larger of newHotpotBasePerBlock and newFarmHotpotBasePerBlock. newHotpotBasePerBlock = newHotpotBasePerBlock > newFarmHotpotBasePerBlock ? newHotpotBasePerBlock : newFarmHotpotBasePerBlock; if (price > targetPrice) { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(price).div(targetPrice); } else { newHotpotBasePerBlock = newHotpotBasePerBlock.mul(targetPrice).div(price); } } // Computes new redShare based on price. function getNewRedShare(uint256 price) public view returns (uint256) { return uint256(1e24).div(price.mul(1e12).div(targetPrice).add(1e12)); } // Check if the current price is within the deviation threshold for rebasing. function withinDeviationThreshold(uint256 price) public view returns (bool) { uint256 absoluteDeviationThreshold = targetPrice.mul(deviationThreshold).div(1e18); return (price >= targetPrice && price.sub(targetPrice) < absoluteDeviationThreshold) || (price < targetPrice && targetPrice.sub(price) < absoluteDeviationThreshold); } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetPrice, then no supply * modifications are made. * @param _deviationThreshold The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 _deviationThreshold) external onlyGov { require(_deviationThreshold > 0, 'deviationThreshold: too low'); uint256 oldDeviationThreshold = deviationThreshold; deviationThreshold = _deviationThreshold; emit NewDeviationThreshold(oldDeviationThreshold, _deviationThreshold); } function setDeviationMovement(uint256 _deviationMovement) external onlyGov { require(_deviationMovement > 0, 'deviationMovement: too low'); uint256 oldDeviationMovement = deviationMovement; deviationMovement = _deviationMovement; emit NewDeviationMovement(oldDeviationMovement, _deviationMovement); } // Sets the retarget threshold parameter, Gov only. function setRetargetThreshold(uint256 _retargetThreshold) external onlyGov { require(_retargetThreshold > 0, 'retargetThreshold: too low'); retargetThreshold = _retargetThreshold; } // Overwrites the target stock-to-flow ratio, Gov only. function setTargetStock2Flow(uint256 _targetStock2Flow) external onlyGov { require(_targetStock2Flow > 0, 'targetStock2Flow: too low'); targetStock2Flow = _targetStock2Flow; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param _minRebaseTimeIntervalSec More than this much time must pass between rebase * operations, in seconds. * @param _rebaseWindowOffsetSec The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param _rebaseWindowLengthSec The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 _minRebaseTimeIntervalSec, uint256 _rebaseWindowOffsetSec, uint256 _rebaseWindowLengthSec ) external onlyGov { require(_minRebaseTimeIntervalSec > 0, 'minRebaseTimeIntervalSec: too low'); require( _rebaseWindowOffsetSec < _minRebaseTimeIntervalSec, 'rebaseWindowOffsetSec: too high' ); minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec; rebaseWindowOffsetSec = _rebaseWindowOffsetSec; rebaseWindowLengthSec = _rebaseWindowLengthSec; } // Passthrough function to add pool. function addPool( uint256 _allocPoint, IERC20 _lpToken, bool _isRed, bool _withUpdate ) public onlyGov { masterPot.addPool(_allocPoint, _lpToken, _isRed, _withUpdate); } // Passthrough function to set pool. function setPool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyGov { masterPot.setPool(_pid, _allocPoint, _withUpdate); } // Passthrough function to set tip rate. function setTipRate(uint256 _tipRate) public onlyGov { masterPot.setTipRate(_tipRate); } // Passthrough function to transfer pot ownership. function transferPotOwnership(address newOwner) public onlyGov { masterPot.transferPotOwnership(newOwner); } function getNow() public virtual view returns (uint256) { return now; } function getBlockNumber() public virtual view returns (uint256) { return block.number; } }
withinDeviationThreshold
function withinDeviationThreshold(uint256 price) public view returns (bool) { uint256 absoluteDeviationThreshold = targetPrice.mul(deviationThreshold).div(1e18); return (price >= targetPrice && price.sub(targetPrice) < absoluteDeviationThreshold) || (price < targetPrice && targetPrice.sub(price) < absoluteDeviationThreshold); }
// Check if the current price is within the deviation threshold for rebasing.
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://06c3e1b7010ded32c215d8d2b064a338aa716548f7264dc15aba4614175c048f
{ "func_code_index": [ 12059, 12406 ] }
59,660