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
Kannabiz
Kannabiz.sol
0xd9506121d67fb918ac47af0b883730694be9377c
Solidity
Kannabiz
contract Kannabiz is ERC20Interface, Owned { using SafeMath for uint; using ExtendedMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public latestDifficultyPeriodStarted; uint public epochCount; //number of 'blocks' mined uint public _BLOCKS_PER_READJUSTMENT = 4; //a little number uint public _MINIMUM_TARGET = 2**16; //a big number is easier, just find a solution that is smaller //uint public _MAXIMUM_TARGET = 2**224; bitcoin uses 224 uint public _MAXIMUM_TARGET = 2**234; uint public miningTarget; bytes32 public challengeNumber; //generate a new one when a new reward is minted uint public rewardEra; uint public maxSupplyForEra; address public lastRewardTo; uint public lastRewardAmount; uint public lastRewardEthBlockNumber; bool locked = false; mapping(bytes32 => bytes32) solutionForChallenge; uint public tokensMinted; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) public frozenAccount; // Array of frozen accounts mapping(address => bool) public whitelistedAccount; // Array of whitelisted accounts mapping(uint256 => uint256) public eraVsMaxSupplyFactor; event FrozenFunds(address target, bool frozen); event whitelistedFunds(address target, bool whitelisted); event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Kannabiz() public onlyOwner { symbol = "KK"; name = "Kannabiz Koin"; decimals = 8; _totalSupply = 25000000000 * 10**uint(decimals); if(locked) revert(); locked = true; tokensMinted = 0; rewardEra = 0; miningTarget = _MAXIMUM_TARGET; latestDifficultyPeriodStarted = block.number; eraVsMaxSupplyFactor[0] = 5; eraVsMaxSupplyFactor[1] = 4; eraVsMaxSupplyFactor[2] = 3; eraVsMaxSupplyFactor[3] = 2; eraVsMaxSupplyFactor[4] = 2; eraVsMaxSupplyFactor[5] = 2; eraVsMaxSupplyFactor[6] = 2; eraVsMaxSupplyFactor[7] = 1; eraVsMaxSupplyFactor[8] = 1; eraVsMaxSupplyFactor[9] = 1; eraVsMaxSupplyFactor[10] = 1; eraVsMaxSupplyFactor[11] = 1; maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals); _startNewMiningEpoch(); } function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success) { if (whitelistedAccount[msg.sender]) { //the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks bytes32 digest = keccak256(challengeNumber, msg.sender, nonce ); //the challenge digest must match the expected if (digest != challenge_digest) revert(); //the digest must be smaller than the target if(uint256(digest) > miningTarget) revert(); //only allow one reward for each challenge bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if(solution != 0x0) revert(); //prevent the same answer from awarding twice uint reward_amount = getMiningReward(); balances[msg.sender] = balances[msg.sender].add(reward_amount); tokensMinted = tokensMinted.add(reward_amount); //Cannot mint more tokens than there are assert(tokensMinted <= maxSupplyForEra); assert(tokensMinted <= _totalSupply); //set readonly diagnostics data lastRewardTo = msg.sender; lastRewardAmount = reward_amount; lastRewardEthBlockNumber = block.number; _startNewMiningEpoch(); Mint(msg.sender, reward_amount, epochCount, challengeNumber ); return true; } else { return false; } } //a new 'block' to be mined function _startNewMiningEpoch() internal { //if max supply for the era will be exceeded next reward round then enter the new era before that happens //4 is the final reward era, almost all tokens minted //once the final era is reached, more tokens will not be given out because the assert function if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 12) { rewardEra = rewardEra + 1; maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals); } epochCount = epochCount.add(1); //every so often, readjust difficulty. Dont readjust when deploying if(epochCount % _BLOCKS_PER_READJUSTMENT == 0) { _reAdjustDifficulty(); } //make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks //do this last since this is a protection mechanism in the mint() function challengeNumber = block.blockhash(block.number - 1); } function _reAdjustDifficulty() internal { uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted; //assume 270 ethereum blocks per hour //we want miners to spend 10 minutes to mine each 'block', about 45 ethereum blocks = one Block X Token epoch uint epochsMined = _BLOCKS_PER_READJUSTMENT; //256 uint targetEthBlocksPerDiffPeriod = epochsMined * 48; //should be 48 times slower than ethereum //if there were less eth blocks passed in time than expected if( ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod ) { uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div( ethBlocksSinceLastDifficultyPeriod ); uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000); // If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100. //make it harder miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra)); //by up to 50 % } else { uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div( targetEthBlocksPerDiffPeriod ); uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); //always between 0 and 1000 //make it easier miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 % } latestDifficultyPeriodStarted = block.number; if(miningTarget < _MINIMUM_TARGET) //very difficult { miningTarget = _MINIMUM_TARGET; } if(miningTarget > _MAXIMUM_TARGET) //very easy { miningTarget = _MAXIMUM_TARGET; } } //this is a recent ethereum block hash, used to prevent pre-mining future blocks function getChallengeNumber() public constant returns (bytes32) { return challengeNumber; } //the number of zeroes the digest of the PoW solution requires. Auto adjusts function getMiningDifficulty() public constant returns (uint) { return _MAXIMUM_TARGET.div(miningTarget); } function getMiningTarget() public constant returns (uint) { return miningTarget; } //10,000,000,000 coins total //reward begins at 100,000 and is cut in half every reward era (as tokens are mined) function getMiningReward() public constant returns (uint) { //once we get half way thru the coins, only get 50,000 per block //every reward era, the reward amount halves. return (100000 * 10**uint(decimals) ).div(5).mul(eraVsMaxSupplyFactor[rewardEra]) ; } //help debug mining software function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if (challenge_digest == 9643712) { //suppress the warning } return digest; } //help debug mining software function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if(uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { // Checks if sender has enough balance, checks for overflows, and checks if the sender or to accounts are frozen if ((balances[msg.sender] < tokens) || (balances[to] + tokens < balances[to]) || (frozenAccount[msg.sender]) || (frozenAccount[to])) { return false; } else { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[spender])) { return false; } else { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[from]) || (frozenAccount[to])) { return false; } else { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[spender])) { return false; } else { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } } function freezeAccount(address target, bool freeze) public onlyOwner { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } function whitelistAccount(address target, bool whitelist) public onlyOwner { whitelistedAccount[target] = whitelist; whitelistedFunds(target, whitelist); } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial fixed supply // ----------------------------------------------------------------------------
LineComment
totalSupply
function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; }
// ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------
LineComment
v0.4.18+commit.9cf6e910
MIT
bzzr://36f2cb1a1a9ef7dc23ca6748643c1e70e2de61a55de2af8061617bc05ba7c865
{ "func_code_index": [ 9229, 9357 ] }
12,200
Kannabiz
Kannabiz.sol
0xd9506121d67fb918ac47af0b883730694be9377c
Solidity
Kannabiz
contract Kannabiz is ERC20Interface, Owned { using SafeMath for uint; using ExtendedMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public latestDifficultyPeriodStarted; uint public epochCount; //number of 'blocks' mined uint public _BLOCKS_PER_READJUSTMENT = 4; //a little number uint public _MINIMUM_TARGET = 2**16; //a big number is easier, just find a solution that is smaller //uint public _MAXIMUM_TARGET = 2**224; bitcoin uses 224 uint public _MAXIMUM_TARGET = 2**234; uint public miningTarget; bytes32 public challengeNumber; //generate a new one when a new reward is minted uint public rewardEra; uint public maxSupplyForEra; address public lastRewardTo; uint public lastRewardAmount; uint public lastRewardEthBlockNumber; bool locked = false; mapping(bytes32 => bytes32) solutionForChallenge; uint public tokensMinted; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) public frozenAccount; // Array of frozen accounts mapping(address => bool) public whitelistedAccount; // Array of whitelisted accounts mapping(uint256 => uint256) public eraVsMaxSupplyFactor; event FrozenFunds(address target, bool frozen); event whitelistedFunds(address target, bool whitelisted); event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Kannabiz() public onlyOwner { symbol = "KK"; name = "Kannabiz Koin"; decimals = 8; _totalSupply = 25000000000 * 10**uint(decimals); if(locked) revert(); locked = true; tokensMinted = 0; rewardEra = 0; miningTarget = _MAXIMUM_TARGET; latestDifficultyPeriodStarted = block.number; eraVsMaxSupplyFactor[0] = 5; eraVsMaxSupplyFactor[1] = 4; eraVsMaxSupplyFactor[2] = 3; eraVsMaxSupplyFactor[3] = 2; eraVsMaxSupplyFactor[4] = 2; eraVsMaxSupplyFactor[5] = 2; eraVsMaxSupplyFactor[6] = 2; eraVsMaxSupplyFactor[7] = 1; eraVsMaxSupplyFactor[8] = 1; eraVsMaxSupplyFactor[9] = 1; eraVsMaxSupplyFactor[10] = 1; eraVsMaxSupplyFactor[11] = 1; maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals); _startNewMiningEpoch(); } function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success) { if (whitelistedAccount[msg.sender]) { //the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks bytes32 digest = keccak256(challengeNumber, msg.sender, nonce ); //the challenge digest must match the expected if (digest != challenge_digest) revert(); //the digest must be smaller than the target if(uint256(digest) > miningTarget) revert(); //only allow one reward for each challenge bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if(solution != 0x0) revert(); //prevent the same answer from awarding twice uint reward_amount = getMiningReward(); balances[msg.sender] = balances[msg.sender].add(reward_amount); tokensMinted = tokensMinted.add(reward_amount); //Cannot mint more tokens than there are assert(tokensMinted <= maxSupplyForEra); assert(tokensMinted <= _totalSupply); //set readonly diagnostics data lastRewardTo = msg.sender; lastRewardAmount = reward_amount; lastRewardEthBlockNumber = block.number; _startNewMiningEpoch(); Mint(msg.sender, reward_amount, epochCount, challengeNumber ); return true; } else { return false; } } //a new 'block' to be mined function _startNewMiningEpoch() internal { //if max supply for the era will be exceeded next reward round then enter the new era before that happens //4 is the final reward era, almost all tokens minted //once the final era is reached, more tokens will not be given out because the assert function if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 12) { rewardEra = rewardEra + 1; maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals); } epochCount = epochCount.add(1); //every so often, readjust difficulty. Dont readjust when deploying if(epochCount % _BLOCKS_PER_READJUSTMENT == 0) { _reAdjustDifficulty(); } //make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks //do this last since this is a protection mechanism in the mint() function challengeNumber = block.blockhash(block.number - 1); } function _reAdjustDifficulty() internal { uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted; //assume 270 ethereum blocks per hour //we want miners to spend 10 minutes to mine each 'block', about 45 ethereum blocks = one Block X Token epoch uint epochsMined = _BLOCKS_PER_READJUSTMENT; //256 uint targetEthBlocksPerDiffPeriod = epochsMined * 48; //should be 48 times slower than ethereum //if there were less eth blocks passed in time than expected if( ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod ) { uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div( ethBlocksSinceLastDifficultyPeriod ); uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000); // If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100. //make it harder miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra)); //by up to 50 % } else { uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div( targetEthBlocksPerDiffPeriod ); uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); //always between 0 and 1000 //make it easier miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 % } latestDifficultyPeriodStarted = block.number; if(miningTarget < _MINIMUM_TARGET) //very difficult { miningTarget = _MINIMUM_TARGET; } if(miningTarget > _MAXIMUM_TARGET) //very easy { miningTarget = _MAXIMUM_TARGET; } } //this is a recent ethereum block hash, used to prevent pre-mining future blocks function getChallengeNumber() public constant returns (bytes32) { return challengeNumber; } //the number of zeroes the digest of the PoW solution requires. Auto adjusts function getMiningDifficulty() public constant returns (uint) { return _MAXIMUM_TARGET.div(miningTarget); } function getMiningTarget() public constant returns (uint) { return miningTarget; } //10,000,000,000 coins total //reward begins at 100,000 and is cut in half every reward era (as tokens are mined) function getMiningReward() public constant returns (uint) { //once we get half way thru the coins, only get 50,000 per block //every reward era, the reward amount halves. return (100000 * 10**uint(decimals) ).div(5).mul(eraVsMaxSupplyFactor[rewardEra]) ; } //help debug mining software function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if (challenge_digest == 9643712) { //suppress the warning } return digest; } //help debug mining software function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if(uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { // Checks if sender has enough balance, checks for overflows, and checks if the sender or to accounts are frozen if ((balances[msg.sender] < tokens) || (balances[to] + tokens < balances[to]) || (frozenAccount[msg.sender]) || (frozenAccount[to])) { return false; } else { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[spender])) { return false; } else { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[from]) || (frozenAccount[to])) { return false; } else { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[spender])) { return false; } else { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } } function freezeAccount(address target, bool freeze) public onlyOwner { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } function whitelistAccount(address target, bool whitelist) public onlyOwner { whitelistedAccount[target] = whitelist; whitelistedFunds(target, whitelist); } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial fixed supply // ----------------------------------------------------------------------------
LineComment
balanceOf
function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; }
// ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------
LineComment
v0.4.18+commit.9cf6e910
MIT
bzzr://36f2cb1a1a9ef7dc23ca6748643c1e70e2de61a55de2af8061617bc05ba7c865
{ "func_code_index": [ 9580, 9716 ] }
12,201
Kannabiz
Kannabiz.sol
0xd9506121d67fb918ac47af0b883730694be9377c
Solidity
Kannabiz
contract Kannabiz is ERC20Interface, Owned { using SafeMath for uint; using ExtendedMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public latestDifficultyPeriodStarted; uint public epochCount; //number of 'blocks' mined uint public _BLOCKS_PER_READJUSTMENT = 4; //a little number uint public _MINIMUM_TARGET = 2**16; //a big number is easier, just find a solution that is smaller //uint public _MAXIMUM_TARGET = 2**224; bitcoin uses 224 uint public _MAXIMUM_TARGET = 2**234; uint public miningTarget; bytes32 public challengeNumber; //generate a new one when a new reward is minted uint public rewardEra; uint public maxSupplyForEra; address public lastRewardTo; uint public lastRewardAmount; uint public lastRewardEthBlockNumber; bool locked = false; mapping(bytes32 => bytes32) solutionForChallenge; uint public tokensMinted; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) public frozenAccount; // Array of frozen accounts mapping(address => bool) public whitelistedAccount; // Array of whitelisted accounts mapping(uint256 => uint256) public eraVsMaxSupplyFactor; event FrozenFunds(address target, bool frozen); event whitelistedFunds(address target, bool whitelisted); event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Kannabiz() public onlyOwner { symbol = "KK"; name = "Kannabiz Koin"; decimals = 8; _totalSupply = 25000000000 * 10**uint(decimals); if(locked) revert(); locked = true; tokensMinted = 0; rewardEra = 0; miningTarget = _MAXIMUM_TARGET; latestDifficultyPeriodStarted = block.number; eraVsMaxSupplyFactor[0] = 5; eraVsMaxSupplyFactor[1] = 4; eraVsMaxSupplyFactor[2] = 3; eraVsMaxSupplyFactor[3] = 2; eraVsMaxSupplyFactor[4] = 2; eraVsMaxSupplyFactor[5] = 2; eraVsMaxSupplyFactor[6] = 2; eraVsMaxSupplyFactor[7] = 1; eraVsMaxSupplyFactor[8] = 1; eraVsMaxSupplyFactor[9] = 1; eraVsMaxSupplyFactor[10] = 1; eraVsMaxSupplyFactor[11] = 1; maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals); _startNewMiningEpoch(); } function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success) { if (whitelistedAccount[msg.sender]) { //the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks bytes32 digest = keccak256(challengeNumber, msg.sender, nonce ); //the challenge digest must match the expected if (digest != challenge_digest) revert(); //the digest must be smaller than the target if(uint256(digest) > miningTarget) revert(); //only allow one reward for each challenge bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if(solution != 0x0) revert(); //prevent the same answer from awarding twice uint reward_amount = getMiningReward(); balances[msg.sender] = balances[msg.sender].add(reward_amount); tokensMinted = tokensMinted.add(reward_amount); //Cannot mint more tokens than there are assert(tokensMinted <= maxSupplyForEra); assert(tokensMinted <= _totalSupply); //set readonly diagnostics data lastRewardTo = msg.sender; lastRewardAmount = reward_amount; lastRewardEthBlockNumber = block.number; _startNewMiningEpoch(); Mint(msg.sender, reward_amount, epochCount, challengeNumber ); return true; } else { return false; } } //a new 'block' to be mined function _startNewMiningEpoch() internal { //if max supply for the era will be exceeded next reward round then enter the new era before that happens //4 is the final reward era, almost all tokens minted //once the final era is reached, more tokens will not be given out because the assert function if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 12) { rewardEra = rewardEra + 1; maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals); } epochCount = epochCount.add(1); //every so often, readjust difficulty. Dont readjust when deploying if(epochCount % _BLOCKS_PER_READJUSTMENT == 0) { _reAdjustDifficulty(); } //make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks //do this last since this is a protection mechanism in the mint() function challengeNumber = block.blockhash(block.number - 1); } function _reAdjustDifficulty() internal { uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted; //assume 270 ethereum blocks per hour //we want miners to spend 10 minutes to mine each 'block', about 45 ethereum blocks = one Block X Token epoch uint epochsMined = _BLOCKS_PER_READJUSTMENT; //256 uint targetEthBlocksPerDiffPeriod = epochsMined * 48; //should be 48 times slower than ethereum //if there were less eth blocks passed in time than expected if( ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod ) { uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div( ethBlocksSinceLastDifficultyPeriod ); uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000); // If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100. //make it harder miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra)); //by up to 50 % } else { uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div( targetEthBlocksPerDiffPeriod ); uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); //always between 0 and 1000 //make it easier miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 % } latestDifficultyPeriodStarted = block.number; if(miningTarget < _MINIMUM_TARGET) //very difficult { miningTarget = _MINIMUM_TARGET; } if(miningTarget > _MAXIMUM_TARGET) //very easy { miningTarget = _MAXIMUM_TARGET; } } //this is a recent ethereum block hash, used to prevent pre-mining future blocks function getChallengeNumber() public constant returns (bytes32) { return challengeNumber; } //the number of zeroes the digest of the PoW solution requires. Auto adjusts function getMiningDifficulty() public constant returns (uint) { return _MAXIMUM_TARGET.div(miningTarget); } function getMiningTarget() public constant returns (uint) { return miningTarget; } //10,000,000,000 coins total //reward begins at 100,000 and is cut in half every reward era (as tokens are mined) function getMiningReward() public constant returns (uint) { //once we get half way thru the coins, only get 50,000 per block //every reward era, the reward amount halves. return (100000 * 10**uint(decimals) ).div(5).mul(eraVsMaxSupplyFactor[rewardEra]) ; } //help debug mining software function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if (challenge_digest == 9643712) { //suppress the warning } return digest; } //help debug mining software function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if(uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { // Checks if sender has enough balance, checks for overflows, and checks if the sender or to accounts are frozen if ((balances[msg.sender] < tokens) || (balances[to] + tokens < balances[to]) || (frozenAccount[msg.sender]) || (frozenAccount[to])) { return false; } else { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[spender])) { return false; } else { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[from]) || (frozenAccount[to])) { return false; } else { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[spender])) { return false; } else { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } } function freezeAccount(address target, bool freeze) public onlyOwner { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } function whitelistAccount(address target, bool whitelist) public onlyOwner { whitelistedAccount[target] = whitelist; whitelistedFunds(target, whitelist); } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial fixed supply // ----------------------------------------------------------------------------
LineComment
transfer
function transfer(address to, uint tokens) public returns (bool success) { // Checks if sender has enough balance, checks for overflows, and checks if the sender or to accounts are frozen if ((balances[msg.sender] < tokens) || (balances[to] + tokens < balances[to]) || (frozenAccount[msg.sender]) || (frozenAccount[to])) { return false; } else { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } }
// ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------
LineComment
v0.4.18+commit.9cf6e910
MIT
bzzr://36f2cb1a1a9ef7dc23ca6748643c1e70e2de61a55de2af8061617bc05ba7c865
{ "func_code_index": [ 10061, 10686 ] }
12,202
Kannabiz
Kannabiz.sol
0xd9506121d67fb918ac47af0b883730694be9377c
Solidity
Kannabiz
contract Kannabiz is ERC20Interface, Owned { using SafeMath for uint; using ExtendedMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public latestDifficultyPeriodStarted; uint public epochCount; //number of 'blocks' mined uint public _BLOCKS_PER_READJUSTMENT = 4; //a little number uint public _MINIMUM_TARGET = 2**16; //a big number is easier, just find a solution that is smaller //uint public _MAXIMUM_TARGET = 2**224; bitcoin uses 224 uint public _MAXIMUM_TARGET = 2**234; uint public miningTarget; bytes32 public challengeNumber; //generate a new one when a new reward is minted uint public rewardEra; uint public maxSupplyForEra; address public lastRewardTo; uint public lastRewardAmount; uint public lastRewardEthBlockNumber; bool locked = false; mapping(bytes32 => bytes32) solutionForChallenge; uint public tokensMinted; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) public frozenAccount; // Array of frozen accounts mapping(address => bool) public whitelistedAccount; // Array of whitelisted accounts mapping(uint256 => uint256) public eraVsMaxSupplyFactor; event FrozenFunds(address target, bool frozen); event whitelistedFunds(address target, bool whitelisted); event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Kannabiz() public onlyOwner { symbol = "KK"; name = "Kannabiz Koin"; decimals = 8; _totalSupply = 25000000000 * 10**uint(decimals); if(locked) revert(); locked = true; tokensMinted = 0; rewardEra = 0; miningTarget = _MAXIMUM_TARGET; latestDifficultyPeriodStarted = block.number; eraVsMaxSupplyFactor[0] = 5; eraVsMaxSupplyFactor[1] = 4; eraVsMaxSupplyFactor[2] = 3; eraVsMaxSupplyFactor[3] = 2; eraVsMaxSupplyFactor[4] = 2; eraVsMaxSupplyFactor[5] = 2; eraVsMaxSupplyFactor[6] = 2; eraVsMaxSupplyFactor[7] = 1; eraVsMaxSupplyFactor[8] = 1; eraVsMaxSupplyFactor[9] = 1; eraVsMaxSupplyFactor[10] = 1; eraVsMaxSupplyFactor[11] = 1; maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals); _startNewMiningEpoch(); } function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success) { if (whitelistedAccount[msg.sender]) { //the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks bytes32 digest = keccak256(challengeNumber, msg.sender, nonce ); //the challenge digest must match the expected if (digest != challenge_digest) revert(); //the digest must be smaller than the target if(uint256(digest) > miningTarget) revert(); //only allow one reward for each challenge bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if(solution != 0x0) revert(); //prevent the same answer from awarding twice uint reward_amount = getMiningReward(); balances[msg.sender] = balances[msg.sender].add(reward_amount); tokensMinted = tokensMinted.add(reward_amount); //Cannot mint more tokens than there are assert(tokensMinted <= maxSupplyForEra); assert(tokensMinted <= _totalSupply); //set readonly diagnostics data lastRewardTo = msg.sender; lastRewardAmount = reward_amount; lastRewardEthBlockNumber = block.number; _startNewMiningEpoch(); Mint(msg.sender, reward_amount, epochCount, challengeNumber ); return true; } else { return false; } } //a new 'block' to be mined function _startNewMiningEpoch() internal { //if max supply for the era will be exceeded next reward round then enter the new era before that happens //4 is the final reward era, almost all tokens minted //once the final era is reached, more tokens will not be given out because the assert function if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 12) { rewardEra = rewardEra + 1; maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals); } epochCount = epochCount.add(1); //every so often, readjust difficulty. Dont readjust when deploying if(epochCount % _BLOCKS_PER_READJUSTMENT == 0) { _reAdjustDifficulty(); } //make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks //do this last since this is a protection mechanism in the mint() function challengeNumber = block.blockhash(block.number - 1); } function _reAdjustDifficulty() internal { uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted; //assume 270 ethereum blocks per hour //we want miners to spend 10 minutes to mine each 'block', about 45 ethereum blocks = one Block X Token epoch uint epochsMined = _BLOCKS_PER_READJUSTMENT; //256 uint targetEthBlocksPerDiffPeriod = epochsMined * 48; //should be 48 times slower than ethereum //if there were less eth blocks passed in time than expected if( ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod ) { uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div( ethBlocksSinceLastDifficultyPeriod ); uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000); // If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100. //make it harder miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra)); //by up to 50 % } else { uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div( targetEthBlocksPerDiffPeriod ); uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); //always between 0 and 1000 //make it easier miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 % } latestDifficultyPeriodStarted = block.number; if(miningTarget < _MINIMUM_TARGET) //very difficult { miningTarget = _MINIMUM_TARGET; } if(miningTarget > _MAXIMUM_TARGET) //very easy { miningTarget = _MAXIMUM_TARGET; } } //this is a recent ethereum block hash, used to prevent pre-mining future blocks function getChallengeNumber() public constant returns (bytes32) { return challengeNumber; } //the number of zeroes the digest of the PoW solution requires. Auto adjusts function getMiningDifficulty() public constant returns (uint) { return _MAXIMUM_TARGET.div(miningTarget); } function getMiningTarget() public constant returns (uint) { return miningTarget; } //10,000,000,000 coins total //reward begins at 100,000 and is cut in half every reward era (as tokens are mined) function getMiningReward() public constant returns (uint) { //once we get half way thru the coins, only get 50,000 per block //every reward era, the reward amount halves. return (100000 * 10**uint(decimals) ).div(5).mul(eraVsMaxSupplyFactor[rewardEra]) ; } //help debug mining software function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if (challenge_digest == 9643712) { //suppress the warning } return digest; } //help debug mining software function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if(uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { // Checks if sender has enough balance, checks for overflows, and checks if the sender or to accounts are frozen if ((balances[msg.sender] < tokens) || (balances[to] + tokens < balances[to]) || (frozenAccount[msg.sender]) || (frozenAccount[to])) { return false; } else { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[spender])) { return false; } else { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[from]) || (frozenAccount[to])) { return false; } else { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[spender])) { return false; } else { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } } function freezeAccount(address target, bool freeze) public onlyOwner { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } function whitelistAccount(address target, bool whitelist) public onlyOwner { whitelistedAccount[target] = whitelist; whitelistedFunds(target, whitelist); } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial fixed supply // ----------------------------------------------------------------------------
LineComment
approve
function approve(address spender, uint tokens) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[spender])) { return false; } else { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } }
// ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------
LineComment
v0.4.18+commit.9cf6e910
MIT
bzzr://36f2cb1a1a9ef7dc23ca6748643c1e70e2de61a55de2af8061617bc05ba7c865
{ "func_code_index": [ 11191, 11567 ] }
12,203
Kannabiz
Kannabiz.sol
0xd9506121d67fb918ac47af0b883730694be9377c
Solidity
Kannabiz
contract Kannabiz is ERC20Interface, Owned { using SafeMath for uint; using ExtendedMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public latestDifficultyPeriodStarted; uint public epochCount; //number of 'blocks' mined uint public _BLOCKS_PER_READJUSTMENT = 4; //a little number uint public _MINIMUM_TARGET = 2**16; //a big number is easier, just find a solution that is smaller //uint public _MAXIMUM_TARGET = 2**224; bitcoin uses 224 uint public _MAXIMUM_TARGET = 2**234; uint public miningTarget; bytes32 public challengeNumber; //generate a new one when a new reward is minted uint public rewardEra; uint public maxSupplyForEra; address public lastRewardTo; uint public lastRewardAmount; uint public lastRewardEthBlockNumber; bool locked = false; mapping(bytes32 => bytes32) solutionForChallenge; uint public tokensMinted; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) public frozenAccount; // Array of frozen accounts mapping(address => bool) public whitelistedAccount; // Array of whitelisted accounts mapping(uint256 => uint256) public eraVsMaxSupplyFactor; event FrozenFunds(address target, bool frozen); event whitelistedFunds(address target, bool whitelisted); event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Kannabiz() public onlyOwner { symbol = "KK"; name = "Kannabiz Koin"; decimals = 8; _totalSupply = 25000000000 * 10**uint(decimals); if(locked) revert(); locked = true; tokensMinted = 0; rewardEra = 0; miningTarget = _MAXIMUM_TARGET; latestDifficultyPeriodStarted = block.number; eraVsMaxSupplyFactor[0] = 5; eraVsMaxSupplyFactor[1] = 4; eraVsMaxSupplyFactor[2] = 3; eraVsMaxSupplyFactor[3] = 2; eraVsMaxSupplyFactor[4] = 2; eraVsMaxSupplyFactor[5] = 2; eraVsMaxSupplyFactor[6] = 2; eraVsMaxSupplyFactor[7] = 1; eraVsMaxSupplyFactor[8] = 1; eraVsMaxSupplyFactor[9] = 1; eraVsMaxSupplyFactor[10] = 1; eraVsMaxSupplyFactor[11] = 1; maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals); _startNewMiningEpoch(); } function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success) { if (whitelistedAccount[msg.sender]) { //the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks bytes32 digest = keccak256(challengeNumber, msg.sender, nonce ); //the challenge digest must match the expected if (digest != challenge_digest) revert(); //the digest must be smaller than the target if(uint256(digest) > miningTarget) revert(); //only allow one reward for each challenge bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if(solution != 0x0) revert(); //prevent the same answer from awarding twice uint reward_amount = getMiningReward(); balances[msg.sender] = balances[msg.sender].add(reward_amount); tokensMinted = tokensMinted.add(reward_amount); //Cannot mint more tokens than there are assert(tokensMinted <= maxSupplyForEra); assert(tokensMinted <= _totalSupply); //set readonly diagnostics data lastRewardTo = msg.sender; lastRewardAmount = reward_amount; lastRewardEthBlockNumber = block.number; _startNewMiningEpoch(); Mint(msg.sender, reward_amount, epochCount, challengeNumber ); return true; } else { return false; } } //a new 'block' to be mined function _startNewMiningEpoch() internal { //if max supply for the era will be exceeded next reward round then enter the new era before that happens //4 is the final reward era, almost all tokens minted //once the final era is reached, more tokens will not be given out because the assert function if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 12) { rewardEra = rewardEra + 1; maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals); } epochCount = epochCount.add(1); //every so often, readjust difficulty. Dont readjust when deploying if(epochCount % _BLOCKS_PER_READJUSTMENT == 0) { _reAdjustDifficulty(); } //make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks //do this last since this is a protection mechanism in the mint() function challengeNumber = block.blockhash(block.number - 1); } function _reAdjustDifficulty() internal { uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted; //assume 270 ethereum blocks per hour //we want miners to spend 10 minutes to mine each 'block', about 45 ethereum blocks = one Block X Token epoch uint epochsMined = _BLOCKS_PER_READJUSTMENT; //256 uint targetEthBlocksPerDiffPeriod = epochsMined * 48; //should be 48 times slower than ethereum //if there were less eth blocks passed in time than expected if( ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod ) { uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div( ethBlocksSinceLastDifficultyPeriod ); uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000); // If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100. //make it harder miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra)); //by up to 50 % } else { uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div( targetEthBlocksPerDiffPeriod ); uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); //always between 0 and 1000 //make it easier miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 % } latestDifficultyPeriodStarted = block.number; if(miningTarget < _MINIMUM_TARGET) //very difficult { miningTarget = _MINIMUM_TARGET; } if(miningTarget > _MAXIMUM_TARGET) //very easy { miningTarget = _MAXIMUM_TARGET; } } //this is a recent ethereum block hash, used to prevent pre-mining future blocks function getChallengeNumber() public constant returns (bytes32) { return challengeNumber; } //the number of zeroes the digest of the PoW solution requires. Auto adjusts function getMiningDifficulty() public constant returns (uint) { return _MAXIMUM_TARGET.div(miningTarget); } function getMiningTarget() public constant returns (uint) { return miningTarget; } //10,000,000,000 coins total //reward begins at 100,000 and is cut in half every reward era (as tokens are mined) function getMiningReward() public constant returns (uint) { //once we get half way thru the coins, only get 50,000 per block //every reward era, the reward amount halves. return (100000 * 10**uint(decimals) ).div(5).mul(eraVsMaxSupplyFactor[rewardEra]) ; } //help debug mining software function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if (challenge_digest == 9643712) { //suppress the warning } return digest; } //help debug mining software function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if(uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { // Checks if sender has enough balance, checks for overflows, and checks if the sender or to accounts are frozen if ((balances[msg.sender] < tokens) || (balances[to] + tokens < balances[to]) || (frozenAccount[msg.sender]) || (frozenAccount[to])) { return false; } else { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[spender])) { return false; } else { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[from]) || (frozenAccount[to])) { return false; } else { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[spender])) { return false; } else { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } } function freezeAccount(address target, bool freeze) public onlyOwner { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } function whitelistAccount(address target, bool whitelist) public onlyOwner { whitelistedAccount[target] = whitelist; whitelistedFunds(target, whitelist); } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial fixed supply // ----------------------------------------------------------------------------
LineComment
transferFrom
function transferFrom(address from, address to, uint tokens) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[from]) || (frozenAccount[to])) { return false; } else { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } }
// ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------
LineComment
v0.4.18+commit.9cf6e910
MIT
bzzr://36f2cb1a1a9ef7dc23ca6748643c1e70e2de61a55de2af8061617bc05ba7c865
{ "func_code_index": [ 12100, 12633 ] }
12,204
Kannabiz
Kannabiz.sol
0xd9506121d67fb918ac47af0b883730694be9377c
Solidity
Kannabiz
contract Kannabiz is ERC20Interface, Owned { using SafeMath for uint; using ExtendedMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public latestDifficultyPeriodStarted; uint public epochCount; //number of 'blocks' mined uint public _BLOCKS_PER_READJUSTMENT = 4; //a little number uint public _MINIMUM_TARGET = 2**16; //a big number is easier, just find a solution that is smaller //uint public _MAXIMUM_TARGET = 2**224; bitcoin uses 224 uint public _MAXIMUM_TARGET = 2**234; uint public miningTarget; bytes32 public challengeNumber; //generate a new one when a new reward is minted uint public rewardEra; uint public maxSupplyForEra; address public lastRewardTo; uint public lastRewardAmount; uint public lastRewardEthBlockNumber; bool locked = false; mapping(bytes32 => bytes32) solutionForChallenge; uint public tokensMinted; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) public frozenAccount; // Array of frozen accounts mapping(address => bool) public whitelistedAccount; // Array of whitelisted accounts mapping(uint256 => uint256) public eraVsMaxSupplyFactor; event FrozenFunds(address target, bool frozen); event whitelistedFunds(address target, bool whitelisted); event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Kannabiz() public onlyOwner { symbol = "KK"; name = "Kannabiz Koin"; decimals = 8; _totalSupply = 25000000000 * 10**uint(decimals); if(locked) revert(); locked = true; tokensMinted = 0; rewardEra = 0; miningTarget = _MAXIMUM_TARGET; latestDifficultyPeriodStarted = block.number; eraVsMaxSupplyFactor[0] = 5; eraVsMaxSupplyFactor[1] = 4; eraVsMaxSupplyFactor[2] = 3; eraVsMaxSupplyFactor[3] = 2; eraVsMaxSupplyFactor[4] = 2; eraVsMaxSupplyFactor[5] = 2; eraVsMaxSupplyFactor[6] = 2; eraVsMaxSupplyFactor[7] = 1; eraVsMaxSupplyFactor[8] = 1; eraVsMaxSupplyFactor[9] = 1; eraVsMaxSupplyFactor[10] = 1; eraVsMaxSupplyFactor[11] = 1; maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals); _startNewMiningEpoch(); } function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success) { if (whitelistedAccount[msg.sender]) { //the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks bytes32 digest = keccak256(challengeNumber, msg.sender, nonce ); //the challenge digest must match the expected if (digest != challenge_digest) revert(); //the digest must be smaller than the target if(uint256(digest) > miningTarget) revert(); //only allow one reward for each challenge bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if(solution != 0x0) revert(); //prevent the same answer from awarding twice uint reward_amount = getMiningReward(); balances[msg.sender] = balances[msg.sender].add(reward_amount); tokensMinted = tokensMinted.add(reward_amount); //Cannot mint more tokens than there are assert(tokensMinted <= maxSupplyForEra); assert(tokensMinted <= _totalSupply); //set readonly diagnostics data lastRewardTo = msg.sender; lastRewardAmount = reward_amount; lastRewardEthBlockNumber = block.number; _startNewMiningEpoch(); Mint(msg.sender, reward_amount, epochCount, challengeNumber ); return true; } else { return false; } } //a new 'block' to be mined function _startNewMiningEpoch() internal { //if max supply for the era will be exceeded next reward round then enter the new era before that happens //4 is the final reward era, almost all tokens minted //once the final era is reached, more tokens will not be given out because the assert function if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 12) { rewardEra = rewardEra + 1; maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals); } epochCount = epochCount.add(1); //every so often, readjust difficulty. Dont readjust when deploying if(epochCount % _BLOCKS_PER_READJUSTMENT == 0) { _reAdjustDifficulty(); } //make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks //do this last since this is a protection mechanism in the mint() function challengeNumber = block.blockhash(block.number - 1); } function _reAdjustDifficulty() internal { uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted; //assume 270 ethereum blocks per hour //we want miners to spend 10 minutes to mine each 'block', about 45 ethereum blocks = one Block X Token epoch uint epochsMined = _BLOCKS_PER_READJUSTMENT; //256 uint targetEthBlocksPerDiffPeriod = epochsMined * 48; //should be 48 times slower than ethereum //if there were less eth blocks passed in time than expected if( ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod ) { uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div( ethBlocksSinceLastDifficultyPeriod ); uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000); // If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100. //make it harder miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra)); //by up to 50 % } else { uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div( targetEthBlocksPerDiffPeriod ); uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); //always between 0 and 1000 //make it easier miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 % } latestDifficultyPeriodStarted = block.number; if(miningTarget < _MINIMUM_TARGET) //very difficult { miningTarget = _MINIMUM_TARGET; } if(miningTarget > _MAXIMUM_TARGET) //very easy { miningTarget = _MAXIMUM_TARGET; } } //this is a recent ethereum block hash, used to prevent pre-mining future blocks function getChallengeNumber() public constant returns (bytes32) { return challengeNumber; } //the number of zeroes the digest of the PoW solution requires. Auto adjusts function getMiningDifficulty() public constant returns (uint) { return _MAXIMUM_TARGET.div(miningTarget); } function getMiningTarget() public constant returns (uint) { return miningTarget; } //10,000,000,000 coins total //reward begins at 100,000 and is cut in half every reward era (as tokens are mined) function getMiningReward() public constant returns (uint) { //once we get half way thru the coins, only get 50,000 per block //every reward era, the reward amount halves. return (100000 * 10**uint(decimals) ).div(5).mul(eraVsMaxSupplyFactor[rewardEra]) ; } //help debug mining software function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if (challenge_digest == 9643712) { //suppress the warning } return digest; } //help debug mining software function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if(uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { // Checks if sender has enough balance, checks for overflows, and checks if the sender or to accounts are frozen if ((balances[msg.sender] < tokens) || (balances[to] + tokens < balances[to]) || (frozenAccount[msg.sender]) || (frozenAccount[to])) { return false; } else { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[spender])) { return false; } else { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[from]) || (frozenAccount[to])) { return false; } else { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[spender])) { return false; } else { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } } function freezeAccount(address target, bool freeze) public onlyOwner { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } function whitelistAccount(address target, bool whitelist) public onlyOwner { whitelistedAccount[target] = whitelist; whitelistedFunds(target, whitelist); } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial fixed supply // ----------------------------------------------------------------------------
LineComment
allowance
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; }
// ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------
LineComment
v0.4.18+commit.9cf6e910
MIT
bzzr://36f2cb1a1a9ef7dc23ca6748643c1e70e2de61a55de2af8061617bc05ba7c865
{ "func_code_index": [ 12916, 13079 ] }
12,205
Kannabiz
Kannabiz.sol
0xd9506121d67fb918ac47af0b883730694be9377c
Solidity
Kannabiz
contract Kannabiz is ERC20Interface, Owned { using SafeMath for uint; using ExtendedMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public latestDifficultyPeriodStarted; uint public epochCount; //number of 'blocks' mined uint public _BLOCKS_PER_READJUSTMENT = 4; //a little number uint public _MINIMUM_TARGET = 2**16; //a big number is easier, just find a solution that is smaller //uint public _MAXIMUM_TARGET = 2**224; bitcoin uses 224 uint public _MAXIMUM_TARGET = 2**234; uint public miningTarget; bytes32 public challengeNumber; //generate a new one when a new reward is minted uint public rewardEra; uint public maxSupplyForEra; address public lastRewardTo; uint public lastRewardAmount; uint public lastRewardEthBlockNumber; bool locked = false; mapping(bytes32 => bytes32) solutionForChallenge; uint public tokensMinted; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) public frozenAccount; // Array of frozen accounts mapping(address => bool) public whitelistedAccount; // Array of whitelisted accounts mapping(uint256 => uint256) public eraVsMaxSupplyFactor; event FrozenFunds(address target, bool frozen); event whitelistedFunds(address target, bool whitelisted); event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Kannabiz() public onlyOwner { symbol = "KK"; name = "Kannabiz Koin"; decimals = 8; _totalSupply = 25000000000 * 10**uint(decimals); if(locked) revert(); locked = true; tokensMinted = 0; rewardEra = 0; miningTarget = _MAXIMUM_TARGET; latestDifficultyPeriodStarted = block.number; eraVsMaxSupplyFactor[0] = 5; eraVsMaxSupplyFactor[1] = 4; eraVsMaxSupplyFactor[2] = 3; eraVsMaxSupplyFactor[3] = 2; eraVsMaxSupplyFactor[4] = 2; eraVsMaxSupplyFactor[5] = 2; eraVsMaxSupplyFactor[6] = 2; eraVsMaxSupplyFactor[7] = 1; eraVsMaxSupplyFactor[8] = 1; eraVsMaxSupplyFactor[9] = 1; eraVsMaxSupplyFactor[10] = 1; eraVsMaxSupplyFactor[11] = 1; maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals); _startNewMiningEpoch(); } function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success) { if (whitelistedAccount[msg.sender]) { //the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks bytes32 digest = keccak256(challengeNumber, msg.sender, nonce ); //the challenge digest must match the expected if (digest != challenge_digest) revert(); //the digest must be smaller than the target if(uint256(digest) > miningTarget) revert(); //only allow one reward for each challenge bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if(solution != 0x0) revert(); //prevent the same answer from awarding twice uint reward_amount = getMiningReward(); balances[msg.sender] = balances[msg.sender].add(reward_amount); tokensMinted = tokensMinted.add(reward_amount); //Cannot mint more tokens than there are assert(tokensMinted <= maxSupplyForEra); assert(tokensMinted <= _totalSupply); //set readonly diagnostics data lastRewardTo = msg.sender; lastRewardAmount = reward_amount; lastRewardEthBlockNumber = block.number; _startNewMiningEpoch(); Mint(msg.sender, reward_amount, epochCount, challengeNumber ); return true; } else { return false; } } //a new 'block' to be mined function _startNewMiningEpoch() internal { //if max supply for the era will be exceeded next reward round then enter the new era before that happens //4 is the final reward era, almost all tokens minted //once the final era is reached, more tokens will not be given out because the assert function if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 12) { rewardEra = rewardEra + 1; maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals); } epochCount = epochCount.add(1); //every so often, readjust difficulty. Dont readjust when deploying if(epochCount % _BLOCKS_PER_READJUSTMENT == 0) { _reAdjustDifficulty(); } //make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks //do this last since this is a protection mechanism in the mint() function challengeNumber = block.blockhash(block.number - 1); } function _reAdjustDifficulty() internal { uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted; //assume 270 ethereum blocks per hour //we want miners to spend 10 minutes to mine each 'block', about 45 ethereum blocks = one Block X Token epoch uint epochsMined = _BLOCKS_PER_READJUSTMENT; //256 uint targetEthBlocksPerDiffPeriod = epochsMined * 48; //should be 48 times slower than ethereum //if there were less eth blocks passed in time than expected if( ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod ) { uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div( ethBlocksSinceLastDifficultyPeriod ); uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000); // If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100. //make it harder miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra)); //by up to 50 % } else { uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div( targetEthBlocksPerDiffPeriod ); uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); //always between 0 and 1000 //make it easier miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 % } latestDifficultyPeriodStarted = block.number; if(miningTarget < _MINIMUM_TARGET) //very difficult { miningTarget = _MINIMUM_TARGET; } if(miningTarget > _MAXIMUM_TARGET) //very easy { miningTarget = _MAXIMUM_TARGET; } } //this is a recent ethereum block hash, used to prevent pre-mining future blocks function getChallengeNumber() public constant returns (bytes32) { return challengeNumber; } //the number of zeroes the digest of the PoW solution requires. Auto adjusts function getMiningDifficulty() public constant returns (uint) { return _MAXIMUM_TARGET.div(miningTarget); } function getMiningTarget() public constant returns (uint) { return miningTarget; } //10,000,000,000 coins total //reward begins at 100,000 and is cut in half every reward era (as tokens are mined) function getMiningReward() public constant returns (uint) { //once we get half way thru the coins, only get 50,000 per block //every reward era, the reward amount halves. return (100000 * 10**uint(decimals) ).div(5).mul(eraVsMaxSupplyFactor[rewardEra]) ; } //help debug mining software function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if (challenge_digest == 9643712) { //suppress the warning } return digest; } //help debug mining software function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if(uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { // Checks if sender has enough balance, checks for overflows, and checks if the sender or to accounts are frozen if ((balances[msg.sender] < tokens) || (balances[to] + tokens < balances[to]) || (frozenAccount[msg.sender]) || (frozenAccount[to])) { return false; } else { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[spender])) { return false; } else { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[from]) || (frozenAccount[to])) { return false; } else { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[spender])) { return false; } else { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } } function freezeAccount(address target, bool freeze) public onlyOwner { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } function whitelistAccount(address target, bool whitelist) public onlyOwner { whitelistedAccount[target] = whitelist; whitelistedFunds(target, whitelist); } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial fixed supply // ----------------------------------------------------------------------------
LineComment
approveAndCall
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[spender])) { return false; } else { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } }
// ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------
LineComment
v0.4.18+commit.9cf6e910
MIT
bzzr://36f2cb1a1a9ef7dc23ca6748643c1e70e2de61a55de2af8061617bc05ba7c865
{ "func_code_index": [ 13441, 13927 ] }
12,206
Kannabiz
Kannabiz.sol
0xd9506121d67fb918ac47af0b883730694be9377c
Solidity
Kannabiz
contract Kannabiz is ERC20Interface, Owned { using SafeMath for uint; using ExtendedMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public latestDifficultyPeriodStarted; uint public epochCount; //number of 'blocks' mined uint public _BLOCKS_PER_READJUSTMENT = 4; //a little number uint public _MINIMUM_TARGET = 2**16; //a big number is easier, just find a solution that is smaller //uint public _MAXIMUM_TARGET = 2**224; bitcoin uses 224 uint public _MAXIMUM_TARGET = 2**234; uint public miningTarget; bytes32 public challengeNumber; //generate a new one when a new reward is minted uint public rewardEra; uint public maxSupplyForEra; address public lastRewardTo; uint public lastRewardAmount; uint public lastRewardEthBlockNumber; bool locked = false; mapping(bytes32 => bytes32) solutionForChallenge; uint public tokensMinted; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) public frozenAccount; // Array of frozen accounts mapping(address => bool) public whitelistedAccount; // Array of whitelisted accounts mapping(uint256 => uint256) public eraVsMaxSupplyFactor; event FrozenFunds(address target, bool frozen); event whitelistedFunds(address target, bool whitelisted); event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Kannabiz() public onlyOwner { symbol = "KK"; name = "Kannabiz Koin"; decimals = 8; _totalSupply = 25000000000 * 10**uint(decimals); if(locked) revert(); locked = true; tokensMinted = 0; rewardEra = 0; miningTarget = _MAXIMUM_TARGET; latestDifficultyPeriodStarted = block.number; eraVsMaxSupplyFactor[0] = 5; eraVsMaxSupplyFactor[1] = 4; eraVsMaxSupplyFactor[2] = 3; eraVsMaxSupplyFactor[3] = 2; eraVsMaxSupplyFactor[4] = 2; eraVsMaxSupplyFactor[5] = 2; eraVsMaxSupplyFactor[6] = 2; eraVsMaxSupplyFactor[7] = 1; eraVsMaxSupplyFactor[8] = 1; eraVsMaxSupplyFactor[9] = 1; eraVsMaxSupplyFactor[10] = 1; eraVsMaxSupplyFactor[11] = 1; maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals); _startNewMiningEpoch(); } function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success) { if (whitelistedAccount[msg.sender]) { //the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks bytes32 digest = keccak256(challengeNumber, msg.sender, nonce ); //the challenge digest must match the expected if (digest != challenge_digest) revert(); //the digest must be smaller than the target if(uint256(digest) > miningTarget) revert(); //only allow one reward for each challenge bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if(solution != 0x0) revert(); //prevent the same answer from awarding twice uint reward_amount = getMiningReward(); balances[msg.sender] = balances[msg.sender].add(reward_amount); tokensMinted = tokensMinted.add(reward_amount); //Cannot mint more tokens than there are assert(tokensMinted <= maxSupplyForEra); assert(tokensMinted <= _totalSupply); //set readonly diagnostics data lastRewardTo = msg.sender; lastRewardAmount = reward_amount; lastRewardEthBlockNumber = block.number; _startNewMiningEpoch(); Mint(msg.sender, reward_amount, epochCount, challengeNumber ); return true; } else { return false; } } //a new 'block' to be mined function _startNewMiningEpoch() internal { //if max supply for the era will be exceeded next reward round then enter the new era before that happens //4 is the final reward era, almost all tokens minted //once the final era is reached, more tokens will not be given out because the assert function if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 12) { rewardEra = rewardEra + 1; maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals); } epochCount = epochCount.add(1); //every so often, readjust difficulty. Dont readjust when deploying if(epochCount % _BLOCKS_PER_READJUSTMENT == 0) { _reAdjustDifficulty(); } //make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks //do this last since this is a protection mechanism in the mint() function challengeNumber = block.blockhash(block.number - 1); } function _reAdjustDifficulty() internal { uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted; //assume 270 ethereum blocks per hour //we want miners to spend 10 minutes to mine each 'block', about 45 ethereum blocks = one Block X Token epoch uint epochsMined = _BLOCKS_PER_READJUSTMENT; //256 uint targetEthBlocksPerDiffPeriod = epochsMined * 48; //should be 48 times slower than ethereum //if there were less eth blocks passed in time than expected if( ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod ) { uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div( ethBlocksSinceLastDifficultyPeriod ); uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000); // If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100. //make it harder miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra)); //by up to 50 % } else { uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div( targetEthBlocksPerDiffPeriod ); uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); //always between 0 and 1000 //make it easier miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 % } latestDifficultyPeriodStarted = block.number; if(miningTarget < _MINIMUM_TARGET) //very difficult { miningTarget = _MINIMUM_TARGET; } if(miningTarget > _MAXIMUM_TARGET) //very easy { miningTarget = _MAXIMUM_TARGET; } } //this is a recent ethereum block hash, used to prevent pre-mining future blocks function getChallengeNumber() public constant returns (bytes32) { return challengeNumber; } //the number of zeroes the digest of the PoW solution requires. Auto adjusts function getMiningDifficulty() public constant returns (uint) { return _MAXIMUM_TARGET.div(miningTarget); } function getMiningTarget() public constant returns (uint) { return miningTarget; } //10,000,000,000 coins total //reward begins at 100,000 and is cut in half every reward era (as tokens are mined) function getMiningReward() public constant returns (uint) { //once we get half way thru the coins, only get 50,000 per block //every reward era, the reward amount halves. return (100000 * 10**uint(decimals) ).div(5).mul(eraVsMaxSupplyFactor[rewardEra]) ; } //help debug mining software function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if (challenge_digest == 9643712) { //suppress the warning } return digest; } //help debug mining software function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if(uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { // Checks if sender has enough balance, checks for overflows, and checks if the sender or to accounts are frozen if ((balances[msg.sender] < tokens) || (balances[to] + tokens < balances[to]) || (frozenAccount[msg.sender]) || (frozenAccount[to])) { return false; } else { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[spender])) { return false; } else { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[from]) || (frozenAccount[to])) { return false; } else { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[spender])) { return false; } else { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } } function freezeAccount(address target, bool freeze) public onlyOwner { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } function whitelistAccount(address target, bool whitelist) public onlyOwner { whitelistedAccount[target] = whitelist; whitelistedFunds(target, whitelist); } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial fixed supply // ----------------------------------------------------------------------------
LineComment
function () public payable { revert(); }
// ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------
LineComment
v0.4.18+commit.9cf6e910
MIT
bzzr://36f2cb1a1a9ef7dc23ca6748643c1e70e2de61a55de2af8061617bc05ba7c865
{ "func_code_index": [ 14494, 14560 ] }
12,207
Kannabiz
Kannabiz.sol
0xd9506121d67fb918ac47af0b883730694be9377c
Solidity
Kannabiz
contract Kannabiz is ERC20Interface, Owned { using SafeMath for uint; using ExtendedMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public latestDifficultyPeriodStarted; uint public epochCount; //number of 'blocks' mined uint public _BLOCKS_PER_READJUSTMENT = 4; //a little number uint public _MINIMUM_TARGET = 2**16; //a big number is easier, just find a solution that is smaller //uint public _MAXIMUM_TARGET = 2**224; bitcoin uses 224 uint public _MAXIMUM_TARGET = 2**234; uint public miningTarget; bytes32 public challengeNumber; //generate a new one when a new reward is minted uint public rewardEra; uint public maxSupplyForEra; address public lastRewardTo; uint public lastRewardAmount; uint public lastRewardEthBlockNumber; bool locked = false; mapping(bytes32 => bytes32) solutionForChallenge; uint public tokensMinted; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; mapping(address => bool) public frozenAccount; // Array of frozen accounts mapping(address => bool) public whitelistedAccount; // Array of whitelisted accounts mapping(uint256 => uint256) public eraVsMaxSupplyFactor; event FrozenFunds(address target, bool frozen); event whitelistedFunds(address target, bool whitelisted); event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function Kannabiz() public onlyOwner { symbol = "KK"; name = "Kannabiz Koin"; decimals = 8; _totalSupply = 25000000000 * 10**uint(decimals); if(locked) revert(); locked = true; tokensMinted = 0; rewardEra = 0; miningTarget = _MAXIMUM_TARGET; latestDifficultyPeriodStarted = block.number; eraVsMaxSupplyFactor[0] = 5; eraVsMaxSupplyFactor[1] = 4; eraVsMaxSupplyFactor[2] = 3; eraVsMaxSupplyFactor[3] = 2; eraVsMaxSupplyFactor[4] = 2; eraVsMaxSupplyFactor[5] = 2; eraVsMaxSupplyFactor[6] = 2; eraVsMaxSupplyFactor[7] = 1; eraVsMaxSupplyFactor[8] = 1; eraVsMaxSupplyFactor[9] = 1; eraVsMaxSupplyFactor[10] = 1; eraVsMaxSupplyFactor[11] = 1; maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals); _startNewMiningEpoch(); } function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success) { if (whitelistedAccount[msg.sender]) { //the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks bytes32 digest = keccak256(challengeNumber, msg.sender, nonce ); //the challenge digest must match the expected if (digest != challenge_digest) revert(); //the digest must be smaller than the target if(uint256(digest) > miningTarget) revert(); //only allow one reward for each challenge bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if(solution != 0x0) revert(); //prevent the same answer from awarding twice uint reward_amount = getMiningReward(); balances[msg.sender] = balances[msg.sender].add(reward_amount); tokensMinted = tokensMinted.add(reward_amount); //Cannot mint more tokens than there are assert(tokensMinted <= maxSupplyForEra); assert(tokensMinted <= _totalSupply); //set readonly diagnostics data lastRewardTo = msg.sender; lastRewardAmount = reward_amount; lastRewardEthBlockNumber = block.number; _startNewMiningEpoch(); Mint(msg.sender, reward_amount, epochCount, challengeNumber ); return true; } else { return false; } } //a new 'block' to be mined function _startNewMiningEpoch() internal { //if max supply for the era will be exceeded next reward round then enter the new era before that happens //4 is the final reward era, almost all tokens minted //once the final era is reached, more tokens will not be given out because the assert function if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 12) { rewardEra = rewardEra + 1; maxSupplyForEra = eraVsMaxSupplyFactor[rewardEra].mul(1000000000) * 10**uint(decimals); } epochCount = epochCount.add(1); //every so often, readjust difficulty. Dont readjust when deploying if(epochCount % _BLOCKS_PER_READJUSTMENT == 0) { _reAdjustDifficulty(); } //make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks //do this last since this is a protection mechanism in the mint() function challengeNumber = block.blockhash(block.number - 1); } function _reAdjustDifficulty() internal { uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted; //assume 270 ethereum blocks per hour //we want miners to spend 10 minutes to mine each 'block', about 45 ethereum blocks = one Block X Token epoch uint epochsMined = _BLOCKS_PER_READJUSTMENT; //256 uint targetEthBlocksPerDiffPeriod = epochsMined * 48; //should be 48 times slower than ethereum //if there were less eth blocks passed in time than expected if( ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod ) { uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div( ethBlocksSinceLastDifficultyPeriod ); uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000); // If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100. //make it harder miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra)); //by up to 50 % } else { uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div( targetEthBlocksPerDiffPeriod ); uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); //always between 0 and 1000 //make it easier miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 % } latestDifficultyPeriodStarted = block.number; if(miningTarget < _MINIMUM_TARGET) //very difficult { miningTarget = _MINIMUM_TARGET; } if(miningTarget > _MAXIMUM_TARGET) //very easy { miningTarget = _MAXIMUM_TARGET; } } //this is a recent ethereum block hash, used to prevent pre-mining future blocks function getChallengeNumber() public constant returns (bytes32) { return challengeNumber; } //the number of zeroes the digest of the PoW solution requires. Auto adjusts function getMiningDifficulty() public constant returns (uint) { return _MAXIMUM_TARGET.div(miningTarget); } function getMiningTarget() public constant returns (uint) { return miningTarget; } //10,000,000,000 coins total //reward begins at 100,000 and is cut in half every reward era (as tokens are mined) function getMiningReward() public constant returns (uint) { //once we get half way thru the coins, only get 50,000 per block //every reward era, the reward amount halves. return (100000 * 10**uint(decimals) ).div(5).mul(eraVsMaxSupplyFactor[rewardEra]) ; } //help debug mining software function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if (challenge_digest == 9643712) { //suppress the warning } return digest; } //help debug mining software function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) { bytes32 digest = keccak256(challenge_number,msg.sender,nonce); if(uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { // Checks if sender has enough balance, checks for overflows, and checks if the sender or to accounts are frozen if ((balances[msg.sender] < tokens) || (balances[to] + tokens < balances[to]) || (frozenAccount[msg.sender]) || (frozenAccount[to])) { return false; } else { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[spender])) { return false; } else { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[from]) || (frozenAccount[to])) { return false; } else { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { if ((frozenAccount[msg.sender]) || (frozenAccount[spender])) { return false; } else { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } } function freezeAccount(address target, bool freeze) public onlyOwner { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } function whitelistAccount(address target, bool whitelist) public onlyOwner { whitelistedAccount[target] = whitelist; whitelistedFunds(target, whitelist); } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
// ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial fixed supply // ----------------------------------------------------------------------------
LineComment
transferAnyERC20Token
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); }
// ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------
LineComment
v0.4.18+commit.9cf6e910
MIT
bzzr://36f2cb1a1a9ef7dc23ca6748643c1e70e2de61a55de2af8061617bc05ba7c865
{ "func_code_index": [ 14794, 14990 ] }
12,208
Wrapped_JAXNET_Token_ERC20
contracts/Wrapped_JAXNET_Token.sol
0xca1262e77fb25c0a4112cfc9bad3ff54f617f2e6
Solidity
Wrapped_JAXNET_Token_ERC20
contract Wrapped_JAXNET_Token_ERC20 is Ownable, ERC20, Pausable { constructor(address owner) ERC20("Wrapped JAXNET", "WJXN") { _mint(owner, 40002164); _pause(); transferOwnership(owner); } function decimals() public pure override returns (uint8) { return 0; } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must be contract owner */ function pause() public onlyOwner { _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must be contract owner. */ function unpause() public onlyOwner { _unpause(); } /** * @dev Check if system is not paused. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } /** * @dev Destroys `amount` tokens from the caller. */ function burn(uint256 amount) public onlyOwner { _burn(_msgSender(), amount); } }
/* This contract created to support token distribution in JaxNet project * By default, all transfers are paused. Except function, transferFromOwner, which allows * to distribute tokens. * Supply is limited to 40002164 * Owner of contract may burn coins from his account */
Comment
pause
function pause() public onlyOwner { _pause(); }
/** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must be contract owner */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 506, 569 ] }
12,209
Wrapped_JAXNET_Token_ERC20
contracts/Wrapped_JAXNET_Token.sol
0xca1262e77fb25c0a4112cfc9bad3ff54f617f2e6
Solidity
Wrapped_JAXNET_Token_ERC20
contract Wrapped_JAXNET_Token_ERC20 is Ownable, ERC20, Pausable { constructor(address owner) ERC20("Wrapped JAXNET", "WJXN") { _mint(owner, 40002164); _pause(); transferOwnership(owner); } function decimals() public pure override returns (uint8) { return 0; } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must be contract owner */ function pause() public onlyOwner { _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must be contract owner. */ function unpause() public onlyOwner { _unpause(); } /** * @dev Check if system is not paused. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } /** * @dev Destroys `amount` tokens from the caller. */ function burn(uint256 amount) public onlyOwner { _burn(_msgSender(), amount); } }
/* This contract created to support token distribution in JaxNet project * By default, all transfers are paused. Except function, transferFromOwner, which allows * to distribute tokens. * Supply is limited to 40002164 * Owner of contract may burn coins from his account */
Comment
unpause
function unpause() public onlyOwner { _unpause(); }
/** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must be contract owner. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 767, 834 ] }
12,210
Wrapped_JAXNET_Token_ERC20
contracts/Wrapped_JAXNET_Token.sol
0xca1262e77fb25c0a4112cfc9bad3ff54f617f2e6
Solidity
Wrapped_JAXNET_Token_ERC20
contract Wrapped_JAXNET_Token_ERC20 is Ownable, ERC20, Pausable { constructor(address owner) ERC20("Wrapped JAXNET", "WJXN") { _mint(owner, 40002164); _pause(); transferOwnership(owner); } function decimals() public pure override returns (uint8) { return 0; } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must be contract owner */ function pause() public onlyOwner { _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must be contract owner. */ function unpause() public onlyOwner { _unpause(); } /** * @dev Check if system is not paused. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } /** * @dev Destroys `amount` tokens from the caller. */ function burn(uint256 amount) public onlyOwner { _burn(_msgSender(), amount); } }
/* This contract created to support token distribution in JaxNet project * By default, all transfers are paused. Except function, transferFromOwner, which allows * to distribute tokens. * Supply is limited to 40002164 * Owner of contract may burn coins from his account */
Comment
_beforeTokenTransfer
function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); }
/** * @dev Check if system is not paused. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 896, 1156 ] }
12,211
Wrapped_JAXNET_Token_ERC20
contracts/Wrapped_JAXNET_Token.sol
0xca1262e77fb25c0a4112cfc9bad3ff54f617f2e6
Solidity
Wrapped_JAXNET_Token_ERC20
contract Wrapped_JAXNET_Token_ERC20 is Ownable, ERC20, Pausable { constructor(address owner) ERC20("Wrapped JAXNET", "WJXN") { _mint(owner, 40002164); _pause(); transferOwnership(owner); } function decimals() public pure override returns (uint8) { return 0; } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must be contract owner */ function pause() public onlyOwner { _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must be contract owner. */ function unpause() public onlyOwner { _unpause(); } /** * @dev Check if system is not paused. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } /** * @dev Destroys `amount` tokens from the caller. */ function burn(uint256 amount) public onlyOwner { _burn(_msgSender(), amount); } }
/* This contract created to support token distribution in JaxNet project * By default, all transfers are paused. Except function, transferFromOwner, which allows * to distribute tokens. * Supply is limited to 40002164 * Owner of contract may burn coins from his account */
Comment
burn
function burn(uint256 amount) public onlyOwner { _burn(_msgSender(), amount); }
/** * @dev Destroys `amount` tokens from the caller. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
{ "func_code_index": [ 1228, 1323 ] }
12,212
EsportsPro
@openzeppelin\contracts\token\ERC20\ERC20Capped.sol
0x29c56e7cb9c840d2b2371b17e28bab44ad3c3ead
Solidity
ERC20Capped
abstract contract ERC20Capped is ERC20 { using SafeMath for uint256; uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap_) internal { require(cap_ > 0, "ERC20Capped: cap is 0"); _cap = cap_; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view virtual returns (uint256) { return _cap; } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require(totalSupply().add(amount) <= cap(), "ERC20Capped: cap exceeded"); } } }
/** * @dev Extension of {ERC20} that adds a cap to the supply of tokens. */
NatSpecMultiLine
cap
function cap() public view virtual returns (uint256) { return _cap; }
/** * @dev Returns the cap on the token's total supply. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://e48c8eeefff0faddbad81c0ec41116429af4e84586d2d4749ad34c84e493fa75
{ "func_code_index": [ 447, 535 ] }
12,213
EsportsPro
@openzeppelin\contracts\token\ERC20\ERC20Capped.sol
0x29c56e7cb9c840d2b2371b17e28bab44ad3c3ead
Solidity
ERC20Capped
abstract contract ERC20Capped is ERC20 { using SafeMath for uint256; uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap_) internal { require(cap_ > 0, "ERC20Capped: cap is 0"); _cap = cap_; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view virtual returns (uint256) { return _cap; } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require(totalSupply().add(amount) <= cap(), "ERC20Capped: cap exceeded"); } } }
/** * @dev Extension of {ERC20} that adds a cap to the supply of tokens. */
NatSpecMultiLine
_beforeTokenTransfer
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require(totalSupply().add(amount) <= cap(), "ERC20Capped: cap exceeded"); } }
/** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://e48c8eeefff0faddbad81c0ec41116429af4e84586d2d4749ad34c84e493fa75
{ "func_code_index": [ 717, 1041 ] }
12,214
SpiderFarm
SpiderFarm.sol
0x25e1779f5f2fbdd378ced1a338f6c26aeb3d6ad0
Solidity
SpiderFarm
contract SpiderFarm{ //uint256 EGGS_PER_SHRIMP_PER_SECOND=1; uint256 public EGGS_TO_HATCH_1SHRIMP=86400;//for final version should be seconds in a day uint256 public STARTING_SHRIMP=50; uint256 PSN=10000; uint256 PSNH=5000; uint256 startTime; bool public initialized=false; address public ceoAddress; address public owner; mapping (address => uint256) public hatcheryShrimp; mapping (address => uint256) public claimedEggs; mapping (address => uint256) public lastHatch; mapping (address => address) public referrals; uint256 public marketEggs; uint256 public snailmasterReq=100000; function becomeSnailmaster() public{ uint256 hasEggs=getMyEggs(); uint256 eggCount=SafeMath.div(hasEggs,EGGS_TO_HATCH_1SHRIMP); require(initialized); require(msg.sender != ceoAddress); require(eggCount>=snailmasterReq); claimedEggs[msg.sender]=0; snailmasterReq=SafeMath.add(snailmasterReq,100000);//+100k shrimps each time ceoAddress=msg.sender; } function hatchEggs(address ref) public{ require(initialized); if(referrals[msg.sender]==0 && referrals[msg.sender]!=msg.sender){ referrals[msg.sender]=ref; } uint256 eggsUsed=getMyEggs(); uint256 newShrimp=SafeMath.div(eggsUsed,EGGS_TO_HATCH_1SHRIMP); uint256 timer=tmp(); hatcheryShrimp[msg.sender]=SafeMath.add(hatcheryShrimp[msg.sender],newShrimp); claimedEggs[msg.sender]=0; lastHatch[msg.sender]=now; if (timer>=1) { marketEggs=SafeMath.mul(SafeMath.div(marketEggs,5),4); startTime=now; } //send referral eggs claimedEggs[referrals[msg.sender]]=SafeMath.add(claimedEggs[referrals[msg.sender]],SafeMath.div(eggsUsed,10)); //boost market to nerf hoarding marketEggs=SafeMath.add(marketEggs,SafeMath.div(eggsUsed,10)); } function sellEggs() public{ require(initialized); uint256 hasEggs=getMyEggs(); uint256 eggValue=calculateEggSell(hasEggs); uint256 fee=devFee(eggValue); uint256 fee2=devFee2(eggValue); uint256 overallfee=SafeMath.add(fee,fee2); // one third of investors die on dump hatcheryShrimp[msg.sender]=SafeMath.mul(SafeMath.div(hatcheryShrimp[msg.sender],3),2); claimedEggs[msg.sender]=0; lastHatch[msg.sender]=now; marketEggs=SafeMath.add(marketEggs,hasEggs); ceoAddress.transfer(fee); owner.transfer(fee2); msg.sender.transfer(SafeMath.sub(eggValue,overallfee)); } function buyEggs() public payable{ require(initialized); uint256 fee=devFee(eggsBought); uint256 fee2=devFee2(eggsBought); uint256 overallfee=SafeMath.add(fee,fee2); uint256 eggsBought=calculateEggBuy(msg.value,SafeMath.sub(this.balance,msg.value)); eggsBought=SafeMath.sub(eggsBought,overallfee); ceoAddress.transfer(devFee(msg.value)); owner.transfer(devFee2(msg.value)); claimedEggs[msg.sender]=SafeMath.add(claimedEggs[msg.sender],eggsBought); } //magic trade balancing algorithm function calculateTrade(uint256 rt,uint256 rs, uint256 bs) public view returns(uint256){ //(PSN*bs)/(PSNH+((PSN*rs+PSNH*rt)/rt)); return SafeMath.div(SafeMath.mul(PSN,bs),SafeMath.add(PSNH,SafeMath.div(SafeMath.add(SafeMath.mul(PSN,rs),SafeMath.mul(PSNH,rt)),rt))); } function calculateEggSell(uint256 eggs) public view returns(uint256){ return calculateTrade(eggs,marketEggs,this.balance); } function calculateEggBuy(uint256 eth,uint256 contractBalance) public view returns(uint256){ return calculateTrade(eth,contractBalance,marketEggs); } function calculateEggBuySimple(uint256 eth) public view returns(uint256){ return calculateEggBuy(eth,this.balance); } function devFee(uint256 amount) public view returns(uint256){ return SafeMath.div(SafeMath.mul(amount,2),100); } function devFee2(uint256 amount) public view returns(uint256){ return SafeMath.div(SafeMath.mul(amount,3),100); } function seedMarket(uint256 eggs) public payable{ require(marketEggs==0); initialized=true; marketEggs=eggs; } function getFreeShrimp() public payable{ require(initialized); require(msg.value==0.001 ether); ceoAddress.transfer(msg.value); //goes to spider queen require(hatcheryShrimp[msg.sender]==0); lastHatch[msg.sender]=now; hatcheryShrimp[msg.sender]=STARTING_SHRIMP; } function getBalance() public view returns(uint256){ return this.balance; } function getMyShrimp() public view returns(uint256){ return hatcheryShrimp[msg.sender]; } function getSnailmasterReq() public view returns(uint256){ return snailmasterReq; } function getMyEggs() public view returns(uint256){ return SafeMath.add(claimedEggs[msg.sender],getEggsSinceLastHatch(msg.sender)); } function updateEggs() public view returns(uint256){ return SafeMath.sub(claimedEggs[msg.sender],snailmasterReq); } function SpiderFarm() public{ ceoAddress=msg.sender; owner=0xa76490c1f5fbf4d5101430c3cd2E63f33D21C738; } function getEggsSinceLastHatch(address adr) public view returns(uint256){ uint256 secondsPassed=min(EGGS_TO_HATCH_1SHRIMP,SafeMath.sub(now,lastHatch[adr])); return SafeMath.mul(secondsPassed,hatcheryShrimp[adr]); } function min(uint256 a, uint256 b) private pure returns (uint256) { return a < b ? a : b; } function tmp() public returns(uint){ require(startTime != 0); return (now - startTime)/(4320 minutes); } function callThisToStart() public { if(owner != msg.sender) throw; startTime = now; } function callThisToStop() public { if(owner != msg.sender) throw; startTime = 0; } }
// similar to shrimp/snail // you lose one third of your spiders on sell anti-inflation + longevity // freebies on a set price of 0.001 and only 50 anti-bot // every three days the global eggs are reduced by 20% anti-inflation // you are able to compete for the spider queen which gives you 3% of the fees and the fixed 0.001 of the freebies competition + longevity // if you buy the title you lose a set amound of eggs, first title costs 100000 eggs, adding 100k each time anti-inflation + competition + longevity // lower seed of 864000000 instead of 8640000000 to make the early game slower, more fair and stop hyperinflation anti-inflation + competition + longevity // lower referral (10%) to fight ref abuse as seen on shrimp anti-inflation + anti-bot
LineComment
calculateTrade
function calculateTrade(uint256 rt,uint256 rs, uint256 bs) public view returns(uint256){ //(PSN*bs)/(PSNH+((PSN*rs+PSNH*rt)/rt)); return SafeMath.div(SafeMath.mul(PSN,bs),SafeMath.add(PSNH,SafeMath.div(SafeMath.add(SafeMath.mul(PSN,rs),SafeMath.mul(PSNH,rt)),rt))); }
//magic trade balancing algorithm
LineComment
v0.4.24+commit.e67f0147
bzzr://08973e877a676516cd38692b1311ee013ce7d4b71d521f8ac4771785966ea2ac
{ "func_code_index": [ 3298, 3593 ] }
12,215
SpiderFarm
SpiderFarm.sol
0x25e1779f5f2fbdd378ced1a338f6c26aeb3d6ad0
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; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
mul
function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; }
/** * @dev Multiplies two numbers, throws on overflow. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://08973e877a676516cd38692b1311ee013ce7d4b71d521f8ac4771785966ea2ac
{ "func_code_index": [ 89, 272 ] }
12,216
SpiderFarm
SpiderFarm.sol
0x25e1779f5f2fbdd378ced1a338f6c26aeb3d6ad0
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; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
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 c; }
/** * @dev Integer division of two numbers, truncating the quotient. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://08973e877a676516cd38692b1311ee013ce7d4b71d521f8ac4771785966ea2ac
{ "func_code_index": [ 356, 629 ] }
12,217
SpiderFarm
SpiderFarm.sol
0x25e1779f5f2fbdd378ced1a338f6c26aeb3d6ad0
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; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; }
/** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://08973e877a676516cd38692b1311ee013ce7d4b71d521f8ac4771785966ea2ac
{ "func_code_index": [ 744, 860 ] }
12,218
SpiderFarm
SpiderFarm.sol
0x25e1779f5f2fbdd378ced1a338f6c26aeb3d6ad0
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; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
add
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; }
/** * @dev Adds two numbers, throws on overflow. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://08973e877a676516cd38692b1311ee013ce7d4b71d521f8ac4771785966ea2ac
{ "func_code_index": [ 924, 1060 ] }
12,219
BabyAXIE
@openzeppelin/contracts/token/ERC20/IERC20.sol
0x39db8e213ebf84d713383bf51c621d210bc1fa17
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
name
function name() public view virtual override returns (string memory) { return _name; }
/** * @dev Returns the name of the token. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
MIT
ipfs://a9bfcd486b1700b948ab2234b7cda1203427abeeef98f725108722ab9937fa21
{ "func_code_index": [ 779, 884 ] }
12,220
BabyAXIE
@openzeppelin/contracts/token/ERC20/IERC20.sol
0x39db8e213ebf84d713383bf51c621d210bc1fa17
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
symbol
function symbol() public view virtual override returns (string memory) { return _symbol; }
/** * @dev Returns the symbol of the token, usually a shorter version of the * name. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
MIT
ipfs://a9bfcd486b1700b948ab2234b7cda1203427abeeef98f725108722ab9937fa21
{ "func_code_index": [ 998, 1107 ] }
12,221
BabyAXIE
@openzeppelin/contracts/token/ERC20/IERC20.sol
0x39db8e213ebf84d713383bf51c621d210bc1fa17
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
decimals
function decimals() public view virtual override returns (uint8) { return 18; }
/** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
MIT
ipfs://a9bfcd486b1700b948ab2234b7cda1203427abeeef98f725108722ab9937fa21
{ "func_code_index": [ 1741, 1839 ] }
12,222
BabyAXIE
@openzeppelin/contracts/token/ERC20/IERC20.sol
0x39db8e213ebf84d713383bf51c621d210bc1fa17
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
totalSupply
function totalSupply() public view virtual override returns (uint256) { return _totalSupply; }
/** * @dev See {IERC20-totalSupply}. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
MIT
ipfs://a9bfcd486b1700b948ab2234b7cda1203427abeeef98f725108722ab9937fa21
{ "func_code_index": [ 1899, 2012 ] }
12,223
BabyAXIE
@openzeppelin/contracts/token/ERC20/IERC20.sol
0x39db8e213ebf84d713383bf51c621d210bc1fa17
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
balanceOf
function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; }
/** * @dev See {IERC20-balanceOf}. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
MIT
ipfs://a9bfcd486b1700b948ab2234b7cda1203427abeeef98f725108722ab9937fa21
{ "func_code_index": [ 2070, 2202 ] }
12,224
BabyAXIE
@openzeppelin/contracts/token/ERC20/IERC20.sol
0x39db8e213ebf84d713383bf51c621d210bc1fa17
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
transfer
function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); 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.8.4+commit.c7e474f2
MIT
ipfs://a9bfcd486b1700b948ab2234b7cda1203427abeeef98f725108722ab9937fa21
{ "func_code_index": [ 2410, 2590 ] }
12,225
BabyAXIE
@openzeppelin/contracts/token/ERC20/IERC20.sol
0x39db8e213ebf84d713383bf51c621d210bc1fa17
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
allowance
function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; }
/** * @dev See {IERC20-allowance}. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
MIT
ipfs://a9bfcd486b1700b948ab2234b7cda1203427abeeef98f725108722ab9937fa21
{ "func_code_index": [ 2648, 2804 ] }
12,226
BabyAXIE
@openzeppelin/contracts/token/ERC20/IERC20.sol
0x39db8e213ebf84d713383bf51c621d210bc1fa17
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
approve
function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; }
/** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
MIT
ipfs://a9bfcd486b1700b948ab2234b7cda1203427abeeef98f725108722ab9937fa21
{ "func_code_index": [ 2946, 3120 ] }
12,227
BabyAXIE
@openzeppelin/contracts/token/ERC20/IERC20.sol
0x39db8e213ebf84d713383bf51c621d210bc1fa17
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
transferFrom
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; }
/** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
MIT
ipfs://a9bfcd486b1700b948ab2234b7cda1203427abeeef98f725108722ab9937fa21
{ "func_code_index": [ 3597, 4024 ] }
12,228
BabyAXIE
@openzeppelin/contracts/token/ERC20/IERC20.sol
0x39db8e213ebf84d713383bf51c621d210bc1fa17
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
increaseAllowance
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; }
/** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
MIT
ipfs://a9bfcd486b1700b948ab2234b7cda1203427abeeef98f725108722ab9937fa21
{ "func_code_index": [ 4428, 4648 ] }
12,229
BabyAXIE
@openzeppelin/contracts/token/ERC20/IERC20.sol
0x39db8e213ebf84d713383bf51c621d210bc1fa17
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
decreaseAllowance
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; }
/** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
MIT
ipfs://a9bfcd486b1700b948ab2234b7cda1203427abeeef98f725108722ab9937fa21
{ "func_code_index": [ 5146, 5528 ] }
12,230
BabyAXIE
@openzeppelin/contracts/token/ERC20/IERC20.sol
0x39db8e213ebf84d713383bf51c621d210bc1fa17
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
_transfer
function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); }
/** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
MIT
ipfs://a9bfcd486b1700b948ab2234b7cda1203427abeeef98f725108722ab9937fa21
{ "func_code_index": [ 6013, 6622 ] }
12,231
BabyAXIE
@openzeppelin/contracts/token/ERC20/IERC20.sol
0x39db8e213ebf84d713383bf51c621d210bc1fa17
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
_mint
function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); }
/** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
MIT
ipfs://a9bfcd486b1700b948ab2234b7cda1203427abeeef98f725108722ab9937fa21
{ "func_code_index": [ 6899, 7242 ] }
12,232
BabyAXIE
@openzeppelin/contracts/token/ERC20/IERC20.sol
0x39db8e213ebf84d713383bf51c621d210bc1fa17
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
_burn
function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); }
/** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
MIT
ipfs://a9bfcd486b1700b948ab2234b7cda1203427abeeef98f725108722ab9937fa21
{ "func_code_index": [ 7570, 8069 ] }
12,233
BabyAXIE
@openzeppelin/contracts/token/ERC20/IERC20.sol
0x39db8e213ebf84d713383bf51c621d210bc1fa17
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
_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 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.8.4+commit.c7e474f2
MIT
ipfs://a9bfcd486b1700b948ab2234b7cda1203427abeeef98f725108722ab9937fa21
{ "func_code_index": [ 8502, 8853 ] }
12,234
BabyAXIE
@openzeppelin/contracts/token/ERC20/IERC20.sol
0x39db8e213ebf84d713383bf51c621d210bc1fa17
Solidity
ERC20
contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
_beforeTokenTransfer
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
/** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
MIT
ipfs://a9bfcd486b1700b948ab2234b7cda1203427abeeef98f725108722ab9937fa21
{ "func_code_index": [ 9451, 9548 ] }
12,235
BabyAXIE
@openzeppelin/contracts/token/ERC20/IERC20.sol
0x39db8e213ebf84d713383bf51c621d210bc1fa17
Solidity
BabyAXIE
contract BabyAXIE is ERC20, Owned { uint256 public minSupply; address public beneficiary; bool public feesEnabled; mapping(address => bool) public isExcludedFromFee; event MinSupplyUpdated(uint256 oldAmount, uint256 newAmount); event BeneficiaryUpdated(address oldBeneficiary, address newBeneficiary); event FeesEnabledUpdated(bool enabled); event ExcludedFromFeeUpdated(address account, bool excluded); constructor() ERC20("BabyAXIE", "BabyAXIE") { minSupply = 100000000 ether; uint256 totalSupply = 1000000000000000 ether; feesEnabled = false; _mint(_msgSender(), totalSupply); isExcludedFromFee[msg.sender] = true; isExcludedFromFee[0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = true; beneficiary = msg.sender; } /** * @dev if fees are enabled, subtract 2.25% fee and send it to beneficiary * @dev after a certain threshold, try to swap collected fees automatically * @dev if automatic swap fails (or beneficiary does not implement swapTokens function) transfer should still succeed */ function _transfer( address sender, address recipient, uint256 amount ) internal override { require( recipient != address(this), "Cannot send tokens to token contract" ); if ( !feesEnabled || isExcludedFromFee[sender] || isExcludedFromFee[recipient] ) { ERC20._transfer(sender, recipient, amount); return; } // burn tokens if min supply not reached yet uint256 burnedFee = calculateFee(amount, 25); if (totalSupply() - burnedFee >= minSupply) { _burn(sender, burnedFee); } else { burnedFee = 0; } uint256 transferFee = calculateFee(amount, 200); ERC20._transfer(sender, beneficiary, transferFee); ERC20._transfer(sender, recipient, amount - transferFee - burnedFee); } function calculateFee(uint256 _amount, uint256 _fee) public pure returns (uint256) { return (_amount * _fee) / 10000; } /** * @notice allows to burn tokens from own balance * @dev only allows burning tokens until minimum supply is reached * @param value amount of tokens to burn */ function burn(uint256 value) public { _burn(_msgSender(), value); require(totalSupply() >= minSupply, "total supply exceeds min supply"); } /** * @notice sets minimum supply of the token * @dev only callable by owner * @param _newMinSupply new minimum supply */ function setMinSupply(uint256 _newMinSupply) public onlyOwner { emit MinSupplyUpdated(minSupply, _newMinSupply); minSupply = _newMinSupply; } /** * @notice sets recipient of transfer fee * @dev only callable by owner * @param _newBeneficiary new beneficiary */ function setBeneficiary(address _newBeneficiary) public onlyOwner { setExcludeFromFee(_newBeneficiary, true); emit BeneficiaryUpdated(beneficiary, _newBeneficiary); beneficiary = _newBeneficiary; } /** * @notice sets whether account collects fees on token transfer * @dev only callable by owner * @param _enabled bool whether fees are enabled */ function setFeesEnabled(bool _enabled) public onlyOwner { emit FeesEnabledUpdated(_enabled); feesEnabled = _enabled; } /** * @notice adds or removes an account that is exempt from fee collection * @dev only callable by owner * @param _account account to modify * @param _excluded new value */ function setExcludeFromFee(address _account, bool _excluded) public onlyOwner { isExcludedFromFee[_account] = _excluded; emit ExcludedFromFeeUpdated(_account, _excluded); } }
_transfer
function _transfer( address sender, address recipient, uint256 amount ) internal override { require( recipient != address(this), "Cannot send tokens to token contract" ); if ( !feesEnabled || isExcludedFromFee[sender] || isExcludedFromFee[recipient] ) { ERC20._transfer(sender, recipient, amount); return; } // burn tokens if min supply not reached yet uint256 burnedFee = calculateFee(amount, 25); if (totalSupply() - burnedFee >= minSupply) { _burn(sender, burnedFee); } else { burnedFee = 0; } uint256 transferFee = calculateFee(amount, 200); ERC20._transfer(sender, beneficiary, transferFee); ERC20._transfer(sender, recipient, amount - transferFee - burnedFee); }
/** * @dev if fees are enabled, subtract 2.25% fee and send it to beneficiary * @dev after a certain threshold, try to swap collected fees automatically * @dev if automatic swap fails (or beneficiary does not implement swapTokens function) transfer should still succeed */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
MIT
ipfs://a9bfcd486b1700b948ab2234b7cda1203427abeeef98f725108722ab9937fa21
{ "func_code_index": [ 1139, 2083 ] }
12,236
BabyAXIE
@openzeppelin/contracts/token/ERC20/IERC20.sol
0x39db8e213ebf84d713383bf51c621d210bc1fa17
Solidity
BabyAXIE
contract BabyAXIE is ERC20, Owned { uint256 public minSupply; address public beneficiary; bool public feesEnabled; mapping(address => bool) public isExcludedFromFee; event MinSupplyUpdated(uint256 oldAmount, uint256 newAmount); event BeneficiaryUpdated(address oldBeneficiary, address newBeneficiary); event FeesEnabledUpdated(bool enabled); event ExcludedFromFeeUpdated(address account, bool excluded); constructor() ERC20("BabyAXIE", "BabyAXIE") { minSupply = 100000000 ether; uint256 totalSupply = 1000000000000000 ether; feesEnabled = false; _mint(_msgSender(), totalSupply); isExcludedFromFee[msg.sender] = true; isExcludedFromFee[0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = true; beneficiary = msg.sender; } /** * @dev if fees are enabled, subtract 2.25% fee and send it to beneficiary * @dev after a certain threshold, try to swap collected fees automatically * @dev if automatic swap fails (or beneficiary does not implement swapTokens function) transfer should still succeed */ function _transfer( address sender, address recipient, uint256 amount ) internal override { require( recipient != address(this), "Cannot send tokens to token contract" ); if ( !feesEnabled || isExcludedFromFee[sender] || isExcludedFromFee[recipient] ) { ERC20._transfer(sender, recipient, amount); return; } // burn tokens if min supply not reached yet uint256 burnedFee = calculateFee(amount, 25); if (totalSupply() - burnedFee >= minSupply) { _burn(sender, burnedFee); } else { burnedFee = 0; } uint256 transferFee = calculateFee(amount, 200); ERC20._transfer(sender, beneficiary, transferFee); ERC20._transfer(sender, recipient, amount - transferFee - burnedFee); } function calculateFee(uint256 _amount, uint256 _fee) public pure returns (uint256) { return (_amount * _fee) / 10000; } /** * @notice allows to burn tokens from own balance * @dev only allows burning tokens until minimum supply is reached * @param value amount of tokens to burn */ function burn(uint256 value) public { _burn(_msgSender(), value); require(totalSupply() >= minSupply, "total supply exceeds min supply"); } /** * @notice sets minimum supply of the token * @dev only callable by owner * @param _newMinSupply new minimum supply */ function setMinSupply(uint256 _newMinSupply) public onlyOwner { emit MinSupplyUpdated(minSupply, _newMinSupply); minSupply = _newMinSupply; } /** * @notice sets recipient of transfer fee * @dev only callable by owner * @param _newBeneficiary new beneficiary */ function setBeneficiary(address _newBeneficiary) public onlyOwner { setExcludeFromFee(_newBeneficiary, true); emit BeneficiaryUpdated(beneficiary, _newBeneficiary); beneficiary = _newBeneficiary; } /** * @notice sets whether account collects fees on token transfer * @dev only callable by owner * @param _enabled bool whether fees are enabled */ function setFeesEnabled(bool _enabled) public onlyOwner { emit FeesEnabledUpdated(_enabled); feesEnabled = _enabled; } /** * @notice adds or removes an account that is exempt from fee collection * @dev only callable by owner * @param _account account to modify * @param _excluded new value */ function setExcludeFromFee(address _account, bool _excluded) public onlyOwner { isExcludedFromFee[_account] = _excluded; emit ExcludedFromFeeUpdated(_account, _excluded); } }
burn
function burn(uint256 value) public { _burn(_msgSender(), value); require(totalSupply() >= minSupply, "total supply exceeds min supply"); }
/** * @notice allows to burn tokens from own balance * @dev only allows burning tokens until minimum supply is reached * @param value amount of tokens to burn */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
MIT
ipfs://a9bfcd486b1700b948ab2234b7cda1203427abeeef98f725108722ab9937fa21
{ "func_code_index": [ 2450, 2617 ] }
12,237
BabyAXIE
@openzeppelin/contracts/token/ERC20/IERC20.sol
0x39db8e213ebf84d713383bf51c621d210bc1fa17
Solidity
BabyAXIE
contract BabyAXIE is ERC20, Owned { uint256 public minSupply; address public beneficiary; bool public feesEnabled; mapping(address => bool) public isExcludedFromFee; event MinSupplyUpdated(uint256 oldAmount, uint256 newAmount); event BeneficiaryUpdated(address oldBeneficiary, address newBeneficiary); event FeesEnabledUpdated(bool enabled); event ExcludedFromFeeUpdated(address account, bool excluded); constructor() ERC20("BabyAXIE", "BabyAXIE") { minSupply = 100000000 ether; uint256 totalSupply = 1000000000000000 ether; feesEnabled = false; _mint(_msgSender(), totalSupply); isExcludedFromFee[msg.sender] = true; isExcludedFromFee[0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = true; beneficiary = msg.sender; } /** * @dev if fees are enabled, subtract 2.25% fee and send it to beneficiary * @dev after a certain threshold, try to swap collected fees automatically * @dev if automatic swap fails (or beneficiary does not implement swapTokens function) transfer should still succeed */ function _transfer( address sender, address recipient, uint256 amount ) internal override { require( recipient != address(this), "Cannot send tokens to token contract" ); if ( !feesEnabled || isExcludedFromFee[sender] || isExcludedFromFee[recipient] ) { ERC20._transfer(sender, recipient, amount); return; } // burn tokens if min supply not reached yet uint256 burnedFee = calculateFee(amount, 25); if (totalSupply() - burnedFee >= minSupply) { _burn(sender, burnedFee); } else { burnedFee = 0; } uint256 transferFee = calculateFee(amount, 200); ERC20._transfer(sender, beneficiary, transferFee); ERC20._transfer(sender, recipient, amount - transferFee - burnedFee); } function calculateFee(uint256 _amount, uint256 _fee) public pure returns (uint256) { return (_amount * _fee) / 10000; } /** * @notice allows to burn tokens from own balance * @dev only allows burning tokens until minimum supply is reached * @param value amount of tokens to burn */ function burn(uint256 value) public { _burn(_msgSender(), value); require(totalSupply() >= minSupply, "total supply exceeds min supply"); } /** * @notice sets minimum supply of the token * @dev only callable by owner * @param _newMinSupply new minimum supply */ function setMinSupply(uint256 _newMinSupply) public onlyOwner { emit MinSupplyUpdated(minSupply, _newMinSupply); minSupply = _newMinSupply; } /** * @notice sets recipient of transfer fee * @dev only callable by owner * @param _newBeneficiary new beneficiary */ function setBeneficiary(address _newBeneficiary) public onlyOwner { setExcludeFromFee(_newBeneficiary, true); emit BeneficiaryUpdated(beneficiary, _newBeneficiary); beneficiary = _newBeneficiary; } /** * @notice sets whether account collects fees on token transfer * @dev only callable by owner * @param _enabled bool whether fees are enabled */ function setFeesEnabled(bool _enabled) public onlyOwner { emit FeesEnabledUpdated(_enabled); feesEnabled = _enabled; } /** * @notice adds or removes an account that is exempt from fee collection * @dev only callable by owner * @param _account account to modify * @param _excluded new value */ function setExcludeFromFee(address _account, bool _excluded) public onlyOwner { isExcludedFromFee[_account] = _excluded; emit ExcludedFromFeeUpdated(_account, _excluded); } }
setMinSupply
function setMinSupply(uint256 _newMinSupply) public onlyOwner { emit MinSupplyUpdated(minSupply, _newMinSupply); minSupply = _newMinSupply; }
/** * @notice sets minimum supply of the token * @dev only callable by owner * @param _newMinSupply new minimum supply */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
MIT
ipfs://a9bfcd486b1700b948ab2234b7cda1203427abeeef98f725108722ab9937fa21
{ "func_code_index": [ 2771, 2940 ] }
12,238
BabyAXIE
@openzeppelin/contracts/token/ERC20/IERC20.sol
0x39db8e213ebf84d713383bf51c621d210bc1fa17
Solidity
BabyAXIE
contract BabyAXIE is ERC20, Owned { uint256 public minSupply; address public beneficiary; bool public feesEnabled; mapping(address => bool) public isExcludedFromFee; event MinSupplyUpdated(uint256 oldAmount, uint256 newAmount); event BeneficiaryUpdated(address oldBeneficiary, address newBeneficiary); event FeesEnabledUpdated(bool enabled); event ExcludedFromFeeUpdated(address account, bool excluded); constructor() ERC20("BabyAXIE", "BabyAXIE") { minSupply = 100000000 ether; uint256 totalSupply = 1000000000000000 ether; feesEnabled = false; _mint(_msgSender(), totalSupply); isExcludedFromFee[msg.sender] = true; isExcludedFromFee[0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = true; beneficiary = msg.sender; } /** * @dev if fees are enabled, subtract 2.25% fee and send it to beneficiary * @dev after a certain threshold, try to swap collected fees automatically * @dev if automatic swap fails (or beneficiary does not implement swapTokens function) transfer should still succeed */ function _transfer( address sender, address recipient, uint256 amount ) internal override { require( recipient != address(this), "Cannot send tokens to token contract" ); if ( !feesEnabled || isExcludedFromFee[sender] || isExcludedFromFee[recipient] ) { ERC20._transfer(sender, recipient, amount); return; } // burn tokens if min supply not reached yet uint256 burnedFee = calculateFee(amount, 25); if (totalSupply() - burnedFee >= minSupply) { _burn(sender, burnedFee); } else { burnedFee = 0; } uint256 transferFee = calculateFee(amount, 200); ERC20._transfer(sender, beneficiary, transferFee); ERC20._transfer(sender, recipient, amount - transferFee - burnedFee); } function calculateFee(uint256 _amount, uint256 _fee) public pure returns (uint256) { return (_amount * _fee) / 10000; } /** * @notice allows to burn tokens from own balance * @dev only allows burning tokens until minimum supply is reached * @param value amount of tokens to burn */ function burn(uint256 value) public { _burn(_msgSender(), value); require(totalSupply() >= minSupply, "total supply exceeds min supply"); } /** * @notice sets minimum supply of the token * @dev only callable by owner * @param _newMinSupply new minimum supply */ function setMinSupply(uint256 _newMinSupply) public onlyOwner { emit MinSupplyUpdated(minSupply, _newMinSupply); minSupply = _newMinSupply; } /** * @notice sets recipient of transfer fee * @dev only callable by owner * @param _newBeneficiary new beneficiary */ function setBeneficiary(address _newBeneficiary) public onlyOwner { setExcludeFromFee(_newBeneficiary, true); emit BeneficiaryUpdated(beneficiary, _newBeneficiary); beneficiary = _newBeneficiary; } /** * @notice sets whether account collects fees on token transfer * @dev only callable by owner * @param _enabled bool whether fees are enabled */ function setFeesEnabled(bool _enabled) public onlyOwner { emit FeesEnabledUpdated(_enabled); feesEnabled = _enabled; } /** * @notice adds or removes an account that is exempt from fee collection * @dev only callable by owner * @param _account account to modify * @param _excluded new value */ function setExcludeFromFee(address _account, bool _excluded) public onlyOwner { isExcludedFromFee[_account] = _excluded; emit ExcludedFromFeeUpdated(_account, _excluded); } }
setBeneficiary
function setBeneficiary(address _newBeneficiary) public onlyOwner { setExcludeFromFee(_newBeneficiary, true); emit BeneficiaryUpdated(beneficiary, _newBeneficiary); beneficiary = _newBeneficiary; }
/** * @notice sets recipient of transfer fee * @dev only callable by owner * @param _newBeneficiary new beneficiary */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
MIT
ipfs://a9bfcd486b1700b948ab2234b7cda1203427abeeef98f725108722ab9937fa21
{ "func_code_index": [ 3096, 3330 ] }
12,239
BabyAXIE
@openzeppelin/contracts/token/ERC20/IERC20.sol
0x39db8e213ebf84d713383bf51c621d210bc1fa17
Solidity
BabyAXIE
contract BabyAXIE is ERC20, Owned { uint256 public minSupply; address public beneficiary; bool public feesEnabled; mapping(address => bool) public isExcludedFromFee; event MinSupplyUpdated(uint256 oldAmount, uint256 newAmount); event BeneficiaryUpdated(address oldBeneficiary, address newBeneficiary); event FeesEnabledUpdated(bool enabled); event ExcludedFromFeeUpdated(address account, bool excluded); constructor() ERC20("BabyAXIE", "BabyAXIE") { minSupply = 100000000 ether; uint256 totalSupply = 1000000000000000 ether; feesEnabled = false; _mint(_msgSender(), totalSupply); isExcludedFromFee[msg.sender] = true; isExcludedFromFee[0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = true; beneficiary = msg.sender; } /** * @dev if fees are enabled, subtract 2.25% fee and send it to beneficiary * @dev after a certain threshold, try to swap collected fees automatically * @dev if automatic swap fails (or beneficiary does not implement swapTokens function) transfer should still succeed */ function _transfer( address sender, address recipient, uint256 amount ) internal override { require( recipient != address(this), "Cannot send tokens to token contract" ); if ( !feesEnabled || isExcludedFromFee[sender] || isExcludedFromFee[recipient] ) { ERC20._transfer(sender, recipient, amount); return; } // burn tokens if min supply not reached yet uint256 burnedFee = calculateFee(amount, 25); if (totalSupply() - burnedFee >= minSupply) { _burn(sender, burnedFee); } else { burnedFee = 0; } uint256 transferFee = calculateFee(amount, 200); ERC20._transfer(sender, beneficiary, transferFee); ERC20._transfer(sender, recipient, amount - transferFee - burnedFee); } function calculateFee(uint256 _amount, uint256 _fee) public pure returns (uint256) { return (_amount * _fee) / 10000; } /** * @notice allows to burn tokens from own balance * @dev only allows burning tokens until minimum supply is reached * @param value amount of tokens to burn */ function burn(uint256 value) public { _burn(_msgSender(), value); require(totalSupply() >= minSupply, "total supply exceeds min supply"); } /** * @notice sets minimum supply of the token * @dev only callable by owner * @param _newMinSupply new minimum supply */ function setMinSupply(uint256 _newMinSupply) public onlyOwner { emit MinSupplyUpdated(minSupply, _newMinSupply); minSupply = _newMinSupply; } /** * @notice sets recipient of transfer fee * @dev only callable by owner * @param _newBeneficiary new beneficiary */ function setBeneficiary(address _newBeneficiary) public onlyOwner { setExcludeFromFee(_newBeneficiary, true); emit BeneficiaryUpdated(beneficiary, _newBeneficiary); beneficiary = _newBeneficiary; } /** * @notice sets whether account collects fees on token transfer * @dev only callable by owner * @param _enabled bool whether fees are enabled */ function setFeesEnabled(bool _enabled) public onlyOwner { emit FeesEnabledUpdated(_enabled); feesEnabled = _enabled; } /** * @notice adds or removes an account that is exempt from fee collection * @dev only callable by owner * @param _account account to modify * @param _excluded new value */ function setExcludeFromFee(address _account, bool _excluded) public onlyOwner { isExcludedFromFee[_account] = _excluded; emit ExcludedFromFeeUpdated(_account, _excluded); } }
setFeesEnabled
function setFeesEnabled(bool _enabled) public onlyOwner { emit FeesEnabledUpdated(_enabled); feesEnabled = _enabled; }
/** * @notice sets whether account collects fees on token transfer * @dev only callable by owner * @param _enabled bool whether fees are enabled */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
MIT
ipfs://a9bfcd486b1700b948ab2234b7cda1203427abeeef98f725108722ab9937fa21
{ "func_code_index": [ 3510, 3656 ] }
12,240
BabyAXIE
@openzeppelin/contracts/token/ERC20/IERC20.sol
0x39db8e213ebf84d713383bf51c621d210bc1fa17
Solidity
BabyAXIE
contract BabyAXIE is ERC20, Owned { uint256 public minSupply; address public beneficiary; bool public feesEnabled; mapping(address => bool) public isExcludedFromFee; event MinSupplyUpdated(uint256 oldAmount, uint256 newAmount); event BeneficiaryUpdated(address oldBeneficiary, address newBeneficiary); event FeesEnabledUpdated(bool enabled); event ExcludedFromFeeUpdated(address account, bool excluded); constructor() ERC20("BabyAXIE", "BabyAXIE") { minSupply = 100000000 ether; uint256 totalSupply = 1000000000000000 ether; feesEnabled = false; _mint(_msgSender(), totalSupply); isExcludedFromFee[msg.sender] = true; isExcludedFromFee[0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = true; beneficiary = msg.sender; } /** * @dev if fees are enabled, subtract 2.25% fee and send it to beneficiary * @dev after a certain threshold, try to swap collected fees automatically * @dev if automatic swap fails (or beneficiary does not implement swapTokens function) transfer should still succeed */ function _transfer( address sender, address recipient, uint256 amount ) internal override { require( recipient != address(this), "Cannot send tokens to token contract" ); if ( !feesEnabled || isExcludedFromFee[sender] || isExcludedFromFee[recipient] ) { ERC20._transfer(sender, recipient, amount); return; } // burn tokens if min supply not reached yet uint256 burnedFee = calculateFee(amount, 25); if (totalSupply() - burnedFee >= minSupply) { _burn(sender, burnedFee); } else { burnedFee = 0; } uint256 transferFee = calculateFee(amount, 200); ERC20._transfer(sender, beneficiary, transferFee); ERC20._transfer(sender, recipient, amount - transferFee - burnedFee); } function calculateFee(uint256 _amount, uint256 _fee) public pure returns (uint256) { return (_amount * _fee) / 10000; } /** * @notice allows to burn tokens from own balance * @dev only allows burning tokens until minimum supply is reached * @param value amount of tokens to burn */ function burn(uint256 value) public { _burn(_msgSender(), value); require(totalSupply() >= minSupply, "total supply exceeds min supply"); } /** * @notice sets minimum supply of the token * @dev only callable by owner * @param _newMinSupply new minimum supply */ function setMinSupply(uint256 _newMinSupply) public onlyOwner { emit MinSupplyUpdated(minSupply, _newMinSupply); minSupply = _newMinSupply; } /** * @notice sets recipient of transfer fee * @dev only callable by owner * @param _newBeneficiary new beneficiary */ function setBeneficiary(address _newBeneficiary) public onlyOwner { setExcludeFromFee(_newBeneficiary, true); emit BeneficiaryUpdated(beneficiary, _newBeneficiary); beneficiary = _newBeneficiary; } /** * @notice sets whether account collects fees on token transfer * @dev only callable by owner * @param _enabled bool whether fees are enabled */ function setFeesEnabled(bool _enabled) public onlyOwner { emit FeesEnabledUpdated(_enabled); feesEnabled = _enabled; } /** * @notice adds or removes an account that is exempt from fee collection * @dev only callable by owner * @param _account account to modify * @param _excluded new value */ function setExcludeFromFee(address _account, bool _excluded) public onlyOwner { isExcludedFromFee[_account] = _excluded; emit ExcludedFromFeeUpdated(_account, _excluded); } }
setExcludeFromFee
function setExcludeFromFee(address _account, bool _excluded) public onlyOwner { isExcludedFromFee[_account] = _excluded; emit ExcludedFromFeeUpdated(_account, _excluded); }
/** * @notice adds or removes an account that is exempt from fee collection * @dev only callable by owner * @param _account account to modify * @param _excluded new value */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
MIT
ipfs://a9bfcd486b1700b948ab2234b7cda1203427abeeef98f725108722ab9937fa21
{ "func_code_index": [ 3868, 4091 ] }
12,241
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
/** * @title SafeMath * @dev Math operations with safety checks that revert on error */
NatSpecMultiLine
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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; }
/** * @dev Multiplies two numbers, reverts on overflow. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 85, 468 ] }
12,242
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
/** * @title SafeMath * @dev Math operations with safety checks that revert on error */
NatSpecMultiLine
div
function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
/** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 576, 848 ] }
12,243
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
/** * @title SafeMath * @dev Math operations with safety checks that revert on error */
NatSpecMultiLine
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; }
/** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 959, 1092 ] }
12,244
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
/** * @title SafeMath * @dev Math operations with safety checks that revert on error */
NatSpecMultiLine
add
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; }
/** * @dev Adds two numbers, reverts on overflow. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 1153, 1286 ] }
12,245
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
/** * @title SafeMath * @dev Math operations with safety checks that revert on error */
NatSpecMultiLine
mod
function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; }
/** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 1416, 1529 ] }
12,246
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SafeDecimalMath
library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } }
/** * @title Safely manipulate unsigned fixed-point decimals at a given precision level. * @dev Functions accepting uints in this contract and derived contracts * are taken to be such fixed point decimals of a specified precision (either standard * or high). */
NatSpecMultiLine
unit
function unit() external pure returns (uint) { return UNIT; }
/** * @return Provides an interface to UNIT. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 627, 732 ] }
12,247
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SafeDecimalMath
library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } }
/** * @title Safely manipulate unsigned fixed-point decimals at a given precision level. * @dev Functions accepting uints in this contract and derived contracts * are taken to be such fixed point decimals of a specified precision (either standard * or high). */
NatSpecMultiLine
preciseUnit
function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; }
/** * @return Provides an interface to PRECISE_UNIT. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 805, 926 ] }
12,248
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SafeDecimalMath
library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } }
/** * @title Safely manipulate unsigned fixed-point decimals at a given precision level. * @dev Functions accepting uints in this contract and derived contracts * are taken to be such fixed point decimals of a specified precision (either standard * or high). */
NatSpecMultiLine
multiplyDecimal
function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; }
/** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 1340, 1564 ] }
12,249
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SafeDecimalMath
library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } }
/** * @title Safely manipulate unsigned fixed-point decimals at a given precision level. * @dev Functions accepting uints in this contract and derived contracts * are taken to be such fixed point decimals of a specified precision (either standard * or high). */
NatSpecMultiLine
_multiplyDecimalRound
function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; }
/** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 2165, 2575 ] }
12,250
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SafeDecimalMath
library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } }
/** * @title Safely manipulate unsigned fixed-point decimals at a given precision level. * @dev Functions accepting uints in this contract and derived contracts * are taken to be such fixed point decimals of a specified precision (either standard * or high). */
NatSpecMultiLine
multiplyDecimalRoundPrecise
function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); }
/** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 3146, 3325 ] }
12,251
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SafeDecimalMath
library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } }
/** * @title Safely manipulate unsigned fixed-point decimals at a given precision level. * @dev Functions accepting uints in this contract and derived contracts * are taken to be such fixed point decimals of a specified precision (either standard * or high). */
NatSpecMultiLine
multiplyDecimalRound
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); }
/** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 3898, 4062 ] }
12,252
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SafeDecimalMath
library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } }
/** * @title Safely manipulate unsigned fixed-point decimals at a given precision level. * @dev Functions accepting uints in this contract and derived contracts * are taken to be such fixed point decimals of a specified precision (either standard * or high). */
NatSpecMultiLine
divideDecimal
function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); }
/** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 4491, 4706 ] }
12,253
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SafeDecimalMath
library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } }
/** * @title Safely manipulate unsigned fixed-point decimals at a given precision level. * @dev Functions accepting uints in this contract and derived contracts * are taken to be such fixed point decimals of a specified precision (either standard * or high). */
NatSpecMultiLine
_divideDecimalRound
function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; }
/** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 5119, 5437 ] }
12,254
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SafeDecimalMath
library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } }
/** * @title Safely manipulate unsigned fixed-point decimals at a given precision level. * @dev Functions accepting uints in this contract and derived contracts * are taken to be such fixed point decimals of a specified precision (either standard * or high). */
NatSpecMultiLine
divideDecimalRound
function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); }
/** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 5818, 5978 ] }
12,255
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SafeDecimalMath
library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } }
/** * @title Safely manipulate unsigned fixed-point decimals at a given precision level. * @dev Functions accepting uints in this contract and derived contracts * are taken to be such fixed point decimals of a specified precision (either standard * or high). */
NatSpecMultiLine
divideDecimalRoundPrecise
function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); }
/** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 6347, 6522 ] }
12,256
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SafeDecimalMath
library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } }
/** * @title Safely manipulate unsigned fixed-point decimals at a given precision level. * @dev Functions accepting uints in this contract and derived contracts * are taken to be such fixed point decimals of a specified precision (either standard * or high). */
NatSpecMultiLine
decimalToPreciseDecimal
function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); }
/** * @dev Convert a standard decimal representation to a high precision one. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 6619, 6792 ] }
12,257
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SafeDecimalMath
library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } }
/** * @title Safely manipulate unsigned fixed-point decimals at a given precision level. * @dev Functions accepting uints in this contract and derived contracts * are taken to be such fixed point decimals of a specified precision (either standard * or high). */
NatSpecMultiLine
preciseDecimalToDecimal
function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; }
/** * @dev Convert a high precision decimal to a standard decimal representation. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 6893, 7215 ] }
12,258
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Owned
contract Owned { address public owner; address public nominatedOwner; /** * @dev Owned Constructor */ constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } /** * @notice Nominate a new owner of this contract. * @dev Only the current owner may nominate a new owner. */ function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } /** * @notice Accept the nomination to be owner. */ function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); }
/** * @title A contract with an owner. * @notice Contract ownership can be transferred by first nominating the new owner, * who must then accept the ownership, which prevents accidental incorrect ownership transfers. */
NatSpecMultiLine
nominateNewOwner
function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); }
/** * @notice Nominate a new owner of this contract. * @dev Only the current owner may nominate a new owner. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 455, 617 ] }
12,259
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Owned
contract Owned { address public owner; address public nominatedOwner; /** * @dev Owned Constructor */ constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } /** * @notice Nominate a new owner of this contract. * @dev Only the current owner may nominate a new owner. */ function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } /** * @notice Accept the nomination to be owner. */ function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); }
/** * @title A contract with an owner. * @notice Contract ownership can be transferred by first nominating the new owner, * who must then accept the ownership, which prevents accidental incorrect ownership transfers. */
NatSpecMultiLine
acceptOwnership
function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); }
/** * @notice Accept the nomination to be owner. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 685, 967 ] }
12,260
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SelfDestructible
contract SelfDestructible is Owned { uint public initiationTime; bool public selfDestructInitiated; address public selfDestructBeneficiary; uint public constant SELFDESTRUCT_DELAY = 4 weeks; /** * @dev Constructor * @param _owner The account which controls this contract. */ constructor(address _owner) Owned(_owner) public { require(_owner != address(0), "Owner must not be zero"); selfDestructBeneficiary = _owner; emit SelfDestructBeneficiaryUpdated(_owner); } /** * @notice Set the beneficiary address of this contract. * @dev Only the contract owner may call this. The provided beneficiary must be non-null. * @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction. */ function setSelfDestructBeneficiary(address _beneficiary) external onlyOwner { require(_beneficiary != address(0), "Beneficiary must not be zero"); selfDestructBeneficiary = _beneficiary; emit SelfDestructBeneficiaryUpdated(_beneficiary); } /** * @notice Begin the self-destruction counter of this contract. * Once the delay has elapsed, the contract may be self-destructed. * @dev Only the contract owner may call this. */ function initiateSelfDestruct() external onlyOwner { initiationTime = now; selfDestructInitiated = true; emit SelfDestructInitiated(SELFDESTRUCT_DELAY); } /** * @notice Terminate and reset the self-destruction timer. * @dev Only the contract owner may call this. */ function terminateSelfDestruct() external onlyOwner { initiationTime = 0; selfDestructInitiated = false; emit SelfDestructTerminated(); } /** * @notice If the self-destruction delay has elapsed, destroy this contract and * remit any ether it owns to the beneficiary address. * @dev Only the contract owner may call this. */ function selfDestruct() external onlyOwner { require(selfDestructInitiated, "Self Destruct not yet initiated"); require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay not met"); address beneficiary = selfDestructBeneficiary; emit SelfDestructed(beneficiary); selfdestruct(beneficiary); } event SelfDestructTerminated(); event SelfDestructed(address beneficiary); event SelfDestructInitiated(uint selfDestructDelay); event SelfDestructBeneficiaryUpdated(address newBeneficiary); }
/** * @title A contract that can be destroyed by its owner after a delay elapses. */
NatSpecMultiLine
setSelfDestructBeneficiary
function setSelfDestructBeneficiary(address _beneficiary) external onlyOwner { require(_beneficiary != address(0), "Beneficiary must not be zero"); selfDestructBeneficiary = _beneficiary; emit SelfDestructBeneficiaryUpdated(_beneficiary); }
/** * @notice Set the beneficiary address of this contract. * @dev Only the contract owner may call this. The provided beneficiary must be non-null. * @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 836, 1128 ] }
12,261
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SelfDestructible
contract SelfDestructible is Owned { uint public initiationTime; bool public selfDestructInitiated; address public selfDestructBeneficiary; uint public constant SELFDESTRUCT_DELAY = 4 weeks; /** * @dev Constructor * @param _owner The account which controls this contract. */ constructor(address _owner) Owned(_owner) public { require(_owner != address(0), "Owner must not be zero"); selfDestructBeneficiary = _owner; emit SelfDestructBeneficiaryUpdated(_owner); } /** * @notice Set the beneficiary address of this contract. * @dev Only the contract owner may call this. The provided beneficiary must be non-null. * @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction. */ function setSelfDestructBeneficiary(address _beneficiary) external onlyOwner { require(_beneficiary != address(0), "Beneficiary must not be zero"); selfDestructBeneficiary = _beneficiary; emit SelfDestructBeneficiaryUpdated(_beneficiary); } /** * @notice Begin the self-destruction counter of this contract. * Once the delay has elapsed, the contract may be self-destructed. * @dev Only the contract owner may call this. */ function initiateSelfDestruct() external onlyOwner { initiationTime = now; selfDestructInitiated = true; emit SelfDestructInitiated(SELFDESTRUCT_DELAY); } /** * @notice Terminate and reset the self-destruction timer. * @dev Only the contract owner may call this. */ function terminateSelfDestruct() external onlyOwner { initiationTime = 0; selfDestructInitiated = false; emit SelfDestructTerminated(); } /** * @notice If the self-destruction delay has elapsed, destroy this contract and * remit any ether it owns to the beneficiary address. * @dev Only the contract owner may call this. */ function selfDestruct() external onlyOwner { require(selfDestructInitiated, "Self Destruct not yet initiated"); require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay not met"); address beneficiary = selfDestructBeneficiary; emit SelfDestructed(beneficiary); selfdestruct(beneficiary); } event SelfDestructTerminated(); event SelfDestructed(address beneficiary); event SelfDestructInitiated(uint selfDestructDelay); event SelfDestructBeneficiaryUpdated(address newBeneficiary); }
/** * @title A contract that can be destroyed by its owner after a delay elapses. */
NatSpecMultiLine
initiateSelfDestruct
function initiateSelfDestruct() external onlyOwner { initiationTime = now; selfDestructInitiated = true; emit SelfDestructInitiated(SELFDESTRUCT_DELAY); }
/** * @notice Begin the self-destruction counter of this contract. * Once the delay has elapsed, the contract may be self-destructed. * @dev Only the contract owner may call this. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 1337, 1543 ] }
12,262
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SelfDestructible
contract SelfDestructible is Owned { uint public initiationTime; bool public selfDestructInitiated; address public selfDestructBeneficiary; uint public constant SELFDESTRUCT_DELAY = 4 weeks; /** * @dev Constructor * @param _owner The account which controls this contract. */ constructor(address _owner) Owned(_owner) public { require(_owner != address(0), "Owner must not be zero"); selfDestructBeneficiary = _owner; emit SelfDestructBeneficiaryUpdated(_owner); } /** * @notice Set the beneficiary address of this contract. * @dev Only the contract owner may call this. The provided beneficiary must be non-null. * @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction. */ function setSelfDestructBeneficiary(address _beneficiary) external onlyOwner { require(_beneficiary != address(0), "Beneficiary must not be zero"); selfDestructBeneficiary = _beneficiary; emit SelfDestructBeneficiaryUpdated(_beneficiary); } /** * @notice Begin the self-destruction counter of this contract. * Once the delay has elapsed, the contract may be self-destructed. * @dev Only the contract owner may call this. */ function initiateSelfDestruct() external onlyOwner { initiationTime = now; selfDestructInitiated = true; emit SelfDestructInitiated(SELFDESTRUCT_DELAY); } /** * @notice Terminate and reset the self-destruction timer. * @dev Only the contract owner may call this. */ function terminateSelfDestruct() external onlyOwner { initiationTime = 0; selfDestructInitiated = false; emit SelfDestructTerminated(); } /** * @notice If the self-destruction delay has elapsed, destroy this contract and * remit any ether it owns to the beneficiary address. * @dev Only the contract owner may call this. */ function selfDestruct() external onlyOwner { require(selfDestructInitiated, "Self Destruct not yet initiated"); require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay not met"); address beneficiary = selfDestructBeneficiary; emit SelfDestructed(beneficiary); selfdestruct(beneficiary); } event SelfDestructTerminated(); event SelfDestructed(address beneficiary); event SelfDestructInitiated(uint selfDestructDelay); event SelfDestructBeneficiaryUpdated(address newBeneficiary); }
/** * @title A contract that can be destroyed by its owner after a delay elapses. */
NatSpecMultiLine
terminateSelfDestruct
function terminateSelfDestruct() external onlyOwner { initiationTime = 0; selfDestructInitiated = false; emit SelfDestructTerminated(); }
/** * @notice Terminate and reset the self-destruction timer. * @dev Only the contract owner may call this. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 1675, 1864 ] }
12,263
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SelfDestructible
contract SelfDestructible is Owned { uint public initiationTime; bool public selfDestructInitiated; address public selfDestructBeneficiary; uint public constant SELFDESTRUCT_DELAY = 4 weeks; /** * @dev Constructor * @param _owner The account which controls this contract. */ constructor(address _owner) Owned(_owner) public { require(_owner != address(0), "Owner must not be zero"); selfDestructBeneficiary = _owner; emit SelfDestructBeneficiaryUpdated(_owner); } /** * @notice Set the beneficiary address of this contract. * @dev Only the contract owner may call this. The provided beneficiary must be non-null. * @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction. */ function setSelfDestructBeneficiary(address _beneficiary) external onlyOwner { require(_beneficiary != address(0), "Beneficiary must not be zero"); selfDestructBeneficiary = _beneficiary; emit SelfDestructBeneficiaryUpdated(_beneficiary); } /** * @notice Begin the self-destruction counter of this contract. * Once the delay has elapsed, the contract may be self-destructed. * @dev Only the contract owner may call this. */ function initiateSelfDestruct() external onlyOwner { initiationTime = now; selfDestructInitiated = true; emit SelfDestructInitiated(SELFDESTRUCT_DELAY); } /** * @notice Terminate and reset the self-destruction timer. * @dev Only the contract owner may call this. */ function terminateSelfDestruct() external onlyOwner { initiationTime = 0; selfDestructInitiated = false; emit SelfDestructTerminated(); } /** * @notice If the self-destruction delay has elapsed, destroy this contract and * remit any ether it owns to the beneficiary address. * @dev Only the contract owner may call this. */ function selfDestruct() external onlyOwner { require(selfDestructInitiated, "Self Destruct not yet initiated"); require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay not met"); address beneficiary = selfDestructBeneficiary; emit SelfDestructed(beneficiary); selfdestruct(beneficiary); } event SelfDestructTerminated(); event SelfDestructed(address beneficiary); event SelfDestructInitiated(uint selfDestructDelay); event SelfDestructBeneficiaryUpdated(address newBeneficiary); }
/** * @title A contract that can be destroyed by its owner after a delay elapses. */
NatSpecMultiLine
selfDestruct
function selfDestruct() external onlyOwner { require(selfDestructInitiated, "Self Destruct not yet initiated"); require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay not met"); address beneficiary = selfDestructBeneficiary; emit SelfDestructed(beneficiary); selfdestruct(beneficiary); }
/** * @notice If the self-destruction delay has elapsed, destroy this contract and * remit any ether it owns to the beneficiary address. * @dev Only the contract owner may call this. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 2076, 2448 ] }
12,264
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
State
contract State is Owned { // the address of the contract that can modify variables // this can only be changed by the owner of this contract address public associatedContract; constructor(address _owner, address _associatedContract) Owned(_owner) public { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } /* ========== SETTERS ========== */ // Change the associated contract to a new address function setAssociatedContract(address _associatedContract) external onlyOwner { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } /* ========== MODIFIERS ========== */ modifier onlyAssociatedContract { require(msg.sender == associatedContract, "Only the associated contract can perform this action"); _; } /* ========== EVENTS ========== */ event AssociatedContractUpdated(address associatedContract); }
/* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: State.sol version: 1.1 author: Dominic Romanowski Anton Jurisevic date: 2018-05-15 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract is used side by side with external state token contracts, such as Synthetix and Synth. It provides an easy way to upgrade contract logic while maintaining all user balances and allowances. This is designed to make the changeover as easy as possible, since mappings are not so cheap or straightforward to migrate. The first deployed contract would create this state contract, using it as its store of balances. When a new contract is deployed, it links to the existing state contract, whose owner would then change its associated contract to the new one. ----------------------------------------------------------------- */
Comment
setAssociatedContract
function setAssociatedContract(address _associatedContract) external onlyOwner { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); }
// Change the associated contract to a new address
LineComment
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 508, 729 ] }
12,265
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
TokenState
contract TokenState is State { /* ERC20 fields. */ mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; /** * @dev Constructor * @param _owner The address which controls this contract. * @param _associatedContract The ERC20 contract whose state this composes. */ constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) public {} /* ========== SETTERS ========== */ /** * @notice Set ERC20 allowance. * @dev Only the associated contract may call this. * @param tokenOwner The authorising party. * @param spender The authorised party. * @param value The total value the authorised party may spend on the * authorising party's behalf. */ function setAllowance(address tokenOwner, address spender, uint value) external onlyAssociatedContract { allowance[tokenOwner][spender] = value; } /** * @notice Set the balance in a given account * @dev Only the associated contract may call this. * @param account The account whose value to set. * @param value The new balance of the given account. */ function setBalanceOf(address account, uint value) external onlyAssociatedContract { balanceOf[account] = value; } }
/** * @title ERC20 Token State * @notice Stores balance information of an ERC20 token contract. */
NatSpecMultiLine
setAllowance
function setAllowance(address tokenOwner, address spender, uint value) external onlyAssociatedContract { allowance[tokenOwner][spender] = value; }
/** * @notice Set ERC20 allowance. * @dev Only the associated contract may call this. * @param tokenOwner The authorising party. * @param spender The authorised party. * @param value The total value the authorised party may spend on the * authorising party's behalf. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 831, 1013 ] }
12,266
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
TokenState
contract TokenState is State { /* ERC20 fields. */ mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; /** * @dev Constructor * @param _owner The address which controls this contract. * @param _associatedContract The ERC20 contract whose state this composes. */ constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) public {} /* ========== SETTERS ========== */ /** * @notice Set ERC20 allowance. * @dev Only the associated contract may call this. * @param tokenOwner The authorising party. * @param spender The authorised party. * @param value The total value the authorised party may spend on the * authorising party's behalf. */ function setAllowance(address tokenOwner, address spender, uint value) external onlyAssociatedContract { allowance[tokenOwner][spender] = value; } /** * @notice Set the balance in a given account * @dev Only the associated contract may call this. * @param account The account whose value to set. * @param value The new balance of the given account. */ function setBalanceOf(address account, uint value) external onlyAssociatedContract { balanceOf[account] = value; } }
/** * @title ERC20 Token State * @notice Stores balance information of an ERC20 token contract. */
NatSpecMultiLine
setBalanceOf
function setBalanceOf(address account, uint value) external onlyAssociatedContract { balanceOf[account] = value; }
/** * @notice Set the balance in a given account * @dev Only the associated contract may call this. * @param account The account whose value to set. * @param value The new balance of the given account. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 1249, 1399 ] }
12,267
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExternStateToken
contract ExternStateToken is SelfDestructible, Proxyable { using SafeMath for uint; using SafeDecimalMath for uint; /* ========== STATE VARIABLES ========== */ /* Stores balances and allowances. */ TokenState public tokenState; /* Other ERC20 fields. */ string public name; string public symbol; uint public totalSupply; uint8 public decimals; /** * @dev Constructor. * @param _proxy The proxy associated with this contract. * @param _name Token's ERC20 name. * @param _symbol Token's ERC20 symbol. * @param _totalSupply The total supply of the token. * @param _tokenState The TokenState contract address. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply, uint8 _decimals, address _owner) SelfDestructible(_owner) Proxyable(_proxy, _owner) public { tokenState = _tokenState; name = _name; symbol = _symbol; totalSupply = _totalSupply; decimals = _decimals; } /* ========== VIEWS ========== */ /** * @notice Returns the ERC20 allowance of one party to spend on behalf of another. * @param owner The party authorising spending of their funds. * @param spender The party spending tokenOwner's funds. */ function allowance(address owner, address spender) public view returns (uint) { return tokenState.allowance(owner, spender); } /** * @notice Returns the ERC20 token balance of a given account. */ function balanceOf(address account) public view returns (uint) { return tokenState.balanceOf(account); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Set the address of the TokenState contract. * @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000.. * as balances would be unreachable. */ function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner { tokenState = _tokenState; emitTokenStateUpdated(_tokenState); } function _internalTransfer(address from, address to, uint value) internal returns (bool) { /* Disallow transfers to irretrievable-addresses. */ require(to != address(0) && to != address(this) && to != address(proxy), "Cannot transfer to this address"); // Insufficient balance will be handled by the safe subtraction. tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value)); tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value)); // Emit a standard ERC20 transfer event emitTransfer(from, to, value); return true; } /** * @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing * the onlyProxy or optionalProxy modifiers. */ function _transfer_byProxy(address from, address to, uint value) internal returns (bool) { return _internalTransfer(from, to, value); } /** * @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions * possessing the optionalProxy or optionalProxy modifiers. */ function _transferFrom_byProxy(address sender, address from, address to, uint value) internal returns (bool) { /* Insufficient allowance will be handled by the safe subtraction. */ tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value)); return _internalTransfer(from, to, value); } /** * @notice Approves spender to transfer on the message sender's behalf. */ function approve(address spender, uint value) public optionalProxy returns (bool) { address sender = messageSender; tokenState.setAllowance(sender, spender, value); emitApproval(sender, spender, value); return true; } /* ========== EVENTS ========== */ event Transfer(address indexed from, address indexed to, uint value); bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)"); function emitTransfer(address from, address to, uint value) internal { proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0); } event Approval(address indexed owner, address indexed spender, uint value); bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)"); function emitApproval(address owner, address spender, uint value) internal { proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0); } event TokenStateUpdated(address newTokenState); bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)"); function emitTokenStateUpdated(address newTokenState) internal { proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0); } }
/** * @title ERC20 Token contract, with detached state and designed to operate behind a proxy. */
NatSpecMultiLine
allowance
function allowance(address owner, address spender) public view returns (uint) { return tokenState.allowance(owner, spender); }
/** * @notice Returns the ERC20 allowance of one party to spend on behalf of another. * @param owner The party authorising spending of their funds. * @param spender The party spending tokenOwner's funds. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 1426, 1596 ] }
12,268
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExternStateToken
contract ExternStateToken is SelfDestructible, Proxyable { using SafeMath for uint; using SafeDecimalMath for uint; /* ========== STATE VARIABLES ========== */ /* Stores balances and allowances. */ TokenState public tokenState; /* Other ERC20 fields. */ string public name; string public symbol; uint public totalSupply; uint8 public decimals; /** * @dev Constructor. * @param _proxy The proxy associated with this contract. * @param _name Token's ERC20 name. * @param _symbol Token's ERC20 symbol. * @param _totalSupply The total supply of the token. * @param _tokenState The TokenState contract address. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply, uint8 _decimals, address _owner) SelfDestructible(_owner) Proxyable(_proxy, _owner) public { tokenState = _tokenState; name = _name; symbol = _symbol; totalSupply = _totalSupply; decimals = _decimals; } /* ========== VIEWS ========== */ /** * @notice Returns the ERC20 allowance of one party to spend on behalf of another. * @param owner The party authorising spending of their funds. * @param spender The party spending tokenOwner's funds. */ function allowance(address owner, address spender) public view returns (uint) { return tokenState.allowance(owner, spender); } /** * @notice Returns the ERC20 token balance of a given account. */ function balanceOf(address account) public view returns (uint) { return tokenState.balanceOf(account); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Set the address of the TokenState contract. * @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000.. * as balances would be unreachable. */ function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner { tokenState = _tokenState; emitTokenStateUpdated(_tokenState); } function _internalTransfer(address from, address to, uint value) internal returns (bool) { /* Disallow transfers to irretrievable-addresses. */ require(to != address(0) && to != address(this) && to != address(proxy), "Cannot transfer to this address"); // Insufficient balance will be handled by the safe subtraction. tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value)); tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value)); // Emit a standard ERC20 transfer event emitTransfer(from, to, value); return true; } /** * @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing * the onlyProxy or optionalProxy modifiers. */ function _transfer_byProxy(address from, address to, uint value) internal returns (bool) { return _internalTransfer(from, to, value); } /** * @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions * possessing the optionalProxy or optionalProxy modifiers. */ function _transferFrom_byProxy(address sender, address from, address to, uint value) internal returns (bool) { /* Insufficient allowance will be handled by the safe subtraction. */ tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value)); return _internalTransfer(from, to, value); } /** * @notice Approves spender to transfer on the message sender's behalf. */ function approve(address spender, uint value) public optionalProxy returns (bool) { address sender = messageSender; tokenState.setAllowance(sender, spender, value); emitApproval(sender, spender, value); return true; } /* ========== EVENTS ========== */ event Transfer(address indexed from, address indexed to, uint value); bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)"); function emitTransfer(address from, address to, uint value) internal { proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0); } event Approval(address indexed owner, address indexed spender, uint value); bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)"); function emitApproval(address owner, address spender, uint value) internal { proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0); } event TokenStateUpdated(address newTokenState); bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)"); function emitTokenStateUpdated(address newTokenState) internal { proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0); } }
/** * @title ERC20 Token contract, with detached state and designed to operate behind a proxy. */
NatSpecMultiLine
balanceOf
function balanceOf(address account) public view returns (uint) { return tokenState.balanceOf(account); }
/** * @notice Returns the ERC20 token balance of a given account. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 1681, 1829 ] }
12,269
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExternStateToken
contract ExternStateToken is SelfDestructible, Proxyable { using SafeMath for uint; using SafeDecimalMath for uint; /* ========== STATE VARIABLES ========== */ /* Stores balances and allowances. */ TokenState public tokenState; /* Other ERC20 fields. */ string public name; string public symbol; uint public totalSupply; uint8 public decimals; /** * @dev Constructor. * @param _proxy The proxy associated with this contract. * @param _name Token's ERC20 name. * @param _symbol Token's ERC20 symbol. * @param _totalSupply The total supply of the token. * @param _tokenState The TokenState contract address. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply, uint8 _decimals, address _owner) SelfDestructible(_owner) Proxyable(_proxy, _owner) public { tokenState = _tokenState; name = _name; symbol = _symbol; totalSupply = _totalSupply; decimals = _decimals; } /* ========== VIEWS ========== */ /** * @notice Returns the ERC20 allowance of one party to spend on behalf of another. * @param owner The party authorising spending of their funds. * @param spender The party spending tokenOwner's funds. */ function allowance(address owner, address spender) public view returns (uint) { return tokenState.allowance(owner, spender); } /** * @notice Returns the ERC20 token balance of a given account. */ function balanceOf(address account) public view returns (uint) { return tokenState.balanceOf(account); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Set the address of the TokenState contract. * @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000.. * as balances would be unreachable. */ function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner { tokenState = _tokenState; emitTokenStateUpdated(_tokenState); } function _internalTransfer(address from, address to, uint value) internal returns (bool) { /* Disallow transfers to irretrievable-addresses. */ require(to != address(0) && to != address(this) && to != address(proxy), "Cannot transfer to this address"); // Insufficient balance will be handled by the safe subtraction. tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value)); tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value)); // Emit a standard ERC20 transfer event emitTransfer(from, to, value); return true; } /** * @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing * the onlyProxy or optionalProxy modifiers. */ function _transfer_byProxy(address from, address to, uint value) internal returns (bool) { return _internalTransfer(from, to, value); } /** * @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions * possessing the optionalProxy or optionalProxy modifiers. */ function _transferFrom_byProxy(address sender, address from, address to, uint value) internal returns (bool) { /* Insufficient allowance will be handled by the safe subtraction. */ tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value)); return _internalTransfer(from, to, value); } /** * @notice Approves spender to transfer on the message sender's behalf. */ function approve(address spender, uint value) public optionalProxy returns (bool) { address sender = messageSender; tokenState.setAllowance(sender, spender, value); emitApproval(sender, spender, value); return true; } /* ========== EVENTS ========== */ event Transfer(address indexed from, address indexed to, uint value); bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)"); function emitTransfer(address from, address to, uint value) internal { proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0); } event Approval(address indexed owner, address indexed spender, uint value); bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)"); function emitApproval(address owner, address spender, uint value) internal { proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0); } event TokenStateUpdated(address newTokenState); bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)"); function emitTokenStateUpdated(address newTokenState) internal { proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0); } }
/** * @title ERC20 Token contract, with detached state and designed to operate behind a proxy. */
NatSpecMultiLine
setTokenState
function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner { tokenState = _tokenState; emitTokenStateUpdated(_tokenState); }
/** * @notice Set the address of the TokenState contract. * @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000.. * as balances would be unreachable. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 2101, 2290 ] }
12,270
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExternStateToken
contract ExternStateToken is SelfDestructible, Proxyable { using SafeMath for uint; using SafeDecimalMath for uint; /* ========== STATE VARIABLES ========== */ /* Stores balances and allowances. */ TokenState public tokenState; /* Other ERC20 fields. */ string public name; string public symbol; uint public totalSupply; uint8 public decimals; /** * @dev Constructor. * @param _proxy The proxy associated with this contract. * @param _name Token's ERC20 name. * @param _symbol Token's ERC20 symbol. * @param _totalSupply The total supply of the token. * @param _tokenState The TokenState contract address. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply, uint8 _decimals, address _owner) SelfDestructible(_owner) Proxyable(_proxy, _owner) public { tokenState = _tokenState; name = _name; symbol = _symbol; totalSupply = _totalSupply; decimals = _decimals; } /* ========== VIEWS ========== */ /** * @notice Returns the ERC20 allowance of one party to spend on behalf of another. * @param owner The party authorising spending of their funds. * @param spender The party spending tokenOwner's funds. */ function allowance(address owner, address spender) public view returns (uint) { return tokenState.allowance(owner, spender); } /** * @notice Returns the ERC20 token balance of a given account. */ function balanceOf(address account) public view returns (uint) { return tokenState.balanceOf(account); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Set the address of the TokenState contract. * @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000.. * as balances would be unreachable. */ function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner { tokenState = _tokenState; emitTokenStateUpdated(_tokenState); } function _internalTransfer(address from, address to, uint value) internal returns (bool) { /* Disallow transfers to irretrievable-addresses. */ require(to != address(0) && to != address(this) && to != address(proxy), "Cannot transfer to this address"); // Insufficient balance will be handled by the safe subtraction. tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value)); tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value)); // Emit a standard ERC20 transfer event emitTransfer(from, to, value); return true; } /** * @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing * the onlyProxy or optionalProxy modifiers. */ function _transfer_byProxy(address from, address to, uint value) internal returns (bool) { return _internalTransfer(from, to, value); } /** * @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions * possessing the optionalProxy or optionalProxy modifiers. */ function _transferFrom_byProxy(address sender, address from, address to, uint value) internal returns (bool) { /* Insufficient allowance will be handled by the safe subtraction. */ tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value)); return _internalTransfer(from, to, value); } /** * @notice Approves spender to transfer on the message sender's behalf. */ function approve(address spender, uint value) public optionalProxy returns (bool) { address sender = messageSender; tokenState.setAllowance(sender, spender, value); emitApproval(sender, spender, value); return true; } /* ========== EVENTS ========== */ event Transfer(address indexed from, address indexed to, uint value); bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)"); function emitTransfer(address from, address to, uint value) internal { proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0); } event Approval(address indexed owner, address indexed spender, uint value); bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)"); function emitApproval(address owner, address spender, uint value) internal { proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0); } event TokenStateUpdated(address newTokenState); bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)"); function emitTokenStateUpdated(address newTokenState) internal { proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0); } }
/** * @title ERC20 Token contract, with detached state and designed to operate behind a proxy. */
NatSpecMultiLine
_transfer_byProxy
function _transfer_byProxy(address from, address to, uint value) internal returns (bool) { return _internalTransfer(from, to, value); }
/** * @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing * the onlyProxy or optionalProxy modifiers. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 3101, 3272 ] }
12,271
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExternStateToken
contract ExternStateToken is SelfDestructible, Proxyable { using SafeMath for uint; using SafeDecimalMath for uint; /* ========== STATE VARIABLES ========== */ /* Stores balances and allowances. */ TokenState public tokenState; /* Other ERC20 fields. */ string public name; string public symbol; uint public totalSupply; uint8 public decimals; /** * @dev Constructor. * @param _proxy The proxy associated with this contract. * @param _name Token's ERC20 name. * @param _symbol Token's ERC20 symbol. * @param _totalSupply The total supply of the token. * @param _tokenState The TokenState contract address. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply, uint8 _decimals, address _owner) SelfDestructible(_owner) Proxyable(_proxy, _owner) public { tokenState = _tokenState; name = _name; symbol = _symbol; totalSupply = _totalSupply; decimals = _decimals; } /* ========== VIEWS ========== */ /** * @notice Returns the ERC20 allowance of one party to spend on behalf of another. * @param owner The party authorising spending of their funds. * @param spender The party spending tokenOwner's funds. */ function allowance(address owner, address spender) public view returns (uint) { return tokenState.allowance(owner, spender); } /** * @notice Returns the ERC20 token balance of a given account. */ function balanceOf(address account) public view returns (uint) { return tokenState.balanceOf(account); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Set the address of the TokenState contract. * @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000.. * as balances would be unreachable. */ function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner { tokenState = _tokenState; emitTokenStateUpdated(_tokenState); } function _internalTransfer(address from, address to, uint value) internal returns (bool) { /* Disallow transfers to irretrievable-addresses. */ require(to != address(0) && to != address(this) && to != address(proxy), "Cannot transfer to this address"); // Insufficient balance will be handled by the safe subtraction. tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value)); tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value)); // Emit a standard ERC20 transfer event emitTransfer(from, to, value); return true; } /** * @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing * the onlyProxy or optionalProxy modifiers. */ function _transfer_byProxy(address from, address to, uint value) internal returns (bool) { return _internalTransfer(from, to, value); } /** * @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions * possessing the optionalProxy or optionalProxy modifiers. */ function _transferFrom_byProxy(address sender, address from, address to, uint value) internal returns (bool) { /* Insufficient allowance will be handled by the safe subtraction. */ tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value)); return _internalTransfer(from, to, value); } /** * @notice Approves spender to transfer on the message sender's behalf. */ function approve(address spender, uint value) public optionalProxy returns (bool) { address sender = messageSender; tokenState.setAllowance(sender, spender, value); emitApproval(sender, spender, value); return true; } /* ========== EVENTS ========== */ event Transfer(address indexed from, address indexed to, uint value); bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)"); function emitTransfer(address from, address to, uint value) internal { proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0); } event Approval(address indexed owner, address indexed spender, uint value); bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)"); function emitApproval(address owner, address spender, uint value) internal { proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0); } event TokenStateUpdated(address newTokenState); bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)"); function emitTokenStateUpdated(address newTokenState) internal { proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0); } }
/** * @title ERC20 Token contract, with detached state and designed to operate behind a proxy. */
NatSpecMultiLine
_transferFrom_byProxy
function _transferFrom_byProxy(address sender, address from, address to, uint value) internal returns (bool) { /* Insufficient allowance will be handled by the safe subtraction. */ tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value)); return _internalTransfer(from, to, value); }
/** * @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions * possessing the optionalProxy or optionalProxy modifiers. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 3451, 3814 ] }
12,272
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExternStateToken
contract ExternStateToken is SelfDestructible, Proxyable { using SafeMath for uint; using SafeDecimalMath for uint; /* ========== STATE VARIABLES ========== */ /* Stores balances and allowances. */ TokenState public tokenState; /* Other ERC20 fields. */ string public name; string public symbol; uint public totalSupply; uint8 public decimals; /** * @dev Constructor. * @param _proxy The proxy associated with this contract. * @param _name Token's ERC20 name. * @param _symbol Token's ERC20 symbol. * @param _totalSupply The total supply of the token. * @param _tokenState The TokenState contract address. * @param _owner The owner of this contract. */ constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply, uint8 _decimals, address _owner) SelfDestructible(_owner) Proxyable(_proxy, _owner) public { tokenState = _tokenState; name = _name; symbol = _symbol; totalSupply = _totalSupply; decimals = _decimals; } /* ========== VIEWS ========== */ /** * @notice Returns the ERC20 allowance of one party to spend on behalf of another. * @param owner The party authorising spending of their funds. * @param spender The party spending tokenOwner's funds. */ function allowance(address owner, address spender) public view returns (uint) { return tokenState.allowance(owner, spender); } /** * @notice Returns the ERC20 token balance of a given account. */ function balanceOf(address account) public view returns (uint) { return tokenState.balanceOf(account); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Set the address of the TokenState contract. * @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000.. * as balances would be unreachable. */ function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner { tokenState = _tokenState; emitTokenStateUpdated(_tokenState); } function _internalTransfer(address from, address to, uint value) internal returns (bool) { /* Disallow transfers to irretrievable-addresses. */ require(to != address(0) && to != address(this) && to != address(proxy), "Cannot transfer to this address"); // Insufficient balance will be handled by the safe subtraction. tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value)); tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value)); // Emit a standard ERC20 transfer event emitTransfer(from, to, value); return true; } /** * @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing * the onlyProxy or optionalProxy modifiers. */ function _transfer_byProxy(address from, address to, uint value) internal returns (bool) { return _internalTransfer(from, to, value); } /** * @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions * possessing the optionalProxy or optionalProxy modifiers. */ function _transferFrom_byProxy(address sender, address from, address to, uint value) internal returns (bool) { /* Insufficient allowance will be handled by the safe subtraction. */ tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value)); return _internalTransfer(from, to, value); } /** * @notice Approves spender to transfer on the message sender's behalf. */ function approve(address spender, uint value) public optionalProxy returns (bool) { address sender = messageSender; tokenState.setAllowance(sender, spender, value); emitApproval(sender, spender, value); return true; } /* ========== EVENTS ========== */ event Transfer(address indexed from, address indexed to, uint value); bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)"); function emitTransfer(address from, address to, uint value) internal { proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0); } event Approval(address indexed owner, address indexed spender, uint value); bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)"); function emitApproval(address owner, address spender, uint value) internal { proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0); } event TokenStateUpdated(address newTokenState); bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)"); function emitTokenStateUpdated(address newTokenState) internal { proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0); } }
/** * @title ERC20 Token contract, with detached state and designed to operate behind a proxy. */
NatSpecMultiLine
approve
function approve(address spender, uint value) public optionalProxy returns (bool) { address sender = messageSender; tokenState.setAllowance(sender, spender, value); emitApproval(sender, spender, value); return true; }
/** * @notice Approves spender to transfer on the message sender's behalf. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 3908, 4194 ] }
12,273
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Math
library Math { using SafeMath for uint; using SafeDecimalMath for uint; /** * @dev Uses "exponentiation by squaring" algorithm where cost is 0(logN) * vs 0(N) for naive repeated multiplication. * Calculates x^n with x as fixed-point and n as regular unsigned int. * Calculates to 18 digits of precision with SafeDecimalMath.unit() */ function powDecimal(uint x, uint n) internal pure returns (uint) { // https://mpark.github.io/programming/2014/08/18/exponentiation-by-squaring/ uint result = SafeDecimalMath.unit(); while (n > 0) { if (n % 2 != 0) { result = result.multiplyDecimal(x); } x = x.multiplyDecimal(x); n /= 2; } return result; } }
powDecimal
function powDecimal(uint x, uint n) internal pure returns (uint) { // https://mpark.github.io/programming/2014/08/18/exponentiation-by-squaring/ uint result = SafeDecimalMath.unit(); while (n > 0) { if (n % 2 != 0) { result = result.multiplyDecimal(x); } x = x.multiplyDecimal(x); n /= 2; } return result; }
/** * @dev Uses "exponentiation by squaring" algorithm where cost is 0(logN) * vs 0(N) for naive repeated multiplication. * Calculates x^n with x as fixed-point and n as regular unsigned int. * Calculates to 18 digits of precision with SafeDecimalMath.unit() */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 369, 817 ] }
12,274
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synth
contract Synth is ExternStateToken { /* ========== STATE VARIABLES ========== */ // Address of the FeePoolProxy address public feePoolProxy; // Address of the SynthetixProxy address public synthetixProxy; // Currency key which identifies this Synth to the Synthetix system bytes32 public currencyKey; uint8 constant DECIMALS = 18; /* ========== CONSTRUCTOR ========== */ constructor(address _proxy, TokenState _tokenState, address _synthetixProxy, address _feePoolProxy, string _tokenName, string _tokenSymbol, address _owner, bytes32 _currencyKey, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, _totalSupply, DECIMALS, _owner) public { require(_proxy != address(0), "_proxy cannot be 0"); require(_synthetixProxy != address(0), "_synthetixProxy cannot be 0"); require(_feePoolProxy != address(0), "_feePoolProxy cannot be 0"); require(_owner != 0, "_owner cannot be 0"); require(ISynthetix(_synthetixProxy).synths(_currencyKey) == Synth(0), "Currency key is already in use"); feePoolProxy = _feePoolProxy; synthetixProxy = _synthetixProxy; currencyKey = _currencyKey; } /* ========== SETTERS ========== */ /** * @notice Set the SynthetixProxy should it ever change. * The Synth requires Synthetix address as it has the authority * to mint and burn synths * */ function setSynthetixProxy(ISynthetix _synthetixProxy) external optionalProxy_onlyOwner { synthetixProxy = _synthetixProxy; emitSynthetixUpdated(_synthetixProxy); } /** * @notice Set the FeePoolProxy should it ever change. * The Synth requires FeePool address as it has the authority * to mint and burn for FeePool.claimFees() * */ function setFeePoolProxy(address _feePoolProxy) external optionalProxy_onlyOwner { feePoolProxy = _feePoolProxy; emitFeePoolUpdated(_feePoolProxy); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice ERC20 transfer function * forward call on to _internalTransfer */ function transfer(address to, uint value) public optionalProxy returns (bool) { return super._internalTransfer(messageSender, to, value); } /** * @notice ERC20 transferFrom function */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Skip allowance update in case of infinite allowance if (tokenState.allowance(from, messageSender) != uint(-1)) { // Reduce the allowance by the amount we're transferring. // The safeSub call will handle an insufficient allowance. tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); } return super._internalTransfer(from, to, value); } // Allow synthetix to issue a certain number of synths from an account. function issue(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount)); totalSupply = totalSupply.add(amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); } // Allow synthetix or another synth contract to burn a certain number of synths from an account. function burn(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount)); totalSupply = totalSupply.sub(amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); } // Allow owner to set the total supply on import. function setTotalSupply(uint amount) external optionalProxy_onlyOwner { totalSupply = amount; } /* ========== MODIFIERS ========== */ modifier onlySynthetixOrFeePool() { bool isSynthetix = msg.sender == address(Proxy(synthetixProxy).target()); bool isFeePool = msg.sender == address(Proxy(feePoolProxy).target()); require(isSynthetix || isFeePool, "Only Synthetix, FeePool allowed"); _; } /* ========== EVENTS ========== */ event SynthetixUpdated(address newSynthetix); bytes32 constant SYNTHETIXUPDATED_SIG = keccak256("SynthetixUpdated(address)"); function emitSynthetixUpdated(address newSynthetix) internal { proxy._emit(abi.encode(newSynthetix), 1, SYNTHETIXUPDATED_SIG, 0, 0, 0); } event FeePoolUpdated(address newFeePool); bytes32 constant FEEPOOLUPDATED_SIG = keccak256("FeePoolUpdated(address)"); function emitFeePoolUpdated(address newFeePool) internal { proxy._emit(abi.encode(newFeePool), 1, FEEPOOLUPDATED_SIG, 0, 0, 0); } event Issued(address indexed account, uint value); bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)"); function emitIssued(address account, uint value) internal { proxy._emit(abi.encode(value), 2, ISSUED_SIG, bytes32(account), 0, 0); } event Burned(address indexed account, uint value); bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)"); function emitBurned(address account, uint value) internal { proxy._emit(abi.encode(value), 2, BURNED_SIG, bytes32(account), 0, 0); } }
/* ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Synthetix-backed stablecoin contract. This contract issues synths, which are tokens that mirror various flavours of fiat currency. Synths are issuable by Synthetix Network Token (SNX) holders who have to lock up some value of their SNX to issue S * Cmax synths. Where Cmax issome value less than 1. A configurable fee is charged on synth exchanges and deposited into the fee pool, which Synthetix holders may withdraw from once per fee period. ----------------------------------------------------------------- */
Comment
setSynthetixProxy
function setSynthetixProxy(ISynthetix _synthetixProxy) external optionalProxy_onlyOwner { synthetixProxy = _synthetixProxy; emitSynthetixUpdated(_synthetixProxy); }
/** * @notice Set the SynthetixProxy should it ever change. * The Synth requires Synthetix address as it has the authority * to mint and burn synths * */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 1475, 1683 ] }
12,275
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synth
contract Synth is ExternStateToken { /* ========== STATE VARIABLES ========== */ // Address of the FeePoolProxy address public feePoolProxy; // Address of the SynthetixProxy address public synthetixProxy; // Currency key which identifies this Synth to the Synthetix system bytes32 public currencyKey; uint8 constant DECIMALS = 18; /* ========== CONSTRUCTOR ========== */ constructor(address _proxy, TokenState _tokenState, address _synthetixProxy, address _feePoolProxy, string _tokenName, string _tokenSymbol, address _owner, bytes32 _currencyKey, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, _totalSupply, DECIMALS, _owner) public { require(_proxy != address(0), "_proxy cannot be 0"); require(_synthetixProxy != address(0), "_synthetixProxy cannot be 0"); require(_feePoolProxy != address(0), "_feePoolProxy cannot be 0"); require(_owner != 0, "_owner cannot be 0"); require(ISynthetix(_synthetixProxy).synths(_currencyKey) == Synth(0), "Currency key is already in use"); feePoolProxy = _feePoolProxy; synthetixProxy = _synthetixProxy; currencyKey = _currencyKey; } /* ========== SETTERS ========== */ /** * @notice Set the SynthetixProxy should it ever change. * The Synth requires Synthetix address as it has the authority * to mint and burn synths * */ function setSynthetixProxy(ISynthetix _synthetixProxy) external optionalProxy_onlyOwner { synthetixProxy = _synthetixProxy; emitSynthetixUpdated(_synthetixProxy); } /** * @notice Set the FeePoolProxy should it ever change. * The Synth requires FeePool address as it has the authority * to mint and burn for FeePool.claimFees() * */ function setFeePoolProxy(address _feePoolProxy) external optionalProxy_onlyOwner { feePoolProxy = _feePoolProxy; emitFeePoolUpdated(_feePoolProxy); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice ERC20 transfer function * forward call on to _internalTransfer */ function transfer(address to, uint value) public optionalProxy returns (bool) { return super._internalTransfer(messageSender, to, value); } /** * @notice ERC20 transferFrom function */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Skip allowance update in case of infinite allowance if (tokenState.allowance(from, messageSender) != uint(-1)) { // Reduce the allowance by the amount we're transferring. // The safeSub call will handle an insufficient allowance. tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); } return super._internalTransfer(from, to, value); } // Allow synthetix to issue a certain number of synths from an account. function issue(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount)); totalSupply = totalSupply.add(amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); } // Allow synthetix or another synth contract to burn a certain number of synths from an account. function burn(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount)); totalSupply = totalSupply.sub(amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); } // Allow owner to set the total supply on import. function setTotalSupply(uint amount) external optionalProxy_onlyOwner { totalSupply = amount; } /* ========== MODIFIERS ========== */ modifier onlySynthetixOrFeePool() { bool isSynthetix = msg.sender == address(Proxy(synthetixProxy).target()); bool isFeePool = msg.sender == address(Proxy(feePoolProxy).target()); require(isSynthetix || isFeePool, "Only Synthetix, FeePool allowed"); _; } /* ========== EVENTS ========== */ event SynthetixUpdated(address newSynthetix); bytes32 constant SYNTHETIXUPDATED_SIG = keccak256("SynthetixUpdated(address)"); function emitSynthetixUpdated(address newSynthetix) internal { proxy._emit(abi.encode(newSynthetix), 1, SYNTHETIXUPDATED_SIG, 0, 0, 0); } event FeePoolUpdated(address newFeePool); bytes32 constant FEEPOOLUPDATED_SIG = keccak256("FeePoolUpdated(address)"); function emitFeePoolUpdated(address newFeePool) internal { proxy._emit(abi.encode(newFeePool), 1, FEEPOOLUPDATED_SIG, 0, 0, 0); } event Issued(address indexed account, uint value); bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)"); function emitIssued(address account, uint value) internal { proxy._emit(abi.encode(value), 2, ISSUED_SIG, bytes32(account), 0, 0); } event Burned(address indexed account, uint value); bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)"); function emitBurned(address account, uint value) internal { proxy._emit(abi.encode(value), 2, BURNED_SIG, bytes32(account), 0, 0); } }
/* ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Synthetix-backed stablecoin contract. This contract issues synths, which are tokens that mirror various flavours of fiat currency. Synths are issuable by Synthetix Network Token (SNX) holders who have to lock up some value of their SNX to issue S * Cmax synths. Where Cmax issome value less than 1. A configurable fee is charged on synth exchanges and deposited into the fee pool, which Synthetix holders may withdraw from once per fee period. ----------------------------------------------------------------- */
Comment
setFeePoolProxy
function setFeePoolProxy(address _feePoolProxy) external optionalProxy_onlyOwner { feePoolProxy = _feePoolProxy; emitFeePoolUpdated(_feePoolProxy); }
/** * @notice Set the FeePoolProxy should it ever change. * The Synth requires FeePool address as it has the authority * to mint and burn for FeePool.claimFees() * */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 1876, 2069 ] }
12,276
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synth
contract Synth is ExternStateToken { /* ========== STATE VARIABLES ========== */ // Address of the FeePoolProxy address public feePoolProxy; // Address of the SynthetixProxy address public synthetixProxy; // Currency key which identifies this Synth to the Synthetix system bytes32 public currencyKey; uint8 constant DECIMALS = 18; /* ========== CONSTRUCTOR ========== */ constructor(address _proxy, TokenState _tokenState, address _synthetixProxy, address _feePoolProxy, string _tokenName, string _tokenSymbol, address _owner, bytes32 _currencyKey, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, _totalSupply, DECIMALS, _owner) public { require(_proxy != address(0), "_proxy cannot be 0"); require(_synthetixProxy != address(0), "_synthetixProxy cannot be 0"); require(_feePoolProxy != address(0), "_feePoolProxy cannot be 0"); require(_owner != 0, "_owner cannot be 0"); require(ISynthetix(_synthetixProxy).synths(_currencyKey) == Synth(0), "Currency key is already in use"); feePoolProxy = _feePoolProxy; synthetixProxy = _synthetixProxy; currencyKey = _currencyKey; } /* ========== SETTERS ========== */ /** * @notice Set the SynthetixProxy should it ever change. * The Synth requires Synthetix address as it has the authority * to mint and burn synths * */ function setSynthetixProxy(ISynthetix _synthetixProxy) external optionalProxy_onlyOwner { synthetixProxy = _synthetixProxy; emitSynthetixUpdated(_synthetixProxy); } /** * @notice Set the FeePoolProxy should it ever change. * The Synth requires FeePool address as it has the authority * to mint and burn for FeePool.claimFees() * */ function setFeePoolProxy(address _feePoolProxy) external optionalProxy_onlyOwner { feePoolProxy = _feePoolProxy; emitFeePoolUpdated(_feePoolProxy); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice ERC20 transfer function * forward call on to _internalTransfer */ function transfer(address to, uint value) public optionalProxy returns (bool) { return super._internalTransfer(messageSender, to, value); } /** * @notice ERC20 transferFrom function */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Skip allowance update in case of infinite allowance if (tokenState.allowance(from, messageSender) != uint(-1)) { // Reduce the allowance by the amount we're transferring. // The safeSub call will handle an insufficient allowance. tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); } return super._internalTransfer(from, to, value); } // Allow synthetix to issue a certain number of synths from an account. function issue(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount)); totalSupply = totalSupply.add(amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); } // Allow synthetix or another synth contract to burn a certain number of synths from an account. function burn(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount)); totalSupply = totalSupply.sub(amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); } // Allow owner to set the total supply on import. function setTotalSupply(uint amount) external optionalProxy_onlyOwner { totalSupply = amount; } /* ========== MODIFIERS ========== */ modifier onlySynthetixOrFeePool() { bool isSynthetix = msg.sender == address(Proxy(synthetixProxy).target()); bool isFeePool = msg.sender == address(Proxy(feePoolProxy).target()); require(isSynthetix || isFeePool, "Only Synthetix, FeePool allowed"); _; } /* ========== EVENTS ========== */ event SynthetixUpdated(address newSynthetix); bytes32 constant SYNTHETIXUPDATED_SIG = keccak256("SynthetixUpdated(address)"); function emitSynthetixUpdated(address newSynthetix) internal { proxy._emit(abi.encode(newSynthetix), 1, SYNTHETIXUPDATED_SIG, 0, 0, 0); } event FeePoolUpdated(address newFeePool); bytes32 constant FEEPOOLUPDATED_SIG = keccak256("FeePoolUpdated(address)"); function emitFeePoolUpdated(address newFeePool) internal { proxy._emit(abi.encode(newFeePool), 1, FEEPOOLUPDATED_SIG, 0, 0, 0); } event Issued(address indexed account, uint value); bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)"); function emitIssued(address account, uint value) internal { proxy._emit(abi.encode(value), 2, ISSUED_SIG, bytes32(account), 0, 0); } event Burned(address indexed account, uint value); bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)"); function emitBurned(address account, uint value) internal { proxy._emit(abi.encode(value), 2, BURNED_SIG, bytes32(account), 0, 0); } }
/* ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Synthetix-backed stablecoin contract. This contract issues synths, which are tokens that mirror various flavours of fiat currency. Synths are issuable by Synthetix Network Token (SNX) holders who have to lock up some value of their SNX to issue S * Cmax synths. Where Cmax issome value less than 1. A configurable fee is charged on synth exchanges and deposited into the fee pool, which Synthetix holders may withdraw from once per fee period. ----------------------------------------------------------------- */
Comment
transfer
function transfer(address to, uint value) public optionalProxy returns (bool) { return super._internalTransfer(messageSender, to, value); }
/** * @notice ERC20 transfer function * forward call on to _internalTransfer */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 2217, 2408 ] }
12,277
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synth
contract Synth is ExternStateToken { /* ========== STATE VARIABLES ========== */ // Address of the FeePoolProxy address public feePoolProxy; // Address of the SynthetixProxy address public synthetixProxy; // Currency key which identifies this Synth to the Synthetix system bytes32 public currencyKey; uint8 constant DECIMALS = 18; /* ========== CONSTRUCTOR ========== */ constructor(address _proxy, TokenState _tokenState, address _synthetixProxy, address _feePoolProxy, string _tokenName, string _tokenSymbol, address _owner, bytes32 _currencyKey, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, _totalSupply, DECIMALS, _owner) public { require(_proxy != address(0), "_proxy cannot be 0"); require(_synthetixProxy != address(0), "_synthetixProxy cannot be 0"); require(_feePoolProxy != address(0), "_feePoolProxy cannot be 0"); require(_owner != 0, "_owner cannot be 0"); require(ISynthetix(_synthetixProxy).synths(_currencyKey) == Synth(0), "Currency key is already in use"); feePoolProxy = _feePoolProxy; synthetixProxy = _synthetixProxy; currencyKey = _currencyKey; } /* ========== SETTERS ========== */ /** * @notice Set the SynthetixProxy should it ever change. * The Synth requires Synthetix address as it has the authority * to mint and burn synths * */ function setSynthetixProxy(ISynthetix _synthetixProxy) external optionalProxy_onlyOwner { synthetixProxy = _synthetixProxy; emitSynthetixUpdated(_synthetixProxy); } /** * @notice Set the FeePoolProxy should it ever change. * The Synth requires FeePool address as it has the authority * to mint and burn for FeePool.claimFees() * */ function setFeePoolProxy(address _feePoolProxy) external optionalProxy_onlyOwner { feePoolProxy = _feePoolProxy; emitFeePoolUpdated(_feePoolProxy); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice ERC20 transfer function * forward call on to _internalTransfer */ function transfer(address to, uint value) public optionalProxy returns (bool) { return super._internalTransfer(messageSender, to, value); } /** * @notice ERC20 transferFrom function */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Skip allowance update in case of infinite allowance if (tokenState.allowance(from, messageSender) != uint(-1)) { // Reduce the allowance by the amount we're transferring. // The safeSub call will handle an insufficient allowance. tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); } return super._internalTransfer(from, to, value); } // Allow synthetix to issue a certain number of synths from an account. function issue(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount)); totalSupply = totalSupply.add(amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); } // Allow synthetix or another synth contract to burn a certain number of synths from an account. function burn(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount)); totalSupply = totalSupply.sub(amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); } // Allow owner to set the total supply on import. function setTotalSupply(uint amount) external optionalProxy_onlyOwner { totalSupply = amount; } /* ========== MODIFIERS ========== */ modifier onlySynthetixOrFeePool() { bool isSynthetix = msg.sender == address(Proxy(synthetixProxy).target()); bool isFeePool = msg.sender == address(Proxy(feePoolProxy).target()); require(isSynthetix || isFeePool, "Only Synthetix, FeePool allowed"); _; } /* ========== EVENTS ========== */ event SynthetixUpdated(address newSynthetix); bytes32 constant SYNTHETIXUPDATED_SIG = keccak256("SynthetixUpdated(address)"); function emitSynthetixUpdated(address newSynthetix) internal { proxy._emit(abi.encode(newSynthetix), 1, SYNTHETIXUPDATED_SIG, 0, 0, 0); } event FeePoolUpdated(address newFeePool); bytes32 constant FEEPOOLUPDATED_SIG = keccak256("FeePoolUpdated(address)"); function emitFeePoolUpdated(address newFeePool) internal { proxy._emit(abi.encode(newFeePool), 1, FEEPOOLUPDATED_SIG, 0, 0, 0); } event Issued(address indexed account, uint value); bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)"); function emitIssued(address account, uint value) internal { proxy._emit(abi.encode(value), 2, ISSUED_SIG, bytes32(account), 0, 0); } event Burned(address indexed account, uint value); bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)"); function emitBurned(address account, uint value) internal { proxy._emit(abi.encode(value), 2, BURNED_SIG, bytes32(account), 0, 0); } }
/* ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Synthetix-backed stablecoin contract. This contract issues synths, which are tokens that mirror various flavours of fiat currency. Synths are issuable by Synthetix Network Token (SNX) holders who have to lock up some value of their SNX to issue S * Cmax synths. Where Cmax issome value less than 1. A configurable fee is charged on synth exchanges and deposited into the fee pool, which Synthetix holders may withdraw from once per fee period. ----------------------------------------------------------------- */
Comment
transferFrom
function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Skip allowance update in case of infinite allowance if (tokenState.allowance(from, messageSender) != uint(-1)) { // Reduce the allowance by the amount we're transferring. // The safeSub call will handle an insufficient allowance. tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); } return super._internalTransfer(from, to, value); }
/** * @notice ERC20 transferFrom function */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 2469, 3073 ] }
12,278
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synth
contract Synth is ExternStateToken { /* ========== STATE VARIABLES ========== */ // Address of the FeePoolProxy address public feePoolProxy; // Address of the SynthetixProxy address public synthetixProxy; // Currency key which identifies this Synth to the Synthetix system bytes32 public currencyKey; uint8 constant DECIMALS = 18; /* ========== CONSTRUCTOR ========== */ constructor(address _proxy, TokenState _tokenState, address _synthetixProxy, address _feePoolProxy, string _tokenName, string _tokenSymbol, address _owner, bytes32 _currencyKey, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, _totalSupply, DECIMALS, _owner) public { require(_proxy != address(0), "_proxy cannot be 0"); require(_synthetixProxy != address(0), "_synthetixProxy cannot be 0"); require(_feePoolProxy != address(0), "_feePoolProxy cannot be 0"); require(_owner != 0, "_owner cannot be 0"); require(ISynthetix(_synthetixProxy).synths(_currencyKey) == Synth(0), "Currency key is already in use"); feePoolProxy = _feePoolProxy; synthetixProxy = _synthetixProxy; currencyKey = _currencyKey; } /* ========== SETTERS ========== */ /** * @notice Set the SynthetixProxy should it ever change. * The Synth requires Synthetix address as it has the authority * to mint and burn synths * */ function setSynthetixProxy(ISynthetix _synthetixProxy) external optionalProxy_onlyOwner { synthetixProxy = _synthetixProxy; emitSynthetixUpdated(_synthetixProxy); } /** * @notice Set the FeePoolProxy should it ever change. * The Synth requires FeePool address as it has the authority * to mint and burn for FeePool.claimFees() * */ function setFeePoolProxy(address _feePoolProxy) external optionalProxy_onlyOwner { feePoolProxy = _feePoolProxy; emitFeePoolUpdated(_feePoolProxy); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice ERC20 transfer function * forward call on to _internalTransfer */ function transfer(address to, uint value) public optionalProxy returns (bool) { return super._internalTransfer(messageSender, to, value); } /** * @notice ERC20 transferFrom function */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Skip allowance update in case of infinite allowance if (tokenState.allowance(from, messageSender) != uint(-1)) { // Reduce the allowance by the amount we're transferring. // The safeSub call will handle an insufficient allowance. tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); } return super._internalTransfer(from, to, value); } // Allow synthetix to issue a certain number of synths from an account. function issue(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount)); totalSupply = totalSupply.add(amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); } // Allow synthetix or another synth contract to burn a certain number of synths from an account. function burn(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount)); totalSupply = totalSupply.sub(amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); } // Allow owner to set the total supply on import. function setTotalSupply(uint amount) external optionalProxy_onlyOwner { totalSupply = amount; } /* ========== MODIFIERS ========== */ modifier onlySynthetixOrFeePool() { bool isSynthetix = msg.sender == address(Proxy(synthetixProxy).target()); bool isFeePool = msg.sender == address(Proxy(feePoolProxy).target()); require(isSynthetix || isFeePool, "Only Synthetix, FeePool allowed"); _; } /* ========== EVENTS ========== */ event SynthetixUpdated(address newSynthetix); bytes32 constant SYNTHETIXUPDATED_SIG = keccak256("SynthetixUpdated(address)"); function emitSynthetixUpdated(address newSynthetix) internal { proxy._emit(abi.encode(newSynthetix), 1, SYNTHETIXUPDATED_SIG, 0, 0, 0); } event FeePoolUpdated(address newFeePool); bytes32 constant FEEPOOLUPDATED_SIG = keccak256("FeePoolUpdated(address)"); function emitFeePoolUpdated(address newFeePool) internal { proxy._emit(abi.encode(newFeePool), 1, FEEPOOLUPDATED_SIG, 0, 0, 0); } event Issued(address indexed account, uint value); bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)"); function emitIssued(address account, uint value) internal { proxy._emit(abi.encode(value), 2, ISSUED_SIG, bytes32(account), 0, 0); } event Burned(address indexed account, uint value); bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)"); function emitBurned(address account, uint value) internal { proxy._emit(abi.encode(value), 2, BURNED_SIG, bytes32(account), 0, 0); } }
/* ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Synthetix-backed stablecoin contract. This contract issues synths, which are tokens that mirror various flavours of fiat currency. Synths are issuable by Synthetix Network Token (SNX) holders who have to lock up some value of their SNX to issue S * Cmax synths. Where Cmax issome value less than 1. A configurable fee is charged on synth exchanges and deposited into the fee pool, which Synthetix holders may withdraw from once per fee period. ----------------------------------------------------------------- */
Comment
issue
function issue(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount)); totalSupply = totalSupply.add(amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); }
// Allow synthetix to issue a certain number of synths from an account.
LineComment
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 3151, 3479 ] }
12,279
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synth
contract Synth is ExternStateToken { /* ========== STATE VARIABLES ========== */ // Address of the FeePoolProxy address public feePoolProxy; // Address of the SynthetixProxy address public synthetixProxy; // Currency key which identifies this Synth to the Synthetix system bytes32 public currencyKey; uint8 constant DECIMALS = 18; /* ========== CONSTRUCTOR ========== */ constructor(address _proxy, TokenState _tokenState, address _synthetixProxy, address _feePoolProxy, string _tokenName, string _tokenSymbol, address _owner, bytes32 _currencyKey, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, _totalSupply, DECIMALS, _owner) public { require(_proxy != address(0), "_proxy cannot be 0"); require(_synthetixProxy != address(0), "_synthetixProxy cannot be 0"); require(_feePoolProxy != address(0), "_feePoolProxy cannot be 0"); require(_owner != 0, "_owner cannot be 0"); require(ISynthetix(_synthetixProxy).synths(_currencyKey) == Synth(0), "Currency key is already in use"); feePoolProxy = _feePoolProxy; synthetixProxy = _synthetixProxy; currencyKey = _currencyKey; } /* ========== SETTERS ========== */ /** * @notice Set the SynthetixProxy should it ever change. * The Synth requires Synthetix address as it has the authority * to mint and burn synths * */ function setSynthetixProxy(ISynthetix _synthetixProxy) external optionalProxy_onlyOwner { synthetixProxy = _synthetixProxy; emitSynthetixUpdated(_synthetixProxy); } /** * @notice Set the FeePoolProxy should it ever change. * The Synth requires FeePool address as it has the authority * to mint and burn for FeePool.claimFees() * */ function setFeePoolProxy(address _feePoolProxy) external optionalProxy_onlyOwner { feePoolProxy = _feePoolProxy; emitFeePoolUpdated(_feePoolProxy); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice ERC20 transfer function * forward call on to _internalTransfer */ function transfer(address to, uint value) public optionalProxy returns (bool) { return super._internalTransfer(messageSender, to, value); } /** * @notice ERC20 transferFrom function */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Skip allowance update in case of infinite allowance if (tokenState.allowance(from, messageSender) != uint(-1)) { // Reduce the allowance by the amount we're transferring. // The safeSub call will handle an insufficient allowance. tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); } return super._internalTransfer(from, to, value); } // Allow synthetix to issue a certain number of synths from an account. function issue(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount)); totalSupply = totalSupply.add(amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); } // Allow synthetix or another synth contract to burn a certain number of synths from an account. function burn(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount)); totalSupply = totalSupply.sub(amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); } // Allow owner to set the total supply on import. function setTotalSupply(uint amount) external optionalProxy_onlyOwner { totalSupply = amount; } /* ========== MODIFIERS ========== */ modifier onlySynthetixOrFeePool() { bool isSynthetix = msg.sender == address(Proxy(synthetixProxy).target()); bool isFeePool = msg.sender == address(Proxy(feePoolProxy).target()); require(isSynthetix || isFeePool, "Only Synthetix, FeePool allowed"); _; } /* ========== EVENTS ========== */ event SynthetixUpdated(address newSynthetix); bytes32 constant SYNTHETIXUPDATED_SIG = keccak256("SynthetixUpdated(address)"); function emitSynthetixUpdated(address newSynthetix) internal { proxy._emit(abi.encode(newSynthetix), 1, SYNTHETIXUPDATED_SIG, 0, 0, 0); } event FeePoolUpdated(address newFeePool); bytes32 constant FEEPOOLUPDATED_SIG = keccak256("FeePoolUpdated(address)"); function emitFeePoolUpdated(address newFeePool) internal { proxy._emit(abi.encode(newFeePool), 1, FEEPOOLUPDATED_SIG, 0, 0, 0); } event Issued(address indexed account, uint value); bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)"); function emitIssued(address account, uint value) internal { proxy._emit(abi.encode(value), 2, ISSUED_SIG, bytes32(account), 0, 0); } event Burned(address indexed account, uint value); bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)"); function emitBurned(address account, uint value) internal { proxy._emit(abi.encode(value), 2, BURNED_SIG, bytes32(account), 0, 0); } }
/* ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Synthetix-backed stablecoin contract. This contract issues synths, which are tokens that mirror various flavours of fiat currency. Synths are issuable by Synthetix Network Token (SNX) holders who have to lock up some value of their SNX to issue S * Cmax synths. Where Cmax issome value less than 1. A configurable fee is charged on synth exchanges and deposited into the fee pool, which Synthetix holders may withdraw from once per fee period. ----------------------------------------------------------------- */
Comment
burn
function burn(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount)); totalSupply = totalSupply.sub(amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); }
// Allow synthetix or another synth contract to burn a certain number of synths from an account.
LineComment
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 3582, 3909 ] }
12,280
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
Synth
contract Synth is ExternStateToken { /* ========== STATE VARIABLES ========== */ // Address of the FeePoolProxy address public feePoolProxy; // Address of the SynthetixProxy address public synthetixProxy; // Currency key which identifies this Synth to the Synthetix system bytes32 public currencyKey; uint8 constant DECIMALS = 18; /* ========== CONSTRUCTOR ========== */ constructor(address _proxy, TokenState _tokenState, address _synthetixProxy, address _feePoolProxy, string _tokenName, string _tokenSymbol, address _owner, bytes32 _currencyKey, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, _totalSupply, DECIMALS, _owner) public { require(_proxy != address(0), "_proxy cannot be 0"); require(_synthetixProxy != address(0), "_synthetixProxy cannot be 0"); require(_feePoolProxy != address(0), "_feePoolProxy cannot be 0"); require(_owner != 0, "_owner cannot be 0"); require(ISynthetix(_synthetixProxy).synths(_currencyKey) == Synth(0), "Currency key is already in use"); feePoolProxy = _feePoolProxy; synthetixProxy = _synthetixProxy; currencyKey = _currencyKey; } /* ========== SETTERS ========== */ /** * @notice Set the SynthetixProxy should it ever change. * The Synth requires Synthetix address as it has the authority * to mint and burn synths * */ function setSynthetixProxy(ISynthetix _synthetixProxy) external optionalProxy_onlyOwner { synthetixProxy = _synthetixProxy; emitSynthetixUpdated(_synthetixProxy); } /** * @notice Set the FeePoolProxy should it ever change. * The Synth requires FeePool address as it has the authority * to mint and burn for FeePool.claimFees() * */ function setFeePoolProxy(address _feePoolProxy) external optionalProxy_onlyOwner { feePoolProxy = _feePoolProxy; emitFeePoolUpdated(_feePoolProxy); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice ERC20 transfer function * forward call on to _internalTransfer */ function transfer(address to, uint value) public optionalProxy returns (bool) { return super._internalTransfer(messageSender, to, value); } /** * @notice ERC20 transferFrom function */ function transferFrom(address from, address to, uint value) public optionalProxy returns (bool) { // Skip allowance update in case of infinite allowance if (tokenState.allowance(from, messageSender) != uint(-1)) { // Reduce the allowance by the amount we're transferring. // The safeSub call will handle an insufficient allowance. tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); } return super._internalTransfer(from, to, value); } // Allow synthetix to issue a certain number of synths from an account. function issue(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount)); totalSupply = totalSupply.add(amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); } // Allow synthetix or another synth contract to burn a certain number of synths from an account. function burn(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount)); totalSupply = totalSupply.sub(amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); } // Allow owner to set the total supply on import. function setTotalSupply(uint amount) external optionalProxy_onlyOwner { totalSupply = amount; } /* ========== MODIFIERS ========== */ modifier onlySynthetixOrFeePool() { bool isSynthetix = msg.sender == address(Proxy(synthetixProxy).target()); bool isFeePool = msg.sender == address(Proxy(feePoolProxy).target()); require(isSynthetix || isFeePool, "Only Synthetix, FeePool allowed"); _; } /* ========== EVENTS ========== */ event SynthetixUpdated(address newSynthetix); bytes32 constant SYNTHETIXUPDATED_SIG = keccak256("SynthetixUpdated(address)"); function emitSynthetixUpdated(address newSynthetix) internal { proxy._emit(abi.encode(newSynthetix), 1, SYNTHETIXUPDATED_SIG, 0, 0, 0); } event FeePoolUpdated(address newFeePool); bytes32 constant FEEPOOLUPDATED_SIG = keccak256("FeePoolUpdated(address)"); function emitFeePoolUpdated(address newFeePool) internal { proxy._emit(abi.encode(newFeePool), 1, FEEPOOLUPDATED_SIG, 0, 0, 0); } event Issued(address indexed account, uint value); bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)"); function emitIssued(address account, uint value) internal { proxy._emit(abi.encode(value), 2, ISSUED_SIG, bytes32(account), 0, 0); } event Burned(address indexed account, uint value); bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)"); function emitBurned(address account, uint value) internal { proxy._emit(abi.encode(value), 2, BURNED_SIG, bytes32(account), 0, 0); } }
/* ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- Synthetix-backed stablecoin contract. This contract issues synths, which are tokens that mirror various flavours of fiat currency. Synths are issuable by Synthetix Network Token (SNX) holders who have to lock up some value of their SNX to issue S * Cmax synths. Where Cmax issome value less than 1. A configurable fee is charged on synth exchanges and deposited into the fee pool, which Synthetix holders may withdraw from once per fee period. ----------------------------------------------------------------- */
Comment
setTotalSupply
function setTotalSupply(uint amount) external optionalProxy_onlyOwner { totalSupply = amount; }
// Allow owner to set the total supply on import.
LineComment
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 3965, 4096 ] }
12,281
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ISynthetix
contract ISynthetix { // ========== PUBLIC STATE VARIABLES ========== IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ISynthetixState public synthetixState; IExchangeRates public exchangeRates; uint public totalSupply; mapping(bytes32 => Synth) public synths; // ========== PUBLIC FUNCTIONS ========== function balanceOf(address account) public view returns (uint); function transfer(address to, uint value) public returns (bool); function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view returns (uint); function synthInitiatedExchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress) external returns (bool); function exchange( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) external returns (bool); function collateralisationRatio(address issuer) public view returns (uint); function totalIssuedSynths(bytes32 currencyKey) public view returns (uint); function getSynth(bytes32 currencyKey) public view returns (ISynth); function debtBalanceOf(address issuer, bytes32 currencyKey) public view returns (uint); }
/** * @title Synthetix interface contract * @notice Abstract contract to hold public getters * @dev pseudo interface, actually declared as contract to hold the public getters */
NatSpecMultiLine
balanceOf
function balanceOf(address account) public view returns (uint);
// ========== PUBLIC FUNCTIONS ==========
LineComment
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 399, 466 ] }
12,282
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SupplySchedule
contract SupplySchedule is Owned { using SafeMath for uint; using SafeDecimalMath for uint; using Math for uint; // Time of the last inflation supply mint event uint public lastMintEvent; // Counter for number of weeks since the start of supply inflation uint public weekCounter; // The number of SNX rewarded to the caller of Synthetix.mint() uint public minterReward = 200 * SafeDecimalMath.unit(); // The initial weekly inflationary supply is 75m / 52 until the start of the decay rate. // 75e6 * SafeDecimalMath.unit() / 52 uint public constant INITIAL_WEEKLY_SUPPLY = 1442307692307692307692307; // Address of the SynthetixProxy for the onlySynthetix modifier address public synthetixProxy; // Max SNX rewards for minter uint public constant MAX_MINTER_REWARD = 200 * SafeDecimalMath.unit(); // How long each inflation period is before mint can be called uint public constant MINT_PERIOD_DURATION = 1 weeks; uint public constant INFLATION_START_DATE = 1551830400; // 2019-03-06T00:00:00+00:00 uint public constant MINT_BUFFER = 1 days; uint8 public constant SUPPLY_DECAY_START = 40; // Week 40 uint8 public constant SUPPLY_DECAY_END = 234; // Supply Decay ends on Week 234 (inclusive of Week 234 for a total of 195 weeks of inflation decay) // Weekly percentage decay of inflationary supply from the first 40 weeks of the 75% inflation rate uint public constant DECAY_RATE = 12500000000000000; // 1.25% weekly // Percentage growth of terminal supply per annum uint public constant TERMINAL_SUPPLY_RATE_ANNUAL = 25000000000000000; // 2.5% pa constructor( address _owner, uint _lastMintEvent, uint _currentWeek) Owned(_owner) public { lastMintEvent = _lastMintEvent; weekCounter = _currentWeek; } // ========== VIEWS ========== /** * @return The amount of SNX mintable for the inflationary supply */ function mintableSupply() external view returns (uint) { uint totalAmount; if (!isMintable()) { return totalAmount; } uint remainingWeeksToMint = weeksSinceLastIssuance(); uint currentWeek = weekCounter; // Calculate total mintable supply from exponential decay function // The decay function stops after week 234 while (remainingWeeksToMint > 0) { currentWeek++; // If current week is before supply decay we add initial supply to mintableSupply if (currentWeek < SUPPLY_DECAY_START) { totalAmount = totalAmount.add(INITIAL_WEEKLY_SUPPLY); remainingWeeksToMint--; } // if current week before supply decay ends we add the new supply for the week else if (currentWeek <= SUPPLY_DECAY_END) { // diff between current week and (supply decay start week - 1) uint decayCount = currentWeek.sub(SUPPLY_DECAY_START -1); totalAmount = totalAmount.add(tokenDecaySupplyForWeek(decayCount)); remainingWeeksToMint--; } // Terminal supply is calculated on the total supply of Synthetix including any new supply // We can compound the remaining week's supply at the fixed terminal rate else { uint totalSupply = ISynthetix(synthetixProxy).totalSupply(); uint currentTotalSupply = totalSupply.add(totalAmount); totalAmount = totalAmount.add(terminalInflationSupply(currentTotalSupply, remainingWeeksToMint)); remainingWeeksToMint = 0; } } return totalAmount; } /** * @return A unit amount of decaying inflationary supply from the INITIAL_WEEKLY_SUPPLY * @dev New token supply reduces by the decay rate each week calculated as supply = INITIAL_WEEKLY_SUPPLY * () */ function tokenDecaySupplyForWeek(uint counter) public pure returns (uint) { // Apply exponential decay function to number of weeks since // start of inflation smoothing to calculate diminishing supply for the week. uint effectiveDecay = (SafeDecimalMath.unit().sub(DECAY_RATE)).powDecimal(counter); uint supplyForWeek = INITIAL_WEEKLY_SUPPLY.multiplyDecimal(effectiveDecay); return supplyForWeek; } /** * @return A unit amount of terminal inflation supply * @dev Weekly compound rate based on number of weeks */ function terminalInflationSupply(uint totalSupply, uint numOfWeeks) public pure returns (uint) { // rate = (1 + weekly rate) ^ num of weeks uint effectiveCompoundRate = SafeDecimalMath.unit().add(TERMINAL_SUPPLY_RATE_ANNUAL.div(52)).powDecimal(numOfWeeks); // return Supply * (effectiveRate - 1) for extra supply to issue based on number of weeks return totalSupply.multiplyDecimal(effectiveCompoundRate.sub(SafeDecimalMath.unit())); } /** * @dev Take timeDiff in seconds (Dividend) and MINT_PERIOD_DURATION as (Divisor) * @return Calculate the numberOfWeeks since last mint rounded down to 1 week */ function weeksSinceLastIssuance() public view returns (uint) { // Get weeks since lastMintEvent // If lastMintEvent not set or 0, then start from inflation start date. uint timeDiff = lastMintEvent > 0 ? now.sub(lastMintEvent) : now.sub(INFLATION_START_DATE); return timeDiff.div(MINT_PERIOD_DURATION); } /** * @return boolean whether the MINT_PERIOD_DURATION (7 days) * has passed since the lastMintEvent. * */ function isMintable() public view returns (bool) { if (now - lastMintEvent > MINT_PERIOD_DURATION) { return true; } return false; } // ========== MUTATIVE FUNCTIONS ========== /** * @notice Record the mint event from Synthetix by incrementing the inflation * week counter for the number of weeks minted (probabaly always 1) * and store the time of the event. * @param supplyMinted the amount of SNX the total supply was inflated by. * */ function recordMintEvent(uint supplyMinted) external onlySynthetix returns (bool) { uint numberOfWeeksIssued = weeksSinceLastIssuance(); // add number of weeks minted to weekCounter weekCounter = weekCounter.add(numberOfWeeksIssued); // Update mint event to latest week issued (start date + number of weeks issued * seconds in week) // 1 day time buffer is added so inflation is minted after feePeriod closes lastMintEvent = INFLATION_START_DATE.add(weekCounter.mul(MINT_PERIOD_DURATION)).add(MINT_BUFFER); emit SupplyMinted(supplyMinted, numberOfWeeksIssued, lastMintEvent, now); return true; } /** * @notice Sets the reward amount of SNX for the caller of the public * function Synthetix.mint(). * This incentivises anyone to mint the inflationary supply and the mintr * Reward will be deducted from the inflationary supply and sent to the caller. * @param amount the amount of SNX to reward the minter. * */ function setMinterReward(uint amount) external onlyOwner { require(amount <= MAX_MINTER_REWARD, "Reward cannot exceed max minter reward"); minterReward = amount; emit MinterRewardUpdated(minterReward); } // ========== SETTERS ========== */ /** * @notice Set the SynthetixProxy should it ever change. * SupplySchedule requires Synthetix address as it has the authority * to record mint event. * */ function setSynthetixProxy(ISynthetix _synthetixProxy) external onlyOwner { require(_synthetixProxy != address(0), "Address cannot be 0"); synthetixProxy = _synthetixProxy; emit SynthetixProxyUpdated(synthetixProxy); } // ========== MODIFIERS ========== /** * @notice Only the Synthetix contract is authorised to call this function * */ modifier onlySynthetix() { require(msg.sender == address(Proxy(synthetixProxy).target()), "Only the synthetix contract can perform this action"); _; } /* ========== EVENTS ========== */ /** * @notice Emitted when the inflationary supply is minted * */ event SupplyMinted(uint supplyMinted, uint numberOfWeeksIssued, uint lastMintEvent, uint timestamp); /** * @notice Emitted when the SNX minter reward amount is updated * */ event MinterRewardUpdated(uint newRewardAmount); /** * @notice Emitted when setSynthetixProxy is called changing the Synthetix Proxy address * */ event SynthetixProxyUpdated(address newAddress); }
/** * @title SupplySchedule contract */
NatSpecMultiLine
mintableSupply
function mintableSupply() external view returns (uint) { uint totalAmount; if (!isMintable()) { return totalAmount; } uint remainingWeeksToMint = weeksSinceLastIssuance(); uint currentWeek = weekCounter; // Calculate total mintable supply from exponential decay function // The decay function stops after week 234 while (remainingWeeksToMint > 0) { currentWeek++; // If current week is before supply decay we add initial supply to mintableSupply if (currentWeek < SUPPLY_DECAY_START) { totalAmount = totalAmount.add(INITIAL_WEEKLY_SUPPLY); remainingWeeksToMint--; } // if current week before supply decay ends we add the new supply for the week else if (currentWeek <= SUPPLY_DECAY_END) { // diff between current week and (supply decay start week - 1) uint decayCount = currentWeek.sub(SUPPLY_DECAY_START -1); totalAmount = totalAmount.add(tokenDecaySupplyForWeek(decayCount)); remainingWeeksToMint--; } // Terminal supply is calculated on the total supply of Synthetix including any new supply // We can compound the remaining week's supply at the fixed terminal rate else { uint totalSupply = ISynthetix(synthetixProxy).totalSupply(); uint currentTotalSupply = totalSupply.add(totalAmount); totalAmount = totalAmount.add(terminalInflationSupply(currentTotalSupply, remainingWeeksToMint)); remainingWeeksToMint = 0; } } return totalAmount; }
/** * @return The amount of SNX mintable for the inflationary supply */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 2030, 3897 ] }
12,283
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SupplySchedule
contract SupplySchedule is Owned { using SafeMath for uint; using SafeDecimalMath for uint; using Math for uint; // Time of the last inflation supply mint event uint public lastMintEvent; // Counter for number of weeks since the start of supply inflation uint public weekCounter; // The number of SNX rewarded to the caller of Synthetix.mint() uint public minterReward = 200 * SafeDecimalMath.unit(); // The initial weekly inflationary supply is 75m / 52 until the start of the decay rate. // 75e6 * SafeDecimalMath.unit() / 52 uint public constant INITIAL_WEEKLY_SUPPLY = 1442307692307692307692307; // Address of the SynthetixProxy for the onlySynthetix modifier address public synthetixProxy; // Max SNX rewards for minter uint public constant MAX_MINTER_REWARD = 200 * SafeDecimalMath.unit(); // How long each inflation period is before mint can be called uint public constant MINT_PERIOD_DURATION = 1 weeks; uint public constant INFLATION_START_DATE = 1551830400; // 2019-03-06T00:00:00+00:00 uint public constant MINT_BUFFER = 1 days; uint8 public constant SUPPLY_DECAY_START = 40; // Week 40 uint8 public constant SUPPLY_DECAY_END = 234; // Supply Decay ends on Week 234 (inclusive of Week 234 for a total of 195 weeks of inflation decay) // Weekly percentage decay of inflationary supply from the first 40 weeks of the 75% inflation rate uint public constant DECAY_RATE = 12500000000000000; // 1.25% weekly // Percentage growth of terminal supply per annum uint public constant TERMINAL_SUPPLY_RATE_ANNUAL = 25000000000000000; // 2.5% pa constructor( address _owner, uint _lastMintEvent, uint _currentWeek) Owned(_owner) public { lastMintEvent = _lastMintEvent; weekCounter = _currentWeek; } // ========== VIEWS ========== /** * @return The amount of SNX mintable for the inflationary supply */ function mintableSupply() external view returns (uint) { uint totalAmount; if (!isMintable()) { return totalAmount; } uint remainingWeeksToMint = weeksSinceLastIssuance(); uint currentWeek = weekCounter; // Calculate total mintable supply from exponential decay function // The decay function stops after week 234 while (remainingWeeksToMint > 0) { currentWeek++; // If current week is before supply decay we add initial supply to mintableSupply if (currentWeek < SUPPLY_DECAY_START) { totalAmount = totalAmount.add(INITIAL_WEEKLY_SUPPLY); remainingWeeksToMint--; } // if current week before supply decay ends we add the new supply for the week else if (currentWeek <= SUPPLY_DECAY_END) { // diff between current week and (supply decay start week - 1) uint decayCount = currentWeek.sub(SUPPLY_DECAY_START -1); totalAmount = totalAmount.add(tokenDecaySupplyForWeek(decayCount)); remainingWeeksToMint--; } // Terminal supply is calculated on the total supply of Synthetix including any new supply // We can compound the remaining week's supply at the fixed terminal rate else { uint totalSupply = ISynthetix(synthetixProxy).totalSupply(); uint currentTotalSupply = totalSupply.add(totalAmount); totalAmount = totalAmount.add(terminalInflationSupply(currentTotalSupply, remainingWeeksToMint)); remainingWeeksToMint = 0; } } return totalAmount; } /** * @return A unit amount of decaying inflationary supply from the INITIAL_WEEKLY_SUPPLY * @dev New token supply reduces by the decay rate each week calculated as supply = INITIAL_WEEKLY_SUPPLY * () */ function tokenDecaySupplyForWeek(uint counter) public pure returns (uint) { // Apply exponential decay function to number of weeks since // start of inflation smoothing to calculate diminishing supply for the week. uint effectiveDecay = (SafeDecimalMath.unit().sub(DECAY_RATE)).powDecimal(counter); uint supplyForWeek = INITIAL_WEEKLY_SUPPLY.multiplyDecimal(effectiveDecay); return supplyForWeek; } /** * @return A unit amount of terminal inflation supply * @dev Weekly compound rate based on number of weeks */ function terminalInflationSupply(uint totalSupply, uint numOfWeeks) public pure returns (uint) { // rate = (1 + weekly rate) ^ num of weeks uint effectiveCompoundRate = SafeDecimalMath.unit().add(TERMINAL_SUPPLY_RATE_ANNUAL.div(52)).powDecimal(numOfWeeks); // return Supply * (effectiveRate - 1) for extra supply to issue based on number of weeks return totalSupply.multiplyDecimal(effectiveCompoundRate.sub(SafeDecimalMath.unit())); } /** * @dev Take timeDiff in seconds (Dividend) and MINT_PERIOD_DURATION as (Divisor) * @return Calculate the numberOfWeeks since last mint rounded down to 1 week */ function weeksSinceLastIssuance() public view returns (uint) { // Get weeks since lastMintEvent // If lastMintEvent not set or 0, then start from inflation start date. uint timeDiff = lastMintEvent > 0 ? now.sub(lastMintEvent) : now.sub(INFLATION_START_DATE); return timeDiff.div(MINT_PERIOD_DURATION); } /** * @return boolean whether the MINT_PERIOD_DURATION (7 days) * has passed since the lastMintEvent. * */ function isMintable() public view returns (bool) { if (now - lastMintEvent > MINT_PERIOD_DURATION) { return true; } return false; } // ========== MUTATIVE FUNCTIONS ========== /** * @notice Record the mint event from Synthetix by incrementing the inflation * week counter for the number of weeks minted (probabaly always 1) * and store the time of the event. * @param supplyMinted the amount of SNX the total supply was inflated by. * */ function recordMintEvent(uint supplyMinted) external onlySynthetix returns (bool) { uint numberOfWeeksIssued = weeksSinceLastIssuance(); // add number of weeks minted to weekCounter weekCounter = weekCounter.add(numberOfWeeksIssued); // Update mint event to latest week issued (start date + number of weeks issued * seconds in week) // 1 day time buffer is added so inflation is minted after feePeriod closes lastMintEvent = INFLATION_START_DATE.add(weekCounter.mul(MINT_PERIOD_DURATION)).add(MINT_BUFFER); emit SupplyMinted(supplyMinted, numberOfWeeksIssued, lastMintEvent, now); return true; } /** * @notice Sets the reward amount of SNX for the caller of the public * function Synthetix.mint(). * This incentivises anyone to mint the inflationary supply and the mintr * Reward will be deducted from the inflationary supply and sent to the caller. * @param amount the amount of SNX to reward the minter. * */ function setMinterReward(uint amount) external onlyOwner { require(amount <= MAX_MINTER_REWARD, "Reward cannot exceed max minter reward"); minterReward = amount; emit MinterRewardUpdated(minterReward); } // ========== SETTERS ========== */ /** * @notice Set the SynthetixProxy should it ever change. * SupplySchedule requires Synthetix address as it has the authority * to record mint event. * */ function setSynthetixProxy(ISynthetix _synthetixProxy) external onlyOwner { require(_synthetixProxy != address(0), "Address cannot be 0"); synthetixProxy = _synthetixProxy; emit SynthetixProxyUpdated(synthetixProxy); } // ========== MODIFIERS ========== /** * @notice Only the Synthetix contract is authorised to call this function * */ modifier onlySynthetix() { require(msg.sender == address(Proxy(synthetixProxy).target()), "Only the synthetix contract can perform this action"); _; } /* ========== EVENTS ========== */ /** * @notice Emitted when the inflationary supply is minted * */ event SupplyMinted(uint supplyMinted, uint numberOfWeeksIssued, uint lastMintEvent, uint timestamp); /** * @notice Emitted when the SNX minter reward amount is updated * */ event MinterRewardUpdated(uint newRewardAmount); /** * @notice Emitted when setSynthetixProxy is called changing the Synthetix Proxy address * */ event SynthetixProxyUpdated(address newAddress); }
/** * @title SupplySchedule contract */
NatSpecMultiLine
tokenDecaySupplyForWeek
function tokenDecaySupplyForWeek(uint counter) public pure returns (uint) { // Apply exponential decay function to number of weeks since // start of inflation smoothing to calculate diminishing supply for the week. uint effectiveDecay = (SafeDecimalMath.unit().sub(DECAY_RATE)).powDecimal(counter); uint supplyForWeek = INITIAL_WEEKLY_SUPPLY.multiplyDecimal(effectiveDecay); return supplyForWeek; }
/** * @return A unit amount of decaying inflationary supply from the INITIAL_WEEKLY_SUPPLY * @dev New token supply reduces by the decay rate each week calculated as supply = INITIAL_WEEKLY_SUPPLY * () */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 4120, 4603 ] }
12,284
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SupplySchedule
contract SupplySchedule is Owned { using SafeMath for uint; using SafeDecimalMath for uint; using Math for uint; // Time of the last inflation supply mint event uint public lastMintEvent; // Counter for number of weeks since the start of supply inflation uint public weekCounter; // The number of SNX rewarded to the caller of Synthetix.mint() uint public minterReward = 200 * SafeDecimalMath.unit(); // The initial weekly inflationary supply is 75m / 52 until the start of the decay rate. // 75e6 * SafeDecimalMath.unit() / 52 uint public constant INITIAL_WEEKLY_SUPPLY = 1442307692307692307692307; // Address of the SynthetixProxy for the onlySynthetix modifier address public synthetixProxy; // Max SNX rewards for minter uint public constant MAX_MINTER_REWARD = 200 * SafeDecimalMath.unit(); // How long each inflation period is before mint can be called uint public constant MINT_PERIOD_DURATION = 1 weeks; uint public constant INFLATION_START_DATE = 1551830400; // 2019-03-06T00:00:00+00:00 uint public constant MINT_BUFFER = 1 days; uint8 public constant SUPPLY_DECAY_START = 40; // Week 40 uint8 public constant SUPPLY_DECAY_END = 234; // Supply Decay ends on Week 234 (inclusive of Week 234 for a total of 195 weeks of inflation decay) // Weekly percentage decay of inflationary supply from the first 40 weeks of the 75% inflation rate uint public constant DECAY_RATE = 12500000000000000; // 1.25% weekly // Percentage growth of terminal supply per annum uint public constant TERMINAL_SUPPLY_RATE_ANNUAL = 25000000000000000; // 2.5% pa constructor( address _owner, uint _lastMintEvent, uint _currentWeek) Owned(_owner) public { lastMintEvent = _lastMintEvent; weekCounter = _currentWeek; } // ========== VIEWS ========== /** * @return The amount of SNX mintable for the inflationary supply */ function mintableSupply() external view returns (uint) { uint totalAmount; if (!isMintable()) { return totalAmount; } uint remainingWeeksToMint = weeksSinceLastIssuance(); uint currentWeek = weekCounter; // Calculate total mintable supply from exponential decay function // The decay function stops after week 234 while (remainingWeeksToMint > 0) { currentWeek++; // If current week is before supply decay we add initial supply to mintableSupply if (currentWeek < SUPPLY_DECAY_START) { totalAmount = totalAmount.add(INITIAL_WEEKLY_SUPPLY); remainingWeeksToMint--; } // if current week before supply decay ends we add the new supply for the week else if (currentWeek <= SUPPLY_DECAY_END) { // diff between current week and (supply decay start week - 1) uint decayCount = currentWeek.sub(SUPPLY_DECAY_START -1); totalAmount = totalAmount.add(tokenDecaySupplyForWeek(decayCount)); remainingWeeksToMint--; } // Terminal supply is calculated on the total supply of Synthetix including any new supply // We can compound the remaining week's supply at the fixed terminal rate else { uint totalSupply = ISynthetix(synthetixProxy).totalSupply(); uint currentTotalSupply = totalSupply.add(totalAmount); totalAmount = totalAmount.add(terminalInflationSupply(currentTotalSupply, remainingWeeksToMint)); remainingWeeksToMint = 0; } } return totalAmount; } /** * @return A unit amount of decaying inflationary supply from the INITIAL_WEEKLY_SUPPLY * @dev New token supply reduces by the decay rate each week calculated as supply = INITIAL_WEEKLY_SUPPLY * () */ function tokenDecaySupplyForWeek(uint counter) public pure returns (uint) { // Apply exponential decay function to number of weeks since // start of inflation smoothing to calculate diminishing supply for the week. uint effectiveDecay = (SafeDecimalMath.unit().sub(DECAY_RATE)).powDecimal(counter); uint supplyForWeek = INITIAL_WEEKLY_SUPPLY.multiplyDecimal(effectiveDecay); return supplyForWeek; } /** * @return A unit amount of terminal inflation supply * @dev Weekly compound rate based on number of weeks */ function terminalInflationSupply(uint totalSupply, uint numOfWeeks) public pure returns (uint) { // rate = (1 + weekly rate) ^ num of weeks uint effectiveCompoundRate = SafeDecimalMath.unit().add(TERMINAL_SUPPLY_RATE_ANNUAL.div(52)).powDecimal(numOfWeeks); // return Supply * (effectiveRate - 1) for extra supply to issue based on number of weeks return totalSupply.multiplyDecimal(effectiveCompoundRate.sub(SafeDecimalMath.unit())); } /** * @dev Take timeDiff in seconds (Dividend) and MINT_PERIOD_DURATION as (Divisor) * @return Calculate the numberOfWeeks since last mint rounded down to 1 week */ function weeksSinceLastIssuance() public view returns (uint) { // Get weeks since lastMintEvent // If lastMintEvent not set or 0, then start from inflation start date. uint timeDiff = lastMintEvent > 0 ? now.sub(lastMintEvent) : now.sub(INFLATION_START_DATE); return timeDiff.div(MINT_PERIOD_DURATION); } /** * @return boolean whether the MINT_PERIOD_DURATION (7 days) * has passed since the lastMintEvent. * */ function isMintable() public view returns (bool) { if (now - lastMintEvent > MINT_PERIOD_DURATION) { return true; } return false; } // ========== MUTATIVE FUNCTIONS ========== /** * @notice Record the mint event from Synthetix by incrementing the inflation * week counter for the number of weeks minted (probabaly always 1) * and store the time of the event. * @param supplyMinted the amount of SNX the total supply was inflated by. * */ function recordMintEvent(uint supplyMinted) external onlySynthetix returns (bool) { uint numberOfWeeksIssued = weeksSinceLastIssuance(); // add number of weeks minted to weekCounter weekCounter = weekCounter.add(numberOfWeeksIssued); // Update mint event to latest week issued (start date + number of weeks issued * seconds in week) // 1 day time buffer is added so inflation is minted after feePeriod closes lastMintEvent = INFLATION_START_DATE.add(weekCounter.mul(MINT_PERIOD_DURATION)).add(MINT_BUFFER); emit SupplyMinted(supplyMinted, numberOfWeeksIssued, lastMintEvent, now); return true; } /** * @notice Sets the reward amount of SNX for the caller of the public * function Synthetix.mint(). * This incentivises anyone to mint the inflationary supply and the mintr * Reward will be deducted from the inflationary supply and sent to the caller. * @param amount the amount of SNX to reward the minter. * */ function setMinterReward(uint amount) external onlyOwner { require(amount <= MAX_MINTER_REWARD, "Reward cannot exceed max minter reward"); minterReward = amount; emit MinterRewardUpdated(minterReward); } // ========== SETTERS ========== */ /** * @notice Set the SynthetixProxy should it ever change. * SupplySchedule requires Synthetix address as it has the authority * to record mint event. * */ function setSynthetixProxy(ISynthetix _synthetixProxy) external onlyOwner { require(_synthetixProxy != address(0), "Address cannot be 0"); synthetixProxy = _synthetixProxy; emit SynthetixProxyUpdated(synthetixProxy); } // ========== MODIFIERS ========== /** * @notice Only the Synthetix contract is authorised to call this function * */ modifier onlySynthetix() { require(msg.sender == address(Proxy(synthetixProxy).target()), "Only the synthetix contract can perform this action"); _; } /* ========== EVENTS ========== */ /** * @notice Emitted when the inflationary supply is minted * */ event SupplyMinted(uint supplyMinted, uint numberOfWeeksIssued, uint lastMintEvent, uint timestamp); /** * @notice Emitted when the SNX minter reward amount is updated * */ event MinterRewardUpdated(uint newRewardAmount); /** * @notice Emitted when setSynthetixProxy is called changing the Synthetix Proxy address * */ event SynthetixProxyUpdated(address newAddress); }
/** * @title SupplySchedule contract */
NatSpecMultiLine
terminalInflationSupply
function terminalInflationSupply(uint totalSupply, uint numOfWeeks) public pure returns (uint) { // rate = (1 + weekly rate) ^ num of weeks uint effectiveCompoundRate = SafeDecimalMath.unit().add(TERMINAL_SUPPLY_RATE_ANNUAL.div(52)).powDecimal(numOfWeeks); // return Supply * (effectiveRate - 1) for extra supply to issue based on number of weeks return totalSupply.multiplyDecimal(effectiveCompoundRate.sub(SafeDecimalMath.unit())); }
/** * @return A unit amount of terminal inflation supply * @dev Weekly compound rate based on number of weeks */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 4743, 5250 ] }
12,285
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SupplySchedule
contract SupplySchedule is Owned { using SafeMath for uint; using SafeDecimalMath for uint; using Math for uint; // Time of the last inflation supply mint event uint public lastMintEvent; // Counter for number of weeks since the start of supply inflation uint public weekCounter; // The number of SNX rewarded to the caller of Synthetix.mint() uint public minterReward = 200 * SafeDecimalMath.unit(); // The initial weekly inflationary supply is 75m / 52 until the start of the decay rate. // 75e6 * SafeDecimalMath.unit() / 52 uint public constant INITIAL_WEEKLY_SUPPLY = 1442307692307692307692307; // Address of the SynthetixProxy for the onlySynthetix modifier address public synthetixProxy; // Max SNX rewards for minter uint public constant MAX_MINTER_REWARD = 200 * SafeDecimalMath.unit(); // How long each inflation period is before mint can be called uint public constant MINT_PERIOD_DURATION = 1 weeks; uint public constant INFLATION_START_DATE = 1551830400; // 2019-03-06T00:00:00+00:00 uint public constant MINT_BUFFER = 1 days; uint8 public constant SUPPLY_DECAY_START = 40; // Week 40 uint8 public constant SUPPLY_DECAY_END = 234; // Supply Decay ends on Week 234 (inclusive of Week 234 for a total of 195 weeks of inflation decay) // Weekly percentage decay of inflationary supply from the first 40 weeks of the 75% inflation rate uint public constant DECAY_RATE = 12500000000000000; // 1.25% weekly // Percentage growth of terminal supply per annum uint public constant TERMINAL_SUPPLY_RATE_ANNUAL = 25000000000000000; // 2.5% pa constructor( address _owner, uint _lastMintEvent, uint _currentWeek) Owned(_owner) public { lastMintEvent = _lastMintEvent; weekCounter = _currentWeek; } // ========== VIEWS ========== /** * @return The amount of SNX mintable for the inflationary supply */ function mintableSupply() external view returns (uint) { uint totalAmount; if (!isMintable()) { return totalAmount; } uint remainingWeeksToMint = weeksSinceLastIssuance(); uint currentWeek = weekCounter; // Calculate total mintable supply from exponential decay function // The decay function stops after week 234 while (remainingWeeksToMint > 0) { currentWeek++; // If current week is before supply decay we add initial supply to mintableSupply if (currentWeek < SUPPLY_DECAY_START) { totalAmount = totalAmount.add(INITIAL_WEEKLY_SUPPLY); remainingWeeksToMint--; } // if current week before supply decay ends we add the new supply for the week else if (currentWeek <= SUPPLY_DECAY_END) { // diff between current week and (supply decay start week - 1) uint decayCount = currentWeek.sub(SUPPLY_DECAY_START -1); totalAmount = totalAmount.add(tokenDecaySupplyForWeek(decayCount)); remainingWeeksToMint--; } // Terminal supply is calculated on the total supply of Synthetix including any new supply // We can compound the remaining week's supply at the fixed terminal rate else { uint totalSupply = ISynthetix(synthetixProxy).totalSupply(); uint currentTotalSupply = totalSupply.add(totalAmount); totalAmount = totalAmount.add(terminalInflationSupply(currentTotalSupply, remainingWeeksToMint)); remainingWeeksToMint = 0; } } return totalAmount; } /** * @return A unit amount of decaying inflationary supply from the INITIAL_WEEKLY_SUPPLY * @dev New token supply reduces by the decay rate each week calculated as supply = INITIAL_WEEKLY_SUPPLY * () */ function tokenDecaySupplyForWeek(uint counter) public pure returns (uint) { // Apply exponential decay function to number of weeks since // start of inflation smoothing to calculate diminishing supply for the week. uint effectiveDecay = (SafeDecimalMath.unit().sub(DECAY_RATE)).powDecimal(counter); uint supplyForWeek = INITIAL_WEEKLY_SUPPLY.multiplyDecimal(effectiveDecay); return supplyForWeek; } /** * @return A unit amount of terminal inflation supply * @dev Weekly compound rate based on number of weeks */ function terminalInflationSupply(uint totalSupply, uint numOfWeeks) public pure returns (uint) { // rate = (1 + weekly rate) ^ num of weeks uint effectiveCompoundRate = SafeDecimalMath.unit().add(TERMINAL_SUPPLY_RATE_ANNUAL.div(52)).powDecimal(numOfWeeks); // return Supply * (effectiveRate - 1) for extra supply to issue based on number of weeks return totalSupply.multiplyDecimal(effectiveCompoundRate.sub(SafeDecimalMath.unit())); } /** * @dev Take timeDiff in seconds (Dividend) and MINT_PERIOD_DURATION as (Divisor) * @return Calculate the numberOfWeeks since last mint rounded down to 1 week */ function weeksSinceLastIssuance() public view returns (uint) { // Get weeks since lastMintEvent // If lastMintEvent not set or 0, then start from inflation start date. uint timeDiff = lastMintEvent > 0 ? now.sub(lastMintEvent) : now.sub(INFLATION_START_DATE); return timeDiff.div(MINT_PERIOD_DURATION); } /** * @return boolean whether the MINT_PERIOD_DURATION (7 days) * has passed since the lastMintEvent. * */ function isMintable() public view returns (bool) { if (now - lastMintEvent > MINT_PERIOD_DURATION) { return true; } return false; } // ========== MUTATIVE FUNCTIONS ========== /** * @notice Record the mint event from Synthetix by incrementing the inflation * week counter for the number of weeks minted (probabaly always 1) * and store the time of the event. * @param supplyMinted the amount of SNX the total supply was inflated by. * */ function recordMintEvent(uint supplyMinted) external onlySynthetix returns (bool) { uint numberOfWeeksIssued = weeksSinceLastIssuance(); // add number of weeks minted to weekCounter weekCounter = weekCounter.add(numberOfWeeksIssued); // Update mint event to latest week issued (start date + number of weeks issued * seconds in week) // 1 day time buffer is added so inflation is minted after feePeriod closes lastMintEvent = INFLATION_START_DATE.add(weekCounter.mul(MINT_PERIOD_DURATION)).add(MINT_BUFFER); emit SupplyMinted(supplyMinted, numberOfWeeksIssued, lastMintEvent, now); return true; } /** * @notice Sets the reward amount of SNX for the caller of the public * function Synthetix.mint(). * This incentivises anyone to mint the inflationary supply and the mintr * Reward will be deducted from the inflationary supply and sent to the caller. * @param amount the amount of SNX to reward the minter. * */ function setMinterReward(uint amount) external onlyOwner { require(amount <= MAX_MINTER_REWARD, "Reward cannot exceed max minter reward"); minterReward = amount; emit MinterRewardUpdated(minterReward); } // ========== SETTERS ========== */ /** * @notice Set the SynthetixProxy should it ever change. * SupplySchedule requires Synthetix address as it has the authority * to record mint event. * */ function setSynthetixProxy(ISynthetix _synthetixProxy) external onlyOwner { require(_synthetixProxy != address(0), "Address cannot be 0"); synthetixProxy = _synthetixProxy; emit SynthetixProxyUpdated(synthetixProxy); } // ========== MODIFIERS ========== /** * @notice Only the Synthetix contract is authorised to call this function * */ modifier onlySynthetix() { require(msg.sender == address(Proxy(synthetixProxy).target()), "Only the synthetix contract can perform this action"); _; } /* ========== EVENTS ========== */ /** * @notice Emitted when the inflationary supply is minted * */ event SupplyMinted(uint supplyMinted, uint numberOfWeeksIssued, uint lastMintEvent, uint timestamp); /** * @notice Emitted when the SNX minter reward amount is updated * */ event MinterRewardUpdated(uint newRewardAmount); /** * @notice Emitted when setSynthetixProxy is called changing the Synthetix Proxy address * */ event SynthetixProxyUpdated(address newAddress); }
/** * @title SupplySchedule contract */
NatSpecMultiLine
weeksSinceLastIssuance
function weeksSinceLastIssuance() public view returns (uint) { // Get weeks since lastMintEvent // If lastMintEvent not set or 0, then start from inflation start date. uint timeDiff = lastMintEvent > 0 ? now.sub(lastMintEvent) : now.sub(INFLATION_START_DATE); return timeDiff.div(MINT_PERIOD_DURATION); }
/** * @dev Take timeDiff in seconds (Dividend) and MINT_PERIOD_DURATION as (Divisor) * @return Calculate the numberOfWeeks since last mint rounded down to 1 week */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 5437, 5809 ] }
12,286
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SupplySchedule
contract SupplySchedule is Owned { using SafeMath for uint; using SafeDecimalMath for uint; using Math for uint; // Time of the last inflation supply mint event uint public lastMintEvent; // Counter for number of weeks since the start of supply inflation uint public weekCounter; // The number of SNX rewarded to the caller of Synthetix.mint() uint public minterReward = 200 * SafeDecimalMath.unit(); // The initial weekly inflationary supply is 75m / 52 until the start of the decay rate. // 75e6 * SafeDecimalMath.unit() / 52 uint public constant INITIAL_WEEKLY_SUPPLY = 1442307692307692307692307; // Address of the SynthetixProxy for the onlySynthetix modifier address public synthetixProxy; // Max SNX rewards for minter uint public constant MAX_MINTER_REWARD = 200 * SafeDecimalMath.unit(); // How long each inflation period is before mint can be called uint public constant MINT_PERIOD_DURATION = 1 weeks; uint public constant INFLATION_START_DATE = 1551830400; // 2019-03-06T00:00:00+00:00 uint public constant MINT_BUFFER = 1 days; uint8 public constant SUPPLY_DECAY_START = 40; // Week 40 uint8 public constant SUPPLY_DECAY_END = 234; // Supply Decay ends on Week 234 (inclusive of Week 234 for a total of 195 weeks of inflation decay) // Weekly percentage decay of inflationary supply from the first 40 weeks of the 75% inflation rate uint public constant DECAY_RATE = 12500000000000000; // 1.25% weekly // Percentage growth of terminal supply per annum uint public constant TERMINAL_SUPPLY_RATE_ANNUAL = 25000000000000000; // 2.5% pa constructor( address _owner, uint _lastMintEvent, uint _currentWeek) Owned(_owner) public { lastMintEvent = _lastMintEvent; weekCounter = _currentWeek; } // ========== VIEWS ========== /** * @return The amount of SNX mintable for the inflationary supply */ function mintableSupply() external view returns (uint) { uint totalAmount; if (!isMintable()) { return totalAmount; } uint remainingWeeksToMint = weeksSinceLastIssuance(); uint currentWeek = weekCounter; // Calculate total mintable supply from exponential decay function // The decay function stops after week 234 while (remainingWeeksToMint > 0) { currentWeek++; // If current week is before supply decay we add initial supply to mintableSupply if (currentWeek < SUPPLY_DECAY_START) { totalAmount = totalAmount.add(INITIAL_WEEKLY_SUPPLY); remainingWeeksToMint--; } // if current week before supply decay ends we add the new supply for the week else if (currentWeek <= SUPPLY_DECAY_END) { // diff between current week and (supply decay start week - 1) uint decayCount = currentWeek.sub(SUPPLY_DECAY_START -1); totalAmount = totalAmount.add(tokenDecaySupplyForWeek(decayCount)); remainingWeeksToMint--; } // Terminal supply is calculated on the total supply of Synthetix including any new supply // We can compound the remaining week's supply at the fixed terminal rate else { uint totalSupply = ISynthetix(synthetixProxy).totalSupply(); uint currentTotalSupply = totalSupply.add(totalAmount); totalAmount = totalAmount.add(terminalInflationSupply(currentTotalSupply, remainingWeeksToMint)); remainingWeeksToMint = 0; } } return totalAmount; } /** * @return A unit amount of decaying inflationary supply from the INITIAL_WEEKLY_SUPPLY * @dev New token supply reduces by the decay rate each week calculated as supply = INITIAL_WEEKLY_SUPPLY * () */ function tokenDecaySupplyForWeek(uint counter) public pure returns (uint) { // Apply exponential decay function to number of weeks since // start of inflation smoothing to calculate diminishing supply for the week. uint effectiveDecay = (SafeDecimalMath.unit().sub(DECAY_RATE)).powDecimal(counter); uint supplyForWeek = INITIAL_WEEKLY_SUPPLY.multiplyDecimal(effectiveDecay); return supplyForWeek; } /** * @return A unit amount of terminal inflation supply * @dev Weekly compound rate based on number of weeks */ function terminalInflationSupply(uint totalSupply, uint numOfWeeks) public pure returns (uint) { // rate = (1 + weekly rate) ^ num of weeks uint effectiveCompoundRate = SafeDecimalMath.unit().add(TERMINAL_SUPPLY_RATE_ANNUAL.div(52)).powDecimal(numOfWeeks); // return Supply * (effectiveRate - 1) for extra supply to issue based on number of weeks return totalSupply.multiplyDecimal(effectiveCompoundRate.sub(SafeDecimalMath.unit())); } /** * @dev Take timeDiff in seconds (Dividend) and MINT_PERIOD_DURATION as (Divisor) * @return Calculate the numberOfWeeks since last mint rounded down to 1 week */ function weeksSinceLastIssuance() public view returns (uint) { // Get weeks since lastMintEvent // If lastMintEvent not set or 0, then start from inflation start date. uint timeDiff = lastMintEvent > 0 ? now.sub(lastMintEvent) : now.sub(INFLATION_START_DATE); return timeDiff.div(MINT_PERIOD_DURATION); } /** * @return boolean whether the MINT_PERIOD_DURATION (7 days) * has passed since the lastMintEvent. * */ function isMintable() public view returns (bool) { if (now - lastMintEvent > MINT_PERIOD_DURATION) { return true; } return false; } // ========== MUTATIVE FUNCTIONS ========== /** * @notice Record the mint event from Synthetix by incrementing the inflation * week counter for the number of weeks minted (probabaly always 1) * and store the time of the event. * @param supplyMinted the amount of SNX the total supply was inflated by. * */ function recordMintEvent(uint supplyMinted) external onlySynthetix returns (bool) { uint numberOfWeeksIssued = weeksSinceLastIssuance(); // add number of weeks minted to weekCounter weekCounter = weekCounter.add(numberOfWeeksIssued); // Update mint event to latest week issued (start date + number of weeks issued * seconds in week) // 1 day time buffer is added so inflation is minted after feePeriod closes lastMintEvent = INFLATION_START_DATE.add(weekCounter.mul(MINT_PERIOD_DURATION)).add(MINT_BUFFER); emit SupplyMinted(supplyMinted, numberOfWeeksIssued, lastMintEvent, now); return true; } /** * @notice Sets the reward amount of SNX for the caller of the public * function Synthetix.mint(). * This incentivises anyone to mint the inflationary supply and the mintr * Reward will be deducted from the inflationary supply and sent to the caller. * @param amount the amount of SNX to reward the minter. * */ function setMinterReward(uint amount) external onlyOwner { require(amount <= MAX_MINTER_REWARD, "Reward cannot exceed max minter reward"); minterReward = amount; emit MinterRewardUpdated(minterReward); } // ========== SETTERS ========== */ /** * @notice Set the SynthetixProxy should it ever change. * SupplySchedule requires Synthetix address as it has the authority * to record mint event. * */ function setSynthetixProxy(ISynthetix _synthetixProxy) external onlyOwner { require(_synthetixProxy != address(0), "Address cannot be 0"); synthetixProxy = _synthetixProxy; emit SynthetixProxyUpdated(synthetixProxy); } // ========== MODIFIERS ========== /** * @notice Only the Synthetix contract is authorised to call this function * */ modifier onlySynthetix() { require(msg.sender == address(Proxy(synthetixProxy).target()), "Only the synthetix contract can perform this action"); _; } /* ========== EVENTS ========== */ /** * @notice Emitted when the inflationary supply is minted * */ event SupplyMinted(uint supplyMinted, uint numberOfWeeksIssued, uint lastMintEvent, uint timestamp); /** * @notice Emitted when the SNX minter reward amount is updated * */ event MinterRewardUpdated(uint newRewardAmount); /** * @notice Emitted when setSynthetixProxy is called changing the Synthetix Proxy address * */ event SynthetixProxyUpdated(address newAddress); }
/** * @title SupplySchedule contract */
NatSpecMultiLine
isMintable
function isMintable() public view returns (bool) { if (now - lastMintEvent > MINT_PERIOD_DURATION) { return true; } return false; }
/** * @return boolean whether the MINT_PERIOD_DURATION (7 days) * has passed since the lastMintEvent. * */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 5937, 6148 ] }
12,287
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SupplySchedule
contract SupplySchedule is Owned { using SafeMath for uint; using SafeDecimalMath for uint; using Math for uint; // Time of the last inflation supply mint event uint public lastMintEvent; // Counter for number of weeks since the start of supply inflation uint public weekCounter; // The number of SNX rewarded to the caller of Synthetix.mint() uint public minterReward = 200 * SafeDecimalMath.unit(); // The initial weekly inflationary supply is 75m / 52 until the start of the decay rate. // 75e6 * SafeDecimalMath.unit() / 52 uint public constant INITIAL_WEEKLY_SUPPLY = 1442307692307692307692307; // Address of the SynthetixProxy for the onlySynthetix modifier address public synthetixProxy; // Max SNX rewards for minter uint public constant MAX_MINTER_REWARD = 200 * SafeDecimalMath.unit(); // How long each inflation period is before mint can be called uint public constant MINT_PERIOD_DURATION = 1 weeks; uint public constant INFLATION_START_DATE = 1551830400; // 2019-03-06T00:00:00+00:00 uint public constant MINT_BUFFER = 1 days; uint8 public constant SUPPLY_DECAY_START = 40; // Week 40 uint8 public constant SUPPLY_DECAY_END = 234; // Supply Decay ends on Week 234 (inclusive of Week 234 for a total of 195 weeks of inflation decay) // Weekly percentage decay of inflationary supply from the first 40 weeks of the 75% inflation rate uint public constant DECAY_RATE = 12500000000000000; // 1.25% weekly // Percentage growth of terminal supply per annum uint public constant TERMINAL_SUPPLY_RATE_ANNUAL = 25000000000000000; // 2.5% pa constructor( address _owner, uint _lastMintEvent, uint _currentWeek) Owned(_owner) public { lastMintEvent = _lastMintEvent; weekCounter = _currentWeek; } // ========== VIEWS ========== /** * @return The amount of SNX mintable for the inflationary supply */ function mintableSupply() external view returns (uint) { uint totalAmount; if (!isMintable()) { return totalAmount; } uint remainingWeeksToMint = weeksSinceLastIssuance(); uint currentWeek = weekCounter; // Calculate total mintable supply from exponential decay function // The decay function stops after week 234 while (remainingWeeksToMint > 0) { currentWeek++; // If current week is before supply decay we add initial supply to mintableSupply if (currentWeek < SUPPLY_DECAY_START) { totalAmount = totalAmount.add(INITIAL_WEEKLY_SUPPLY); remainingWeeksToMint--; } // if current week before supply decay ends we add the new supply for the week else if (currentWeek <= SUPPLY_DECAY_END) { // diff between current week and (supply decay start week - 1) uint decayCount = currentWeek.sub(SUPPLY_DECAY_START -1); totalAmount = totalAmount.add(tokenDecaySupplyForWeek(decayCount)); remainingWeeksToMint--; } // Terminal supply is calculated on the total supply of Synthetix including any new supply // We can compound the remaining week's supply at the fixed terminal rate else { uint totalSupply = ISynthetix(synthetixProxy).totalSupply(); uint currentTotalSupply = totalSupply.add(totalAmount); totalAmount = totalAmount.add(terminalInflationSupply(currentTotalSupply, remainingWeeksToMint)); remainingWeeksToMint = 0; } } return totalAmount; } /** * @return A unit amount of decaying inflationary supply from the INITIAL_WEEKLY_SUPPLY * @dev New token supply reduces by the decay rate each week calculated as supply = INITIAL_WEEKLY_SUPPLY * () */ function tokenDecaySupplyForWeek(uint counter) public pure returns (uint) { // Apply exponential decay function to number of weeks since // start of inflation smoothing to calculate diminishing supply for the week. uint effectiveDecay = (SafeDecimalMath.unit().sub(DECAY_RATE)).powDecimal(counter); uint supplyForWeek = INITIAL_WEEKLY_SUPPLY.multiplyDecimal(effectiveDecay); return supplyForWeek; } /** * @return A unit amount of terminal inflation supply * @dev Weekly compound rate based on number of weeks */ function terminalInflationSupply(uint totalSupply, uint numOfWeeks) public pure returns (uint) { // rate = (1 + weekly rate) ^ num of weeks uint effectiveCompoundRate = SafeDecimalMath.unit().add(TERMINAL_SUPPLY_RATE_ANNUAL.div(52)).powDecimal(numOfWeeks); // return Supply * (effectiveRate - 1) for extra supply to issue based on number of weeks return totalSupply.multiplyDecimal(effectiveCompoundRate.sub(SafeDecimalMath.unit())); } /** * @dev Take timeDiff in seconds (Dividend) and MINT_PERIOD_DURATION as (Divisor) * @return Calculate the numberOfWeeks since last mint rounded down to 1 week */ function weeksSinceLastIssuance() public view returns (uint) { // Get weeks since lastMintEvent // If lastMintEvent not set or 0, then start from inflation start date. uint timeDiff = lastMintEvent > 0 ? now.sub(lastMintEvent) : now.sub(INFLATION_START_DATE); return timeDiff.div(MINT_PERIOD_DURATION); } /** * @return boolean whether the MINT_PERIOD_DURATION (7 days) * has passed since the lastMintEvent. * */ function isMintable() public view returns (bool) { if (now - lastMintEvent > MINT_PERIOD_DURATION) { return true; } return false; } // ========== MUTATIVE FUNCTIONS ========== /** * @notice Record the mint event from Synthetix by incrementing the inflation * week counter for the number of weeks minted (probabaly always 1) * and store the time of the event. * @param supplyMinted the amount of SNX the total supply was inflated by. * */ function recordMintEvent(uint supplyMinted) external onlySynthetix returns (bool) { uint numberOfWeeksIssued = weeksSinceLastIssuance(); // add number of weeks minted to weekCounter weekCounter = weekCounter.add(numberOfWeeksIssued); // Update mint event to latest week issued (start date + number of weeks issued * seconds in week) // 1 day time buffer is added so inflation is minted after feePeriod closes lastMintEvent = INFLATION_START_DATE.add(weekCounter.mul(MINT_PERIOD_DURATION)).add(MINT_BUFFER); emit SupplyMinted(supplyMinted, numberOfWeeksIssued, lastMintEvent, now); return true; } /** * @notice Sets the reward amount of SNX for the caller of the public * function Synthetix.mint(). * This incentivises anyone to mint the inflationary supply and the mintr * Reward will be deducted from the inflationary supply and sent to the caller. * @param amount the amount of SNX to reward the minter. * */ function setMinterReward(uint amount) external onlyOwner { require(amount <= MAX_MINTER_REWARD, "Reward cannot exceed max minter reward"); minterReward = amount; emit MinterRewardUpdated(minterReward); } // ========== SETTERS ========== */ /** * @notice Set the SynthetixProxy should it ever change. * SupplySchedule requires Synthetix address as it has the authority * to record mint event. * */ function setSynthetixProxy(ISynthetix _synthetixProxy) external onlyOwner { require(_synthetixProxy != address(0), "Address cannot be 0"); synthetixProxy = _synthetixProxy; emit SynthetixProxyUpdated(synthetixProxy); } // ========== MODIFIERS ========== /** * @notice Only the Synthetix contract is authorised to call this function * */ modifier onlySynthetix() { require(msg.sender == address(Proxy(synthetixProxy).target()), "Only the synthetix contract can perform this action"); _; } /* ========== EVENTS ========== */ /** * @notice Emitted when the inflationary supply is minted * */ event SupplyMinted(uint supplyMinted, uint numberOfWeeksIssued, uint lastMintEvent, uint timestamp); /** * @notice Emitted when the SNX minter reward amount is updated * */ event MinterRewardUpdated(uint newRewardAmount); /** * @notice Emitted when setSynthetixProxy is called changing the Synthetix Proxy address * */ event SynthetixProxyUpdated(address newAddress); }
/** * @title SupplySchedule contract */
NatSpecMultiLine
recordMintEvent
function recordMintEvent(uint supplyMinted) external onlySynthetix returns (bool) { uint numberOfWeeksIssued = weeksSinceLastIssuance(); // add number of weeks minted to weekCounter weekCounter = weekCounter.add(numberOfWeeksIssued); // Update mint event to latest week issued (start date + number of weeks issued * seconds in week) // 1 day time buffer is added so inflation is minted after feePeriod closes lastMintEvent = INFLATION_START_DATE.add(weekCounter.mul(MINT_PERIOD_DURATION)).add(MINT_BUFFER); emit SupplyMinted(supplyMinted, numberOfWeeksIssued, lastMintEvent, now); return true; }
/** * @notice Record the mint event from Synthetix by incrementing the inflation * week counter for the number of weeks minted (probabaly always 1) * and store the time of the event. * @param supplyMinted the amount of SNX the total supply was inflated by. * */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 6491, 7190 ] }
12,288
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SupplySchedule
contract SupplySchedule is Owned { using SafeMath for uint; using SafeDecimalMath for uint; using Math for uint; // Time of the last inflation supply mint event uint public lastMintEvent; // Counter for number of weeks since the start of supply inflation uint public weekCounter; // The number of SNX rewarded to the caller of Synthetix.mint() uint public minterReward = 200 * SafeDecimalMath.unit(); // The initial weekly inflationary supply is 75m / 52 until the start of the decay rate. // 75e6 * SafeDecimalMath.unit() / 52 uint public constant INITIAL_WEEKLY_SUPPLY = 1442307692307692307692307; // Address of the SynthetixProxy for the onlySynthetix modifier address public synthetixProxy; // Max SNX rewards for minter uint public constant MAX_MINTER_REWARD = 200 * SafeDecimalMath.unit(); // How long each inflation period is before mint can be called uint public constant MINT_PERIOD_DURATION = 1 weeks; uint public constant INFLATION_START_DATE = 1551830400; // 2019-03-06T00:00:00+00:00 uint public constant MINT_BUFFER = 1 days; uint8 public constant SUPPLY_DECAY_START = 40; // Week 40 uint8 public constant SUPPLY_DECAY_END = 234; // Supply Decay ends on Week 234 (inclusive of Week 234 for a total of 195 weeks of inflation decay) // Weekly percentage decay of inflationary supply from the first 40 weeks of the 75% inflation rate uint public constant DECAY_RATE = 12500000000000000; // 1.25% weekly // Percentage growth of terminal supply per annum uint public constant TERMINAL_SUPPLY_RATE_ANNUAL = 25000000000000000; // 2.5% pa constructor( address _owner, uint _lastMintEvent, uint _currentWeek) Owned(_owner) public { lastMintEvent = _lastMintEvent; weekCounter = _currentWeek; } // ========== VIEWS ========== /** * @return The amount of SNX mintable for the inflationary supply */ function mintableSupply() external view returns (uint) { uint totalAmount; if (!isMintable()) { return totalAmount; } uint remainingWeeksToMint = weeksSinceLastIssuance(); uint currentWeek = weekCounter; // Calculate total mintable supply from exponential decay function // The decay function stops after week 234 while (remainingWeeksToMint > 0) { currentWeek++; // If current week is before supply decay we add initial supply to mintableSupply if (currentWeek < SUPPLY_DECAY_START) { totalAmount = totalAmount.add(INITIAL_WEEKLY_SUPPLY); remainingWeeksToMint--; } // if current week before supply decay ends we add the new supply for the week else if (currentWeek <= SUPPLY_DECAY_END) { // diff between current week and (supply decay start week - 1) uint decayCount = currentWeek.sub(SUPPLY_DECAY_START -1); totalAmount = totalAmount.add(tokenDecaySupplyForWeek(decayCount)); remainingWeeksToMint--; } // Terminal supply is calculated on the total supply of Synthetix including any new supply // We can compound the remaining week's supply at the fixed terminal rate else { uint totalSupply = ISynthetix(synthetixProxy).totalSupply(); uint currentTotalSupply = totalSupply.add(totalAmount); totalAmount = totalAmount.add(terminalInflationSupply(currentTotalSupply, remainingWeeksToMint)); remainingWeeksToMint = 0; } } return totalAmount; } /** * @return A unit amount of decaying inflationary supply from the INITIAL_WEEKLY_SUPPLY * @dev New token supply reduces by the decay rate each week calculated as supply = INITIAL_WEEKLY_SUPPLY * () */ function tokenDecaySupplyForWeek(uint counter) public pure returns (uint) { // Apply exponential decay function to number of weeks since // start of inflation smoothing to calculate diminishing supply for the week. uint effectiveDecay = (SafeDecimalMath.unit().sub(DECAY_RATE)).powDecimal(counter); uint supplyForWeek = INITIAL_WEEKLY_SUPPLY.multiplyDecimal(effectiveDecay); return supplyForWeek; } /** * @return A unit amount of terminal inflation supply * @dev Weekly compound rate based on number of weeks */ function terminalInflationSupply(uint totalSupply, uint numOfWeeks) public pure returns (uint) { // rate = (1 + weekly rate) ^ num of weeks uint effectiveCompoundRate = SafeDecimalMath.unit().add(TERMINAL_SUPPLY_RATE_ANNUAL.div(52)).powDecimal(numOfWeeks); // return Supply * (effectiveRate - 1) for extra supply to issue based on number of weeks return totalSupply.multiplyDecimal(effectiveCompoundRate.sub(SafeDecimalMath.unit())); } /** * @dev Take timeDiff in seconds (Dividend) and MINT_PERIOD_DURATION as (Divisor) * @return Calculate the numberOfWeeks since last mint rounded down to 1 week */ function weeksSinceLastIssuance() public view returns (uint) { // Get weeks since lastMintEvent // If lastMintEvent not set or 0, then start from inflation start date. uint timeDiff = lastMintEvent > 0 ? now.sub(lastMintEvent) : now.sub(INFLATION_START_DATE); return timeDiff.div(MINT_PERIOD_DURATION); } /** * @return boolean whether the MINT_PERIOD_DURATION (7 days) * has passed since the lastMintEvent. * */ function isMintable() public view returns (bool) { if (now - lastMintEvent > MINT_PERIOD_DURATION) { return true; } return false; } // ========== MUTATIVE FUNCTIONS ========== /** * @notice Record the mint event from Synthetix by incrementing the inflation * week counter for the number of weeks minted (probabaly always 1) * and store the time of the event. * @param supplyMinted the amount of SNX the total supply was inflated by. * */ function recordMintEvent(uint supplyMinted) external onlySynthetix returns (bool) { uint numberOfWeeksIssued = weeksSinceLastIssuance(); // add number of weeks minted to weekCounter weekCounter = weekCounter.add(numberOfWeeksIssued); // Update mint event to latest week issued (start date + number of weeks issued * seconds in week) // 1 day time buffer is added so inflation is minted after feePeriod closes lastMintEvent = INFLATION_START_DATE.add(weekCounter.mul(MINT_PERIOD_DURATION)).add(MINT_BUFFER); emit SupplyMinted(supplyMinted, numberOfWeeksIssued, lastMintEvent, now); return true; } /** * @notice Sets the reward amount of SNX for the caller of the public * function Synthetix.mint(). * This incentivises anyone to mint the inflationary supply and the mintr * Reward will be deducted from the inflationary supply and sent to the caller. * @param amount the amount of SNX to reward the minter. * */ function setMinterReward(uint amount) external onlyOwner { require(amount <= MAX_MINTER_REWARD, "Reward cannot exceed max minter reward"); minterReward = amount; emit MinterRewardUpdated(minterReward); } // ========== SETTERS ========== */ /** * @notice Set the SynthetixProxy should it ever change. * SupplySchedule requires Synthetix address as it has the authority * to record mint event. * */ function setSynthetixProxy(ISynthetix _synthetixProxy) external onlyOwner { require(_synthetixProxy != address(0), "Address cannot be 0"); synthetixProxy = _synthetixProxy; emit SynthetixProxyUpdated(synthetixProxy); } // ========== MODIFIERS ========== /** * @notice Only the Synthetix contract is authorised to call this function * */ modifier onlySynthetix() { require(msg.sender == address(Proxy(synthetixProxy).target()), "Only the synthetix contract can perform this action"); _; } /* ========== EVENTS ========== */ /** * @notice Emitted when the inflationary supply is minted * */ event SupplyMinted(uint supplyMinted, uint numberOfWeeksIssued, uint lastMintEvent, uint timestamp); /** * @notice Emitted when the SNX minter reward amount is updated * */ event MinterRewardUpdated(uint newRewardAmount); /** * @notice Emitted when setSynthetixProxy is called changing the Synthetix Proxy address * */ event SynthetixProxyUpdated(address newAddress); }
/** * @title SupplySchedule contract */
NatSpecMultiLine
setMinterReward
function setMinterReward(uint amount) external onlyOwner { require(amount <= MAX_MINTER_REWARD, "Reward cannot exceed max minter reward"); minterReward = amount; emit MinterRewardUpdated(minterReward); }
/** * @notice Sets the reward amount of SNX for the caller of the public * function Synthetix.mint(). * This incentivises anyone to mint the inflationary supply and the mintr * Reward will be deducted from the inflationary supply and sent to the caller. * @param amount the amount of SNX to reward the minter. * */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 7544, 7799 ] }
12,289
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
SupplySchedule
contract SupplySchedule is Owned { using SafeMath for uint; using SafeDecimalMath for uint; using Math for uint; // Time of the last inflation supply mint event uint public lastMintEvent; // Counter for number of weeks since the start of supply inflation uint public weekCounter; // The number of SNX rewarded to the caller of Synthetix.mint() uint public minterReward = 200 * SafeDecimalMath.unit(); // The initial weekly inflationary supply is 75m / 52 until the start of the decay rate. // 75e6 * SafeDecimalMath.unit() / 52 uint public constant INITIAL_WEEKLY_SUPPLY = 1442307692307692307692307; // Address of the SynthetixProxy for the onlySynthetix modifier address public synthetixProxy; // Max SNX rewards for minter uint public constant MAX_MINTER_REWARD = 200 * SafeDecimalMath.unit(); // How long each inflation period is before mint can be called uint public constant MINT_PERIOD_DURATION = 1 weeks; uint public constant INFLATION_START_DATE = 1551830400; // 2019-03-06T00:00:00+00:00 uint public constant MINT_BUFFER = 1 days; uint8 public constant SUPPLY_DECAY_START = 40; // Week 40 uint8 public constant SUPPLY_DECAY_END = 234; // Supply Decay ends on Week 234 (inclusive of Week 234 for a total of 195 weeks of inflation decay) // Weekly percentage decay of inflationary supply from the first 40 weeks of the 75% inflation rate uint public constant DECAY_RATE = 12500000000000000; // 1.25% weekly // Percentage growth of terminal supply per annum uint public constant TERMINAL_SUPPLY_RATE_ANNUAL = 25000000000000000; // 2.5% pa constructor( address _owner, uint _lastMintEvent, uint _currentWeek) Owned(_owner) public { lastMintEvent = _lastMintEvent; weekCounter = _currentWeek; } // ========== VIEWS ========== /** * @return The amount of SNX mintable for the inflationary supply */ function mintableSupply() external view returns (uint) { uint totalAmount; if (!isMintable()) { return totalAmount; } uint remainingWeeksToMint = weeksSinceLastIssuance(); uint currentWeek = weekCounter; // Calculate total mintable supply from exponential decay function // The decay function stops after week 234 while (remainingWeeksToMint > 0) { currentWeek++; // If current week is before supply decay we add initial supply to mintableSupply if (currentWeek < SUPPLY_DECAY_START) { totalAmount = totalAmount.add(INITIAL_WEEKLY_SUPPLY); remainingWeeksToMint--; } // if current week before supply decay ends we add the new supply for the week else if (currentWeek <= SUPPLY_DECAY_END) { // diff between current week and (supply decay start week - 1) uint decayCount = currentWeek.sub(SUPPLY_DECAY_START -1); totalAmount = totalAmount.add(tokenDecaySupplyForWeek(decayCount)); remainingWeeksToMint--; } // Terminal supply is calculated on the total supply of Synthetix including any new supply // We can compound the remaining week's supply at the fixed terminal rate else { uint totalSupply = ISynthetix(synthetixProxy).totalSupply(); uint currentTotalSupply = totalSupply.add(totalAmount); totalAmount = totalAmount.add(terminalInflationSupply(currentTotalSupply, remainingWeeksToMint)); remainingWeeksToMint = 0; } } return totalAmount; } /** * @return A unit amount of decaying inflationary supply from the INITIAL_WEEKLY_SUPPLY * @dev New token supply reduces by the decay rate each week calculated as supply = INITIAL_WEEKLY_SUPPLY * () */ function tokenDecaySupplyForWeek(uint counter) public pure returns (uint) { // Apply exponential decay function to number of weeks since // start of inflation smoothing to calculate diminishing supply for the week. uint effectiveDecay = (SafeDecimalMath.unit().sub(DECAY_RATE)).powDecimal(counter); uint supplyForWeek = INITIAL_WEEKLY_SUPPLY.multiplyDecimal(effectiveDecay); return supplyForWeek; } /** * @return A unit amount of terminal inflation supply * @dev Weekly compound rate based on number of weeks */ function terminalInflationSupply(uint totalSupply, uint numOfWeeks) public pure returns (uint) { // rate = (1 + weekly rate) ^ num of weeks uint effectiveCompoundRate = SafeDecimalMath.unit().add(TERMINAL_SUPPLY_RATE_ANNUAL.div(52)).powDecimal(numOfWeeks); // return Supply * (effectiveRate - 1) for extra supply to issue based on number of weeks return totalSupply.multiplyDecimal(effectiveCompoundRate.sub(SafeDecimalMath.unit())); } /** * @dev Take timeDiff in seconds (Dividend) and MINT_PERIOD_DURATION as (Divisor) * @return Calculate the numberOfWeeks since last mint rounded down to 1 week */ function weeksSinceLastIssuance() public view returns (uint) { // Get weeks since lastMintEvent // If lastMintEvent not set or 0, then start from inflation start date. uint timeDiff = lastMintEvent > 0 ? now.sub(lastMintEvent) : now.sub(INFLATION_START_DATE); return timeDiff.div(MINT_PERIOD_DURATION); } /** * @return boolean whether the MINT_PERIOD_DURATION (7 days) * has passed since the lastMintEvent. * */ function isMintable() public view returns (bool) { if (now - lastMintEvent > MINT_PERIOD_DURATION) { return true; } return false; } // ========== MUTATIVE FUNCTIONS ========== /** * @notice Record the mint event from Synthetix by incrementing the inflation * week counter for the number of weeks minted (probabaly always 1) * and store the time of the event. * @param supplyMinted the amount of SNX the total supply was inflated by. * */ function recordMintEvent(uint supplyMinted) external onlySynthetix returns (bool) { uint numberOfWeeksIssued = weeksSinceLastIssuance(); // add number of weeks minted to weekCounter weekCounter = weekCounter.add(numberOfWeeksIssued); // Update mint event to latest week issued (start date + number of weeks issued * seconds in week) // 1 day time buffer is added so inflation is minted after feePeriod closes lastMintEvent = INFLATION_START_DATE.add(weekCounter.mul(MINT_PERIOD_DURATION)).add(MINT_BUFFER); emit SupplyMinted(supplyMinted, numberOfWeeksIssued, lastMintEvent, now); return true; } /** * @notice Sets the reward amount of SNX for the caller of the public * function Synthetix.mint(). * This incentivises anyone to mint the inflationary supply and the mintr * Reward will be deducted from the inflationary supply and sent to the caller. * @param amount the amount of SNX to reward the minter. * */ function setMinterReward(uint amount) external onlyOwner { require(amount <= MAX_MINTER_REWARD, "Reward cannot exceed max minter reward"); minterReward = amount; emit MinterRewardUpdated(minterReward); } // ========== SETTERS ========== */ /** * @notice Set the SynthetixProxy should it ever change. * SupplySchedule requires Synthetix address as it has the authority * to record mint event. * */ function setSynthetixProxy(ISynthetix _synthetixProxy) external onlyOwner { require(_synthetixProxy != address(0), "Address cannot be 0"); synthetixProxy = _synthetixProxy; emit SynthetixProxyUpdated(synthetixProxy); } // ========== MODIFIERS ========== /** * @notice Only the Synthetix contract is authorised to call this function * */ modifier onlySynthetix() { require(msg.sender == address(Proxy(synthetixProxy).target()), "Only the synthetix contract can perform this action"); _; } /* ========== EVENTS ========== */ /** * @notice Emitted when the inflationary supply is minted * */ event SupplyMinted(uint supplyMinted, uint numberOfWeeksIssued, uint lastMintEvent, uint timestamp); /** * @notice Emitted when the SNX minter reward amount is updated * */ event MinterRewardUpdated(uint newRewardAmount); /** * @notice Emitted when setSynthetixProxy is called changing the Synthetix Proxy address * */ event SynthetixProxyUpdated(address newAddress); }
/** * @title SupplySchedule contract */
NatSpecMultiLine
setSynthetixProxy
function setSynthetixProxy(ISynthetix _synthetixProxy) external onlyOwner { require(_synthetixProxy != address(0), "Address cannot be 0"); synthetixProxy = _synthetixProxy; emit SynthetixProxyUpdated(synthetixProxy); }
/** * @notice Set the SynthetixProxy should it ever change. * SupplySchedule requires Synthetix address as it has the authority * to record mint event. * */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 8023, 8293 ] }
12,290
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExchangeRates
contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => RateAndUpdatedTime) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of configure aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we'll declare that clearly. bytes32[5] public xdrParticipants; // A conveience mapping for checking if a rate is a XDR participant mapping(bytes32 => bool) public isXDRParticipant; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won't change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes32("sUSD"), bytes32("sAUD"), bytes32("sCHF"), bytes32("sEUR"), bytes32("sGBP") ]; // Mapping the XDR participants is cheaper than looping the xdrParticipants array to check if they exist isXDRParticipant[bytes32("sUSD")] = true; isXDRParticipant[bytes32("sAUD")] = true; isXDRParticipant[bytes32("sCHF")] = true; isXDRParticipant[bytes32("sEUR")] = true; isXDRParticipant[bytes32("sGBP")] = true; internalUpdateRates(_currencyKeys, _newRates, now); } function getRateAndUpdatedTime(bytes32 code) internal view returns (RateAndUpdatedTime) { if (code == "XDR") { // The XDR rate is the sum of the underlying XDR participant rates, and the latest // timestamp from those rates uint total = 0; uint lastUpdated = 0; for (uint i = 0; i < xdrParticipants.length; i++) { RateAndUpdatedTime memory xdrEntry = getRateAndUpdatedTime(xdrParticipants[i]); total = total.add(xdrEntry.rate); if (xdrEntry.time > lastUpdated) { lastUpdated = xdrEntry.time; } } return RateAndUpdatedTime({ rate: uint216(total), time: uint40(lastUpdated) }); } else if (aggregators[code] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[code].latestAnswer() * 1e10), time: uint40(aggregators[code].latestTimestamp()) }); } else { return _rates[code]; } } /** * @notice Retrieves the exchange rate (sUSD per unit) for a given currency key */ function rates(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).rate; } /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } function _setRate(bytes32 code, uint256 rate, uint256 time) internal { _rates[code] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(rates(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey THe currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } /* ========== VIEWS ========== */ /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) public view returns (uint) { return rates(currencyKey); } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = rates(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) public view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
/** * @title The repository for exchange rates */
NatSpecMultiLine
rates
function rates(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).rate; }
/** * @notice Retrieves the exchange rate (sUSD per unit) for a given currency key */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 5024, 5142 ] }
12,291
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExchangeRates
contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => RateAndUpdatedTime) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of configure aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we'll declare that clearly. bytes32[5] public xdrParticipants; // A conveience mapping for checking if a rate is a XDR participant mapping(bytes32 => bool) public isXDRParticipant; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won't change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes32("sUSD"), bytes32("sAUD"), bytes32("sCHF"), bytes32("sEUR"), bytes32("sGBP") ]; // Mapping the XDR participants is cheaper than looping the xdrParticipants array to check if they exist isXDRParticipant[bytes32("sUSD")] = true; isXDRParticipant[bytes32("sAUD")] = true; isXDRParticipant[bytes32("sCHF")] = true; isXDRParticipant[bytes32("sEUR")] = true; isXDRParticipant[bytes32("sGBP")] = true; internalUpdateRates(_currencyKeys, _newRates, now); } function getRateAndUpdatedTime(bytes32 code) internal view returns (RateAndUpdatedTime) { if (code == "XDR") { // The XDR rate is the sum of the underlying XDR participant rates, and the latest // timestamp from those rates uint total = 0; uint lastUpdated = 0; for (uint i = 0; i < xdrParticipants.length; i++) { RateAndUpdatedTime memory xdrEntry = getRateAndUpdatedTime(xdrParticipants[i]); total = total.add(xdrEntry.rate); if (xdrEntry.time > lastUpdated) { lastUpdated = xdrEntry.time; } } return RateAndUpdatedTime({ rate: uint216(total), time: uint40(lastUpdated) }); } else if (aggregators[code] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[code].latestAnswer() * 1e10), time: uint40(aggregators[code].latestTimestamp()) }); } else { return _rates[code]; } } /** * @notice Retrieves the exchange rate (sUSD per unit) for a given currency key */ function rates(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).rate; } /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } function _setRate(bytes32 code, uint256 rate, uint256 time) internal { _rates[code] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(rates(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey THe currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } /* ========== VIEWS ========== */ /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) public view returns (uint) { return rates(currencyKey); } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = rates(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) public view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
/** * @title The repository for exchange rates */
NatSpecMultiLine
lastRateUpdateTimes
function lastRateUpdateTimes(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).time; }
/** * @notice Retrieves the timestamp the given rate was last updated. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 5232, 5364 ] }
12,292
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExchangeRates
contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => RateAndUpdatedTime) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of configure aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we'll declare that clearly. bytes32[5] public xdrParticipants; // A conveience mapping for checking if a rate is a XDR participant mapping(bytes32 => bool) public isXDRParticipant; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won't change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes32("sUSD"), bytes32("sAUD"), bytes32("sCHF"), bytes32("sEUR"), bytes32("sGBP") ]; // Mapping the XDR participants is cheaper than looping the xdrParticipants array to check if they exist isXDRParticipant[bytes32("sUSD")] = true; isXDRParticipant[bytes32("sAUD")] = true; isXDRParticipant[bytes32("sCHF")] = true; isXDRParticipant[bytes32("sEUR")] = true; isXDRParticipant[bytes32("sGBP")] = true; internalUpdateRates(_currencyKeys, _newRates, now); } function getRateAndUpdatedTime(bytes32 code) internal view returns (RateAndUpdatedTime) { if (code == "XDR") { // The XDR rate is the sum of the underlying XDR participant rates, and the latest // timestamp from those rates uint total = 0; uint lastUpdated = 0; for (uint i = 0; i < xdrParticipants.length; i++) { RateAndUpdatedTime memory xdrEntry = getRateAndUpdatedTime(xdrParticipants[i]); total = total.add(xdrEntry.rate); if (xdrEntry.time > lastUpdated) { lastUpdated = xdrEntry.time; } } return RateAndUpdatedTime({ rate: uint216(total), time: uint40(lastUpdated) }); } else if (aggregators[code] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[code].latestAnswer() * 1e10), time: uint40(aggregators[code].latestTimestamp()) }); } else { return _rates[code]; } } /** * @notice Retrieves the exchange rate (sUSD per unit) for a given currency key */ function rates(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).rate; } /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } function _setRate(bytes32 code, uint256 rate, uint256 time) internal { _rates[code] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(rates(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey THe currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } /* ========== VIEWS ========== */ /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) public view returns (uint) { return rates(currencyKey); } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = rates(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) public view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
/** * @title The repository for exchange rates */
NatSpecMultiLine
lastRateUpdateTimesForCurrencies
function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; }
/** * @notice Retrieve the last update time for a list of currencies */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 5452, 5831 ] }
12,293
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExchangeRates
contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => RateAndUpdatedTime) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of configure aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we'll declare that clearly. bytes32[5] public xdrParticipants; // A conveience mapping for checking if a rate is a XDR participant mapping(bytes32 => bool) public isXDRParticipant; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won't change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes32("sUSD"), bytes32("sAUD"), bytes32("sCHF"), bytes32("sEUR"), bytes32("sGBP") ]; // Mapping the XDR participants is cheaper than looping the xdrParticipants array to check if they exist isXDRParticipant[bytes32("sUSD")] = true; isXDRParticipant[bytes32("sAUD")] = true; isXDRParticipant[bytes32("sCHF")] = true; isXDRParticipant[bytes32("sEUR")] = true; isXDRParticipant[bytes32("sGBP")] = true; internalUpdateRates(_currencyKeys, _newRates, now); } function getRateAndUpdatedTime(bytes32 code) internal view returns (RateAndUpdatedTime) { if (code == "XDR") { // The XDR rate is the sum of the underlying XDR participant rates, and the latest // timestamp from those rates uint total = 0; uint lastUpdated = 0; for (uint i = 0; i < xdrParticipants.length; i++) { RateAndUpdatedTime memory xdrEntry = getRateAndUpdatedTime(xdrParticipants[i]); total = total.add(xdrEntry.rate); if (xdrEntry.time > lastUpdated) { lastUpdated = xdrEntry.time; } } return RateAndUpdatedTime({ rate: uint216(total), time: uint40(lastUpdated) }); } else if (aggregators[code] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[code].latestAnswer() * 1e10), time: uint40(aggregators[code].latestTimestamp()) }); } else { return _rates[code]; } } /** * @notice Retrieves the exchange rate (sUSD per unit) for a given currency key */ function rates(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).rate; } /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } function _setRate(bytes32 code, uint256 rate, uint256 time) internal { _rates[code] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(rates(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey THe currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } /* ========== VIEWS ========== */ /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) public view returns (uint) { return rates(currencyKey); } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = rates(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) public view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
/** * @title The repository for exchange rates */
NatSpecMultiLine
updateRates
function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); }
/** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 6686, 6906 ] }
12,294
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExchangeRates
contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => RateAndUpdatedTime) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of configure aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we'll declare that clearly. bytes32[5] public xdrParticipants; // A conveience mapping for checking if a rate is a XDR participant mapping(bytes32 => bool) public isXDRParticipant; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won't change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes32("sUSD"), bytes32("sAUD"), bytes32("sCHF"), bytes32("sEUR"), bytes32("sGBP") ]; // Mapping the XDR participants is cheaper than looping the xdrParticipants array to check if they exist isXDRParticipant[bytes32("sUSD")] = true; isXDRParticipant[bytes32("sAUD")] = true; isXDRParticipant[bytes32("sCHF")] = true; isXDRParticipant[bytes32("sEUR")] = true; isXDRParticipant[bytes32("sGBP")] = true; internalUpdateRates(_currencyKeys, _newRates, now); } function getRateAndUpdatedTime(bytes32 code) internal view returns (RateAndUpdatedTime) { if (code == "XDR") { // The XDR rate is the sum of the underlying XDR participant rates, and the latest // timestamp from those rates uint total = 0; uint lastUpdated = 0; for (uint i = 0; i < xdrParticipants.length; i++) { RateAndUpdatedTime memory xdrEntry = getRateAndUpdatedTime(xdrParticipants[i]); total = total.add(xdrEntry.rate); if (xdrEntry.time > lastUpdated) { lastUpdated = xdrEntry.time; } } return RateAndUpdatedTime({ rate: uint216(total), time: uint40(lastUpdated) }); } else if (aggregators[code] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[code].latestAnswer() * 1e10), time: uint40(aggregators[code].latestTimestamp()) }); } else { return _rates[code]; } } /** * @notice Retrieves the exchange rate (sUSD per unit) for a given currency key */ function rates(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).rate; } /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } function _setRate(bytes32 code, uint256 rate, uint256 time) internal { _rates[code] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(rates(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey THe currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } /* ========== VIEWS ========== */ /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) public view returns (uint) { return rates(currencyKey); } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = rates(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) public view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
/** * @title The repository for exchange rates */
NatSpecMultiLine
internalUpdateRates
function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; }
/** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 7543, 8933 ] }
12,295
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExchangeRates
contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => RateAndUpdatedTime) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of configure aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we'll declare that clearly. bytes32[5] public xdrParticipants; // A conveience mapping for checking if a rate is a XDR participant mapping(bytes32 => bool) public isXDRParticipant; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won't change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes32("sUSD"), bytes32("sAUD"), bytes32("sCHF"), bytes32("sEUR"), bytes32("sGBP") ]; // Mapping the XDR participants is cheaper than looping the xdrParticipants array to check if they exist isXDRParticipant[bytes32("sUSD")] = true; isXDRParticipant[bytes32("sAUD")] = true; isXDRParticipant[bytes32("sCHF")] = true; isXDRParticipant[bytes32("sEUR")] = true; isXDRParticipant[bytes32("sGBP")] = true; internalUpdateRates(_currencyKeys, _newRates, now); } function getRateAndUpdatedTime(bytes32 code) internal view returns (RateAndUpdatedTime) { if (code == "XDR") { // The XDR rate is the sum of the underlying XDR participant rates, and the latest // timestamp from those rates uint total = 0; uint lastUpdated = 0; for (uint i = 0; i < xdrParticipants.length; i++) { RateAndUpdatedTime memory xdrEntry = getRateAndUpdatedTime(xdrParticipants[i]); total = total.add(xdrEntry.rate); if (xdrEntry.time > lastUpdated) { lastUpdated = xdrEntry.time; } } return RateAndUpdatedTime({ rate: uint216(total), time: uint40(lastUpdated) }); } else if (aggregators[code] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[code].latestAnswer() * 1e10), time: uint40(aggregators[code].latestTimestamp()) }); } else { return _rates[code]; } } /** * @notice Retrieves the exchange rate (sUSD per unit) for a given currency key */ function rates(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).rate; } /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } function _setRate(bytes32 code, uint256 rate, uint256 time) internal { _rates[code] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(rates(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey THe currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } /* ========== VIEWS ========== */ /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) public view returns (uint) { return rates(currencyKey); } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = rates(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) public view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
/** * @title The repository for exchange rates */
NatSpecMultiLine
rateOrInverted
function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; }
/** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 10221, 11784 ] }
12,296
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExchangeRates
contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => RateAndUpdatedTime) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of configure aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we'll declare that clearly. bytes32[5] public xdrParticipants; // A conveience mapping for checking if a rate is a XDR participant mapping(bytes32 => bool) public isXDRParticipant; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won't change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes32("sUSD"), bytes32("sAUD"), bytes32("sCHF"), bytes32("sEUR"), bytes32("sGBP") ]; // Mapping the XDR participants is cheaper than looping the xdrParticipants array to check if they exist isXDRParticipant[bytes32("sUSD")] = true; isXDRParticipant[bytes32("sAUD")] = true; isXDRParticipant[bytes32("sCHF")] = true; isXDRParticipant[bytes32("sEUR")] = true; isXDRParticipant[bytes32("sGBP")] = true; internalUpdateRates(_currencyKeys, _newRates, now); } function getRateAndUpdatedTime(bytes32 code) internal view returns (RateAndUpdatedTime) { if (code == "XDR") { // The XDR rate is the sum of the underlying XDR participant rates, and the latest // timestamp from those rates uint total = 0; uint lastUpdated = 0; for (uint i = 0; i < xdrParticipants.length; i++) { RateAndUpdatedTime memory xdrEntry = getRateAndUpdatedTime(xdrParticipants[i]); total = total.add(xdrEntry.rate); if (xdrEntry.time > lastUpdated) { lastUpdated = xdrEntry.time; } } return RateAndUpdatedTime({ rate: uint216(total), time: uint40(lastUpdated) }); } else if (aggregators[code] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[code].latestAnswer() * 1e10), time: uint40(aggregators[code].latestTimestamp()) }); } else { return _rates[code]; } } /** * @notice Retrieves the exchange rate (sUSD per unit) for a given currency key */ function rates(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).rate; } /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } function _setRate(bytes32 code, uint256 rate, uint256 time) internal { _rates[code] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(rates(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey THe currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } /* ========== VIEWS ========== */ /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) public view returns (uint) { return rates(currencyKey); } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = rates(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) public view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
/** * @title The repository for exchange rates */
NatSpecMultiLine
deleteRate
function deleteRate(bytes32 currencyKey) external onlyOracle { require(rates(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey]; emit RateDeleted(currencyKey); }
/** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 11929, 12155 ] }
12,297
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExchangeRates
contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => RateAndUpdatedTime) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of configure aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we'll declare that clearly. bytes32[5] public xdrParticipants; // A conveience mapping for checking if a rate is a XDR participant mapping(bytes32 => bool) public isXDRParticipant; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won't change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes32("sUSD"), bytes32("sAUD"), bytes32("sCHF"), bytes32("sEUR"), bytes32("sGBP") ]; // Mapping the XDR participants is cheaper than looping the xdrParticipants array to check if they exist isXDRParticipant[bytes32("sUSD")] = true; isXDRParticipant[bytes32("sAUD")] = true; isXDRParticipant[bytes32("sCHF")] = true; isXDRParticipant[bytes32("sEUR")] = true; isXDRParticipant[bytes32("sGBP")] = true; internalUpdateRates(_currencyKeys, _newRates, now); } function getRateAndUpdatedTime(bytes32 code) internal view returns (RateAndUpdatedTime) { if (code == "XDR") { // The XDR rate is the sum of the underlying XDR participant rates, and the latest // timestamp from those rates uint total = 0; uint lastUpdated = 0; for (uint i = 0; i < xdrParticipants.length; i++) { RateAndUpdatedTime memory xdrEntry = getRateAndUpdatedTime(xdrParticipants[i]); total = total.add(xdrEntry.rate); if (xdrEntry.time > lastUpdated) { lastUpdated = xdrEntry.time; } } return RateAndUpdatedTime({ rate: uint216(total), time: uint40(lastUpdated) }); } else if (aggregators[code] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[code].latestAnswer() * 1e10), time: uint40(aggregators[code].latestTimestamp()) }); } else { return _rates[code]; } } /** * @notice Retrieves the exchange rate (sUSD per unit) for a given currency key */ function rates(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).rate; } /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } function _setRate(bytes32 code, uint256 rate, uint256 time) internal { _rates[code] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(rates(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey THe currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } /* ========== VIEWS ========== */ /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) public view returns (uint) { return rates(currencyKey); } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = rates(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) public view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
/** * @title The repository for exchange rates */
NatSpecMultiLine
setOracle
function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); }
/** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 12298, 12446 ] }
12,298
Synthetix
Synthetix.sol
0x7cb89c509001d25da9938999abfea6740212e5f0
Solidity
ExchangeRates
contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; struct RateAndUpdatedTime { uint216 rate; uint40 time; } // Exchange rates and update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes32 => RateAndUpdatedTime) private _rates; // The address of the oracle which pushes rate updates to this contract address public oracle; // Decentralized oracle networks that feed into pricing aggregators mapping(bytes32 => AggregatorInterface) public aggregators; // List of configure aggregator keys for convenient iteration bytes32[] public aggregatorKeys; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we'll declare that clearly. bytes32[5] public xdrParticipants; // A conveience mapping for checking if a rate is a XDR participant mapping(bytes32 => bool) public isXDRParticipant; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes32 => InversePricing) public inversePricing; bytes32[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes32[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. _setRate("sUSD", SafeDecimalMath.unit(), now); // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won't change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes32("sUSD"), bytes32("sAUD"), bytes32("sCHF"), bytes32("sEUR"), bytes32("sGBP") ]; // Mapping the XDR participants is cheaper than looping the xdrParticipants array to check if they exist isXDRParticipant[bytes32("sUSD")] = true; isXDRParticipant[bytes32("sAUD")] = true; isXDRParticipant[bytes32("sCHF")] = true; isXDRParticipant[bytes32("sEUR")] = true; isXDRParticipant[bytes32("sGBP")] = true; internalUpdateRates(_currencyKeys, _newRates, now); } function getRateAndUpdatedTime(bytes32 code) internal view returns (RateAndUpdatedTime) { if (code == "XDR") { // The XDR rate is the sum of the underlying XDR participant rates, and the latest // timestamp from those rates uint total = 0; uint lastUpdated = 0; for (uint i = 0; i < xdrParticipants.length; i++) { RateAndUpdatedTime memory xdrEntry = getRateAndUpdatedTime(xdrParticipants[i]); total = total.add(xdrEntry.rate); if (xdrEntry.time > lastUpdated) { lastUpdated = xdrEntry.time; } } return RateAndUpdatedTime({ rate: uint216(total), time: uint40(lastUpdated) }); } else if (aggregators[code] != address(0)) { return RateAndUpdatedTime({ rate: uint216(aggregators[code].latestAnswer() * 1e10), time: uint40(aggregators[code].latestTimestamp()) }); } else { return _rates[code]; } } /** * @notice Retrieves the exchange rate (sUSD per unit) for a given currency key */ function rates(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).rate; } /** * @notice Retrieves the timestamp the given rate was last updated. */ function lastRateUpdateTimes(bytes32 code) public view returns(uint256) { return getRateAndUpdatedTime(code).time; } /** * @notice Retrieve the last update time for a list of currencies */ function lastRateUpdateTimesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes(currencyKeys[i]); } return lastUpdateTimes; } function _setRate(bytes32 code, uint256 rate, uint256 time) internal { _rates[code] = RateAndUpdatedTime({ rate: uint216(rate), time: uint40(time) }); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes32[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { bytes32 currencyKey = currencyKeys[i]; // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKey != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes(currencyKey)) { continue; } newRates[i] = rateOrInverted(currencyKey, newRates[i]); // Ok, go ahead with the update. _setRate(currencyKey, newRates[i], timeSent); } emit RatesUpdated(currencyKeys, newRates); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * * Inverted rates are ones that take a regular rate, perform a simple calculation (double entryPrice and * subtract the rate) on them and if the result of the calculation is over or under predefined limits, it freezes the * rate at that limit, preventing any future rate updates. * * For example, if we have an inverted rate iBTC with the following parameters set: * - entryPrice of 200 * - upperLimit of 300 * - lower of 100 * * if this function is invoked with params iETH and 184 (or rather 184e18), * then the rate would be: 200 * 2 - 184 = 216. 100 < 216 < 200, so the rate would be 216, * and remain unfrozen. * * If this function is then invoked with params iETH and 301 (or rather 301e18), * then the rate would be: 200 * 2 - 301 = 99. 99 < 100, so the rate would be 100 and the * rate would become frozen, no longer accepting future price updates until the synth is unfrozen * by the owner function: setInversePricing(). * * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes32 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates(currencyKey); // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes32 currencyKey) external onlyOracle { require(rates(currencyKey) > 0, "Rate is zero"); delete _rates[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set an inverse price up for the currency key. * * An inverse price is one which has an entryPoint, an uppper and a lower limit. Each update, the * rate is calculated as double the entryPrice minus the current rate. If this calculation is * above or below the upper or lower limits respectively, then the rate is frozen, and no more * rate updates will be accepted. * * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen * @param freeze Whether or not to freeze this rate immediately. Note: no frozen event will be configured * @param freezeAtUpperLimit When the freeze flag is true, this flag indicates whether the rate * to freeze at is the upperLimit or lowerLimit.. */ function setInversePricing(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit, bool freeze, bool freezeAtUpperLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = freeze; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); // When indicating to freeze, we need to know the rate to freeze it at - either upper or lower // this is useful in situations where ExchangeRates is updated and there are existing inverted // rates already frozen in the current contract that need persisting across the upgrade if (freeze) { emit InversePriceFrozen(currencyKey); _setRate(currencyKey, freezeAtUpperLimit ? upperLimit : lowerLimit, now); } } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes32 currencyKey) external onlyOwner { require(inversePricing[currencyKey].entryPoint > 0, "No inverted price exists"); inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array bool wasRemoved = removeFromArray(currencyKey, invertedKeys); if (wasRemoved) { emit InversePriceConfigured(currencyKey, 0, 0, 0); } } /** * @notice Add a pricing aggregator for the given key. Note: existing aggregators may be overridden. * @param currencyKey The currency key to add an aggregator for */ function addAggregator(bytes32 currencyKey, address aggregatorAddress) external onlyOwner { AggregatorInterface aggregator = AggregatorInterface(aggregatorAddress); require(aggregator.latestTimestamp() >= 0, "Given Aggregator is invalid"); if (aggregators[currencyKey] == address(0)) { aggregatorKeys.push(currencyKey); } aggregators[currencyKey] = aggregator; emit AggregatorAdded(currencyKey, aggregator); } /** * @notice Remove a single value from an array by iterating through until it is found. * @param entry The entry to find * @param array The array to mutate * @return bool Whether or not the entry was found and removed */ function removeFromArray(bytes32 entry, bytes32[] storage array) internal returns (bool) { for (uint i = 0; i < array.length; i++) { if (array[i] == entry) { delete array[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. array[i] = array[array.length - 1]; // Decrease the size of the array by one. array.length--; return true; } } return false; } /** * @notice Remove a pricing aggregator for the given key * @param currencyKey THe currency key to remove an aggregator for */ function removeAggregator(bytes32 currencyKey) external onlyOwner { address aggregator = aggregators[currencyKey]; require(aggregator != address(0), "No aggregator exists for key"); delete aggregators[currencyKey]; bool wasRemoved = removeFromArray(currencyKey, aggregatorKeys); if (wasRemoved) { emit AggregatorRemoved(currencyKey, aggregator); } } /* ========== VIEWS ========== */ /** * @notice A function that lets you easily convert an amount in a source currency to an amount in the destination currency * @param sourceCurrencyKey The currency the amount is specified in * @param sourceAmount The source amount, specified in UNIT base * @param destinationCurrencyKey The destination currency */ function effectiveValue(bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { // If there's no change in the currency, then just return the amount they gave us if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; // Calculate the effective value by going from source -> USD -> destination return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes32 currencyKey) public view returns (uint) { return rates(currencyKey); } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes32[] currencyKeys) public view returns (uint[]) { uint[] memory _localRates = new uint[](currencyKeys.length); for (uint i = 0; i < currencyKeys.length; i++) { _localRates[i] = rates(currencyKeys[i]); } return _localRates; } /** * @notice Retrieve the rates and isAnyStale for a list of currencies */ function ratesAndStaleForCurrencies(bytes32[] currencyKeys) public view returns (uint[], bool) { uint[] memory _localRates = new uint[](currencyKeys.length); bool anyRateStale = false; uint period = rateStalePeriod; for (uint i = 0; i < currencyKeys.length; i++) { RateAndUpdatedTime memory rateAndUpdateTime = getRateAndUpdatedTime(currencyKeys[i]); _localRates[i] = uint256(rateAndUpdateTime.rate); if (!anyRateStale) { anyRateStale = (currencyKeys[i] != "sUSD" && uint256(rateAndUpdateTime.time).add(period) < now); } } return (_localRates, anyRateStale); } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes32 currencyKey) public view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes(currencyKey).add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes32 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes32[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes(currencyKeys[i]).add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier rateNotStale(bytes32 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes32[] currencyKeys, uint[] newRates); event RateDeleted(bytes32 currencyKey); event InversePriceConfigured(bytes32 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes32 currencyKey); event AggregatorAdded(bytes32 currencyKey, address aggregator); event AggregatorRemoved(bytes32 currencyKey, address aggregator); }
/** * @title The repository for exchange rates */
NatSpecMultiLine
setRateStalePeriod
function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); }
/** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */
NatSpecMultiLine
v0.4.25+commit.59dbf8f1
bzzr://7e5de7b2c8454afb4fecf2a46fa9ccc0e392fe2b302da0369358c02ba4f12d11
{ "func_code_index": [ 12574, 12751 ] }
12,299