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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
BeastInu | BeastInu.sol | 0x3ba7bd4ca6feba7553521f5ba763b512983a6202 | Solidity | SafeMathInt | library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
} | sub | function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
| /**
* @dev Subtracts two int256 variables and fails on overflow.
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | None | ipfs://6eb2f669bd1e34b27004ebb832721fbc1ba867dc6db9365cdc2c984628976573 | {
"func_code_index": [
984,
1165
]
} | 13,200 |
||
BeastInu | BeastInu.sol | 0x3ba7bd4ca6feba7553521f5ba763b512983a6202 | Solidity | SafeMathInt | library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
} | add | function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
| /**
* @dev Adds two int256 variables and fails on overflow.
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | None | ipfs://6eb2f669bd1e34b27004ebb832721fbc1ba867dc6db9365cdc2c984628976573 | {
"func_code_index": [
1248,
1429
]
} | 13,201 |
||
BeastInu | BeastInu.sol | 0x3ba7bd4ca6feba7553521f5ba763b512983a6202 | Solidity | SafeMathInt | library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
} | abs | function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
| /**
* @dev Converts to absolute value, and fails on overflow.
*/ | NatSpecMultiLine | v0.8.9+commit.e5eed63a | None | ipfs://6eb2f669bd1e34b27004ebb832721fbc1ba867dc6db9365cdc2c984628976573 | {
"func_code_index": [
1514,
1648
]
} | 13,202 |
||
BeastInu | BeastInu.sol | 0x3ba7bd4ca6feba7553521f5ba763b512983a6202 | Solidity | BeastInu | contract BeastInu is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 25; // 25 = .25%
bool public lpBurnEnabled = false;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 private sellTotalFees;
uint256 private sellMarketingFee;
uint256 private sellLiquidityFee;
uint256 private sellDevFee;
uint256 private tokensForMarketing;
uint256 private tokensForLiquidity;
uint256 private tokensForDev;
/******************/
// exlcude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("BeastInu", "BI") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 10;
uint256 _buyLiquidityFee = 3;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 18;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1 * 1e12 * 1e18;
maxTransactionAmount = totalSupply * 1 / 100; // 1% maxTransactionAmountTxn
maxWallet = totalSupply * 5 / 100; // 5% maxWallet
swapTokensAtAmount = totalSupply * 50 / 10000; // 0.50% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = address(owner()); // set as marketing wallet
devWallet = address(owner()); // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
deadAddress,
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success,) = address(devWallet).call{value: ethForDev}("");
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner {
require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes");
require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%");
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool){
lastLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualNukeLP();
return true;
}
} | enableTrading | function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
| // once enabled, can never be turned off | LineComment | v0.8.9+commit.e5eed63a | None | ipfs://6eb2f669bd1e34b27004ebb832721fbc1ba867dc6db9365cdc2c984628976573 | {
"func_code_index": [
4907,
5067
]
} | 13,203 |
||
BeastInu | BeastInu.sol | 0x3ba7bd4ca6feba7553521f5ba763b512983a6202 | Solidity | BeastInu | contract BeastInu is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 25; // 25 = .25%
bool public lpBurnEnabled = false;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 private sellTotalFees;
uint256 private sellMarketingFee;
uint256 private sellLiquidityFee;
uint256 private sellDevFee;
uint256 private tokensForMarketing;
uint256 private tokensForLiquidity;
uint256 private tokensForDev;
/******************/
// exlcude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("BeastInu", "BI") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 10;
uint256 _buyLiquidityFee = 3;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 18;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1 * 1e12 * 1e18;
maxTransactionAmount = totalSupply * 1 / 100; // 1% maxTransactionAmountTxn
maxWallet = totalSupply * 5 / 100; // 5% maxWallet
swapTokensAtAmount = totalSupply * 50 / 10000; // 0.50% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = address(owner()); // set as marketing wallet
devWallet = address(owner()); // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
deadAddress,
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success,) = address(devWallet).call{value: ethForDev}("");
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner {
require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes");
require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%");
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool){
lastLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualNukeLP();
return true;
}
} | removeLimits | function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
| // remove limits after token is stable | LineComment | v0.8.9+commit.e5eed63a | None | ipfs://6eb2f669bd1e34b27004ebb832721fbc1ba867dc6db9365cdc2c984628976573 | {
"func_code_index": [
5118,
5243
]
} | 13,204 |
||
BeastInu | BeastInu.sol | 0x3ba7bd4ca6feba7553521f5ba763b512983a6202 | Solidity | BeastInu | contract BeastInu is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 25; // 25 = .25%
bool public lpBurnEnabled = false;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 private sellTotalFees;
uint256 private sellMarketingFee;
uint256 private sellLiquidityFee;
uint256 private sellDevFee;
uint256 private tokensForMarketing;
uint256 private tokensForLiquidity;
uint256 private tokensForDev;
/******************/
// exlcude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("BeastInu", "BI") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 10;
uint256 _buyLiquidityFee = 3;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 18;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1 * 1e12 * 1e18;
maxTransactionAmount = totalSupply * 1 / 100; // 1% maxTransactionAmountTxn
maxWallet = totalSupply * 5 / 100; // 5% maxWallet
swapTokensAtAmount = totalSupply * 50 / 10000; // 0.50% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = address(owner()); // set as marketing wallet
devWallet = address(owner()); // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
deadAddress,
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success,) = address(devWallet).call{value: ethForDev}("");
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner {
require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes");
require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%");
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool){
lastLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualNukeLP();
return true;
}
} | disableTransferDelay | function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
| // disable Transfer delay - cannot be reenabled | LineComment | v0.8.9+commit.e5eed63a | None | ipfs://6eb2f669bd1e34b27004ebb832721fbc1ba867dc6db9365cdc2c984628976573 | {
"func_code_index": [
5303,
5442
]
} | 13,205 |
||
BeastInu | BeastInu.sol | 0x3ba7bd4ca6feba7553521f5ba763b512983a6202 | Solidity | BeastInu | contract BeastInu is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 25; // 25 = .25%
bool public lpBurnEnabled = false;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 private sellTotalFees;
uint256 private sellMarketingFee;
uint256 private sellLiquidityFee;
uint256 private sellDevFee;
uint256 private tokensForMarketing;
uint256 private tokensForLiquidity;
uint256 private tokensForDev;
/******************/
// exlcude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("BeastInu", "BI") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 10;
uint256 _buyLiquidityFee = 3;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 18;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1 * 1e12 * 1e18;
maxTransactionAmount = totalSupply * 1 / 100; // 1% maxTransactionAmountTxn
maxWallet = totalSupply * 5 / 100; // 5% maxWallet
swapTokensAtAmount = totalSupply * 50 / 10000; // 0.50% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = address(owner()); // set as marketing wallet
devWallet = address(owner()); // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
deadAddress,
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success,) = address(devWallet).call{value: ethForDev}("");
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner {
require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes");
require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%");
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool){
lastLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualNukeLP();
return true;
}
} | updateSwapTokensAtAmount | function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
| // change the minimum amount of tokens to sell from fees | LineComment | v0.8.9+commit.e5eed63a | None | ipfs://6eb2f669bd1e34b27004ebb832721fbc1ba867dc6db9365cdc2c984628976573 | {
"func_code_index": [
5512,
5903
]
} | 13,206 |
||
BeastInu | BeastInu.sol | 0x3ba7bd4ca6feba7553521f5ba763b512983a6202 | Solidity | BeastInu | contract BeastInu is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 25; // 25 = .25%
bool public lpBurnEnabled = false;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 private sellTotalFees;
uint256 private sellMarketingFee;
uint256 private sellLiquidityFee;
uint256 private sellDevFee;
uint256 private tokensForMarketing;
uint256 private tokensForLiquidity;
uint256 private tokensForDev;
/******************/
// exlcude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("BeastInu", "BI") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 10;
uint256 _buyLiquidityFee = 3;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 18;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1 * 1e12 * 1e18;
maxTransactionAmount = totalSupply * 1 / 100; // 1% maxTransactionAmountTxn
maxWallet = totalSupply * 5 / 100; // 5% maxWallet
swapTokensAtAmount = totalSupply * 50 / 10000; // 0.50% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = address(owner()); // set as marketing wallet
devWallet = address(owner()); // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
deadAddress,
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success,) = address(devWallet).call{value: ethForDev}("");
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner {
require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes");
require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%");
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool){
lastLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualNukeLP();
return true;
}
} | updateSwapEnabled | function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
| // only use to disable contract sales if absolutely necessary (emergency use only) | LineComment | v0.8.9+commit.e5eed63a | None | ipfs://6eb2f669bd1e34b27004ebb832721fbc1ba867dc6db9365cdc2c984628976573 | {
"func_code_index": [
6623,
6729
]
} | 13,207 |
||
FoundersContract | FoundersContract.sol | 0xce5e040786513702fa21a36f465d3be77c48930d | Solidity | FoundersContract | contract FoundersContract {
using SafeMath for uint256;
ROBOToken public token;
uint64 public freezOne = 1538352000;
uint64 public freezTwo = 1554076800;
mapping(address => uint256) public balances_freez_one;
mapping(address => uint256) public balances_freez_two;
address muhtov = 0x0134111c40D59E8476FfabB7D0B2ED6F86513E6e; //13 680 000
address scherbakov = 0x7B8E11cFE4E7aFec83276002dD246a71a4bD51EC;// 13 680 000
address sattarova = 0xFDA80FA2b42063F5c2Aa14C5da18cBBDfC2f72F8;//720 000
address roma_kiev = 0x5edc1959772b3C63310f475E04a72CdA1733D6A4;//Рома Киев 5% 1 800 000
address iliya = 0x45F8da4a6f465345DdaF003094C2B9D11254B15D;//Ильяс Казань 3% 1 080 000
address oleg =0x5f77b7F905913431957E800BfbDF5a9DB1B911C7;//Олег Калининград 5% 1 800 000
address fund =0x0Ecff5AA3F6bEcA65e0c39660b8A410c62d18F05;//ФОНД 1% 360 000
address mihail =0xb19f59271B64A2f8240b62Dbd6EEDFF38f6778DD;//Михаил 5% 1 800 000
address reserv1 =0x8a51B8Bc84272E375D2d46A8b29B1E245F2a9248;//Резерв1 1% 360 000
address reserv2 =0x3B820FDabc92d338E3625BbA2F81366df1C417d6;//Резерв2 1% 360 000
address reserv3 =0xb3B142e2Edccfb844c83CCcc872cFd8A13505240;//Резерв3 1% 360 000
address kostya = 0xC4Eb8BfFBAA3BC5dF11bdFD2e3800ed88EE0e5c7;//Костя 14% 500 000
address igor = 0xCd25FF018807bd8082E27AD7E12A28964c17159D;//Игорь 6% 200 000
address dasha =0x05D6b898701961452298D09B87f072239D836Cf4;//Даша 4% 150 000
address alexey =0x6BC2ee50CD8491745fD45Fb3a8E400BEdb2e02df;//Алексей 4% 150 000
address emp1 =0x8bfDedbB38ee8e6354BeffdAC26F0c64bBAB4F1d;//emp1 4% 150 000
address emp2 =0x4BCce99dD86DC640DCd76510aC7E68be67b44dD9;//emp2 4% 150 000
address emp3 =0x28C6d5D60A57046778be226c1Fea9def8B7bC067;//emp3 4% 150 000
address emp4 =0x00D56900f9D2d559A89fAEfe2CfbB464B1368dEe;//emp4 4% 150 000
address emp5 =0x241B9F4eeC66bE554378b1C9fF93FD4aaC0bD31c;//emp5 6% 200 000
address emp6 =0x536917d509117ccC26171E21CC51335d0b8022CE;//emp6 6% 200 000
address emp7 =0xf818199304A658B770eEcb85F2ad891D1B582beB;//emp7 6% 200 000
address emp8 =0x88Aec59d98b2dBEde71F96a5C8044D5b619955C0;//emp8 6% 200 000
address emp9 =0x35b3bDb3aC3c1c834fb5e9798a6cB9Db97caF370;//emp9 6% 200 000
address emp10 =0x9CA083D10fC4944F22654829Ac2E9702Ecce204F;//emp10 6% 200 000
address emp11 =0xBfD84a9641849B07271919AD2ad5F2453F4BF06c;//emp11 6% 200 000
address emp12 =0x7Ff40441F748229A004bc15e70Fccf3c82A51874;//emp12 3% 100 000
address emp13 =0xE7B45875d2380113eC3F76E7B7a44549C368E523;//emp13 3% 100 000
address emp14 =0xB46C56C97664152F77B26c5D0b8B5f1CB642A84E;//emp14 3% 100 000
address emp15 =0x897a133c4f01aEf11c58fd9Ec0c7932552a39C9f;//emp15 3% 100 000
address emp16 =0xd9537D3cf1a2624FA309c0AA65ac9eaAE350ef1D;//emp16 3% 100 000
address emp17 =0x4E4c22151f47D2C236Ac9Ec5D4fC2B46c58b34dE;//emp17 3% 100 000
function FoundersContract(address _token) public {
token = ROBOToken(_token);
balances_freez_one[muhtov] = 6840000 * 1 ether; //13680000
balances_freez_one[scherbakov] = 6840000 * 1 ether;// 13680000
balances_freez_one[sattarova] = 320000 * 1 ether;//720000
balances_freez_one[roma_kiev] = 900000 * 1 ether;//Рома Киев 5% 1800000
balances_freez_one[iliya] = 540000 * 1 ether;//Ильяс Казань 3% 1080000
balances_freez_one[oleg] = 900000 * 1 ether;//Олег Калининград 5% 1800000
balances_freez_one[fund] = 180000 * 1 ether;//ФОНД 1% 360000
balances_freez_one[mihail] =900000 * 1 ether; //Михаил 5% 1800000
balances_freez_one[reserv1] =180000 * 1 ether;//Резерв1 1% 360000
balances_freez_one[reserv2] =180000 * 1 ether;//Резерв2 1% 360000
balances_freez_one[reserv3] =180000 * 1 ether;//Резерв3 1% 360000
balances_freez_one[kostya] = 250000 * 1 ether;//500000
balances_freez_one[igor] = 100000 * 1 ether;//Игорь 6% 200000
balances_freez_one[dasha] = 75000 * 1 ether;//Даша 4% 150000
balances_freez_one[alexey] = 75000 * 1 ether;//Алексей 4% 150000
balances_freez_one[emp1] = 75000 * 1 ether;//emp1 4% 150000
balances_freez_one[emp2] = 75000 * 1 ether;//emp2 4% 150000
balances_freez_one[emp3] = 75000 * 1 ether;//emp3 4% 150000
balances_freez_one[emp4] = 75000 * 1 ether;//emp4 4% 150000
balances_freez_one[emp5] = 100000 * 1 ether;//emp5 6% 200000
balances_freez_one[emp6] = 100000 * 1 ether;//emp6 6% 200000
balances_freez_one[emp7] = 100000 * 1 ether;//emp7 6% 200000
balances_freez_one[emp8] = 100000 * 1 ether;//emp8 6% 200000
balances_freez_one[emp9] = 100000 * 1 ether;//emp9 6% 200000
balances_freez_one[emp10] = 100000 * 1 ether;//emp10 6% 200000
balances_freez_one[emp11] = 100000 * 1 ether;//emp11 6% 200000
balances_freez_one[emp12] = 50000 * 1 ether;//emp12 3% 100000
balances_freez_one[emp13] = 50000 * 1 ether;//emp13 3% 100000
balances_freez_one[emp14] = 50000 * 1 ether;//emp14 3% 100000
balances_freez_one[emp15] = 50000 * 1 ether;//emp15 3% 100000
balances_freez_one[emp16] = 50000 * 1 ether;//emp16 3% 100000
balances_freez_one[emp17] = 50000 * 1 ether; //emp17 3% 100000
balances_freez_two[muhtov] = balances_freez_one[muhtov];
balances_freez_two[scherbakov] = balances_freez_one[scherbakov];
balances_freez_two[sattarova] = balances_freez_one[sattarova];
balances_freez_two[roma_kiev] = balances_freez_one[roma_kiev];
balances_freez_two[iliya] = balances_freez_one[iliya];
balances_freez_two[oleg] = balances_freez_one[oleg];
balances_freez_two[fund] = balances_freez_one[fund];
balances_freez_two[mihail] = balances_freez_one[mihail];
balances_freez_two[reserv1] = balances_freez_one[reserv1];
balances_freez_two[reserv2] = balances_freez_one[reserv2];
balances_freez_two[reserv3] = balances_freez_one[reserv3];
balances_freez_two[kostya] = balances_freez_one[kostya];
balances_freez_two[igor] = balances_freez_one[igor];
balances_freez_two[dasha] = balances_freez_one[dasha];
balances_freez_two[alexey] = balances_freez_one[alexey];
balances_freez_two[emp1] = balances_freez_one[emp1];
balances_freez_two[emp2] = balances_freez_one[emp2];
balances_freez_two[emp3] = balances_freez_one[emp3];
balances_freez_two[emp4] = balances_freez_one[emp4];
balances_freez_two[emp5] = balances_freez_one[emp5];
balances_freez_two[emp6] = balances_freez_one[emp6];
balances_freez_two[emp7] = balances_freez_one[emp7];
balances_freez_two[emp8] = balances_freez_one[emp8];
balances_freez_two[emp9] = balances_freez_one[emp9];
balances_freez_two[emp10] = balances_freez_one[emp10];
balances_freez_two[emp11] = balances_freez_one[emp11];
balances_freez_two[emp12] = balances_freez_one[emp12];
balances_freez_two[emp13] = balances_freez_one[emp13];
balances_freez_two[emp14] = balances_freez_one[emp14];
balances_freez_two[emp15] = balances_freez_one[emp15];
balances_freez_two[emp16] = balances_freez_one[emp16];
balances_freez_two[emp17] = balances_freez_one[emp17];
}
function getFirstTokens() public {
require(freezOne <= uint64(now));
token.transfer(msg.sender, balances_freez_one[msg.sender]);
}
function getSecondTokens() public {
require(freezTwo <= uint64(now));
token.transfer(msg.sender, balances_freez_two[msg.sender]);
}
} | FoundersContract | function FoundersContract(address _token) public {
token = ROBOToken(_token);
balances_freez_one[muhtov] = 6840000 * 1 ether; //13680000
balances_freez_one[scherbakov] = 6840000 * 1 ether;// 13680000
balances_freez_one[sattarova] = 320000 * 1 ether;//720000
balances_freez_one[roma_kiev] = 900000 * 1 ether;//Рома Киев 5% 1800000
balances_freez_one[iliya] = 540000 * 1 ether;//Ильяс Казань 3% 1080000
balances_freez_one[oleg] = 900000 * 1 ether;//Олег Калининград 5% 1800000
balances_freez_one[fund] = 180000 * 1 ether;//ФОНД 1% 360000
balances_freez_one[mihail] =900000 * 1 ether; //Михаил 5% 1800000
balances_freez_one[reserv1] =180000 * 1 ether;//Резерв1 1% 360000
balances_freez_one[reserv2] =180000 * 1 ether;//Резерв2 1% 360000
balances_freez_one[reserv3] =180000 * 1 ether;//Резерв3 1% 360000
balances_freez_one[kostya] = 250000 * 1 ether;//500000
balances_freez_one[igor] = 100000 * 1 ether;//Игорь 6% 200000
balances_freez_one[dasha] = 75000 * 1 ether;//Даша 4% 150000
balances_freez_one[alexey] = 75000 * 1 ether;//Алексей 4% 150000
balances_freez_one[emp1] = 75000 * 1 ether;//emp1 4% 150000
balances_freez_one[emp2] = 75000 * 1 ether;//emp2 4% 150000
balances_freez_one[emp3] = 75000 * 1 ether;//emp3 4% 150000
balances_freez_one[emp4] = 75000 * 1 ether;//emp4 4% 150000
balances_freez_one[emp5] = 100000 * 1 ether;//emp5 6% 200000
balances_freez_one[emp6] = 100000 * 1 ether;//emp6 6% 200000
balances_freez_one[emp7] = 100000 * 1 ether;//emp7 6% 200000
balances_freez_one[emp8] = 100000 * 1 ether;//emp8 6% 200000
balances_freez_one[emp9] = 100000 * 1 ether;//emp9 6% 200000
balances_freez_one[emp10] = 100000 * 1 ether;//emp10 6% 200000
balances_freez_one[emp11] = 100000 * 1 ether;//emp11 6% 200000
balances_freez_one[emp12] = 50000 * 1 ether;//emp12 3% 100000
balances_freez_one[emp13] = 50000 * 1 ether;//emp13 3% 100000
balances_freez_one[emp14] = 50000 * 1 ether;//emp14 3% 100000
balances_freez_one[emp15] = 50000 * 1 ether;//emp15 3% 100000
balances_freez_one[emp16] = 50000 * 1 ether;//emp16 3% 100000
balances_freez_one[emp17] = 50000 * 1 ether; //emp17 3% 100000
balances_freez_two[muhtov] = balances_freez_one[muhtov];
balances_freez_two[scherbakov] = balances_freez_one[scherbakov];
balances_freez_two[sattarova] = balances_freez_one[sattarova];
balances_freez_two[roma_kiev] = balances_freez_one[roma_kiev];
balances_freez_two[iliya] = balances_freez_one[iliya];
balances_freez_two[oleg] = balances_freez_one[oleg];
balances_freez_two[fund] = balances_freez_one[fund];
balances_freez_two[mihail] = balances_freez_one[mihail];
balances_freez_two[reserv1] = balances_freez_one[reserv1];
balances_freez_two[reserv2] = balances_freez_one[reserv2];
balances_freez_two[reserv3] = balances_freez_one[reserv3];
balances_freez_two[kostya] = balances_freez_one[kostya];
balances_freez_two[igor] = balances_freez_one[igor];
balances_freez_two[dasha] = balances_freez_one[dasha];
balances_freez_two[alexey] = balances_freez_one[alexey];
balances_freez_two[emp1] = balances_freez_one[emp1];
balances_freez_two[emp2] = balances_freez_one[emp2];
balances_freez_two[emp3] = balances_freez_one[emp3];
balances_freez_two[emp4] = balances_freez_one[emp4];
balances_freez_two[emp5] = balances_freez_one[emp5];
balances_freez_two[emp6] = balances_freez_one[emp6];
balances_freez_two[emp7] = balances_freez_one[emp7];
balances_freez_two[emp8] = balances_freez_one[emp8];
balances_freez_two[emp9] = balances_freez_one[emp9];
balances_freez_two[emp10] = balances_freez_one[emp10];
balances_freez_two[emp11] = balances_freez_one[emp11];
balances_freez_two[emp12] = balances_freez_one[emp12];
balances_freez_two[emp13] = balances_freez_one[emp13];
balances_freez_two[emp14] = balances_freez_one[emp14];
balances_freez_two[emp15] = balances_freez_one[emp15];
balances_freez_two[emp16] = balances_freez_one[emp16];
balances_freez_two[emp17] = balances_freez_one[emp17];
}
| //emp17 3% 100 000 | LineComment | v0.4.21+commit.dfe3193c | bzzr://1cc26be6b25749aea9912a3b4e5b725c56e13315bc6704235c6929ec387466aa | {
"func_code_index": [
2965,
7451
]
} | 13,208 |
|||
LidoBridgeSwapper | contracts/LidoBridgeSwapper.sol | 0xd222a83d4dd5bad5ed5e9430c99661df4c3483da | Solidity | LidoBridgeSwapper | contract LidoBridgeSwapper is ZkSyncBridgeSwapper {
// The address of the stEth token
address public immutable stEth;
// The address of the wrapped stEth token
address public immutable wStEth;
// The address of the stEth/Eth Curve pool
address public immutable stEthPool;
// The referral address for Lido
address public immutable lidoReferral;
constructor(
address _zkSync,
address _l2Account,
address _wStEth,
address _stEthPool,
address _lidoReferral
)
ZkSyncBridgeSwapper(_zkSync, _l2Account)
{
wStEth = _wStEth;
address _stEth = IWstETH(_wStEth).stETH();
require(_stEth == ICurvePool(_stEthPool).coins(1), "stEth mismatch");
stEth = _stEth;
stEthPool = _stEthPool;
lidoReferral = _lidoReferral;
}
function exchange(uint256 _indexIn, uint256 _indexOut, uint256 _amountIn) external override returns (uint256 amountOut) {
require(_indexIn + _indexOut == 1, "invalid indexes");
if (_indexIn == 0) {
transferFromZkSync(ETH_TOKEN);
amountOut = swapEthForStEth(_amountIn);
transferToZkSync(wStEth, amountOut);
emit Swapped(ETH_TOKEN, _amountIn, wStEth, amountOut);
} else {
transferFromZkSync(wStEth);
amountOut = swapStEthForEth(_amountIn);
transferToZkSync(ETH_TOKEN, amountOut);
emit Swapped(wStEth, _amountIn, ETH_TOKEN, amountOut);
}
}
/**
* @dev Swaps ETH for wrapped stETH and deposits the resulting wstETH to the ZkSync bridge.
* First withdraws ETH from the bridge if there is a pending balance.
* @param _amountIn The amount of ETH to swap.
*/
function swapEthForStEth(uint256 _amountIn) internal returns (uint256) {
// swap Eth for stEth on the Lido contract
ILido(stEth).submit{value: _amountIn}(lidoReferral);
// approve the wStEth contract to take the stEth
IERC20(stEth).approve(wStEth, _amountIn);
// wrap to wStEth and return deposited amount
return IWstETH(wStEth).wrap(_amountIn);
}
/**
* @dev Swaps wrapped stETH for ETH and deposits the resulting ETH to the ZkSync bridge.
* First withdraws wrapped stETH from the bridge if there is a pending balance.
* @param _amountIn The amount of wrapped stETH to swap.
*/
function swapStEthForEth(uint256 _amountIn) internal returns (uint256) {
// unwrap to stEth
uint256 unwrapped = IWstETH(wStEth).unwrap(_amountIn);
// approve pool
bool success = IERC20(stEth).approve(stEthPool, unwrapped);
require(success, "approve failed");
// swap stEth for ETH on Curve and return deposited amount
return ICurvePool(stEthPool).exchange(1, 0, unwrapped, getMinAmountOut(unwrapped));
}
} | /**
* Exchanges between ETH and wStETH
* index 0: ETH
* index 1: wStETH
*/ | NatSpecMultiLine | swapEthForStEth | function swapEthForStEth(uint256 _amountIn) internal returns (uint256) {
// swap Eth for stEth on the Lido contract
ILido(stEth).submit{value: _amountIn}(lidoReferral);
// approve the wStEth contract to take the stEth
IERC20(stEth).approve(wStEth, _amountIn);
// wrap to wStEth and return deposited amount
return IWstETH(wStEth).wrap(_amountIn);
}
| /**
* @dev Swaps ETH for wrapped stETH and deposits the resulting wstETH to the ZkSync bridge.
* First withdraws ETH from the bridge if there is a pending balance.
* @param _amountIn The amount of ETH to swap.
*/ | NatSpecMultiLine | v0.8.3+commit.8d00100c | {
"func_code_index": [
1756,
2159
]
} | 13,209 |
||
LidoBridgeSwapper | contracts/LidoBridgeSwapper.sol | 0xd222a83d4dd5bad5ed5e9430c99661df4c3483da | Solidity | LidoBridgeSwapper | contract LidoBridgeSwapper is ZkSyncBridgeSwapper {
// The address of the stEth token
address public immutable stEth;
// The address of the wrapped stEth token
address public immutable wStEth;
// The address of the stEth/Eth Curve pool
address public immutable stEthPool;
// The referral address for Lido
address public immutable lidoReferral;
constructor(
address _zkSync,
address _l2Account,
address _wStEth,
address _stEthPool,
address _lidoReferral
)
ZkSyncBridgeSwapper(_zkSync, _l2Account)
{
wStEth = _wStEth;
address _stEth = IWstETH(_wStEth).stETH();
require(_stEth == ICurvePool(_stEthPool).coins(1), "stEth mismatch");
stEth = _stEth;
stEthPool = _stEthPool;
lidoReferral = _lidoReferral;
}
function exchange(uint256 _indexIn, uint256 _indexOut, uint256 _amountIn) external override returns (uint256 amountOut) {
require(_indexIn + _indexOut == 1, "invalid indexes");
if (_indexIn == 0) {
transferFromZkSync(ETH_TOKEN);
amountOut = swapEthForStEth(_amountIn);
transferToZkSync(wStEth, amountOut);
emit Swapped(ETH_TOKEN, _amountIn, wStEth, amountOut);
} else {
transferFromZkSync(wStEth);
amountOut = swapStEthForEth(_amountIn);
transferToZkSync(ETH_TOKEN, amountOut);
emit Swapped(wStEth, _amountIn, ETH_TOKEN, amountOut);
}
}
/**
* @dev Swaps ETH for wrapped stETH and deposits the resulting wstETH to the ZkSync bridge.
* First withdraws ETH from the bridge if there is a pending balance.
* @param _amountIn The amount of ETH to swap.
*/
function swapEthForStEth(uint256 _amountIn) internal returns (uint256) {
// swap Eth for stEth on the Lido contract
ILido(stEth).submit{value: _amountIn}(lidoReferral);
// approve the wStEth contract to take the stEth
IERC20(stEth).approve(wStEth, _amountIn);
// wrap to wStEth and return deposited amount
return IWstETH(wStEth).wrap(_amountIn);
}
/**
* @dev Swaps wrapped stETH for ETH and deposits the resulting ETH to the ZkSync bridge.
* First withdraws wrapped stETH from the bridge if there is a pending balance.
* @param _amountIn The amount of wrapped stETH to swap.
*/
function swapStEthForEth(uint256 _amountIn) internal returns (uint256) {
// unwrap to stEth
uint256 unwrapped = IWstETH(wStEth).unwrap(_amountIn);
// approve pool
bool success = IERC20(stEth).approve(stEthPool, unwrapped);
require(success, "approve failed");
// swap stEth for ETH on Curve and return deposited amount
return ICurvePool(stEthPool).exchange(1, 0, unwrapped, getMinAmountOut(unwrapped));
}
} | /**
* Exchanges between ETH and wStETH
* index 0: ETH
* index 1: wStETH
*/ | NatSpecMultiLine | swapStEthForEth | function swapStEthForEth(uint256 _amountIn) internal returns (uint256) {
// unwrap to stEth
uint256 unwrapped = IWstETH(wStEth).unwrap(_amountIn);
// approve pool
bool success = IERC20(stEth).approve(stEthPool, unwrapped);
require(success, "approve failed");
// swap stEth for ETH on Curve and return deposited amount
return ICurvePool(stEthPool).exchange(1, 0, unwrapped, getMinAmountOut(unwrapped));
}
| /**
* @dev Swaps wrapped stETH for ETH and deposits the resulting ETH to the ZkSync bridge.
* First withdraws wrapped stETH from the bridge if there is a pending balance.
* @param _amountIn The amount of wrapped stETH to swap.
*/ | NatSpecMultiLine | v0.8.3+commit.8d00100c | {
"func_code_index": [
2411,
2878
]
} | 13,210 |
||
PACOIN | PACOIN.sol | 0xaf470d6dc7d02c301e3b2b871e63f075be6ce207 | 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 Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | mul | function mul(uint256 a, uint256 b) internal pure returns (uint256) {
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.25-nightly.2018.6.14+commit.baeabe1c | bzzr://10e3f690a68caa6e8b1cd1ec13b2edbc7af2621b111d718e8a8f31b97e04d08b | {
"func_code_index": [
89,
272
]
} | 13,211 |
|
PACOIN | PACOIN.sol | 0xaf470d6dc7d02c301e3b2b871e63f075be6ce207 | 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 Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | div | function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| /**
* @dev Integer division of two numbers, truncating the quotient.
*/ | NatSpecMultiLine | v0.4.25-nightly.2018.6.14+commit.baeabe1c | bzzr://10e3f690a68caa6e8b1cd1ec13b2edbc7af2621b111d718e8a8f31b97e04d08b | {
"func_code_index": [
356,
629
]
} | 13,212 |
|
PACOIN | PACOIN.sol | 0xaf470d6dc7d02c301e3b2b871e63f075be6ce207 | 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 Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | sub | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
| /**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/ | NatSpecMultiLine | v0.4.25-nightly.2018.6.14+commit.baeabe1c | bzzr://10e3f690a68caa6e8b1cd1ec13b2edbc7af2621b111d718e8a8f31b97e04d08b | {
"func_code_index": [
743,
859
]
} | 13,213 |
|
PACOIN | PACOIN.sol | 0xaf470d6dc7d02c301e3b2b871e63f075be6ce207 | 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 Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | /**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/ | NatSpecMultiLine | add | function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
| /**
* @dev Adds two numbers, throws on overflow.
*/ | NatSpecMultiLine | v0.4.25-nightly.2018.6.14+commit.baeabe1c | bzzr://10e3f690a68caa6e8b1cd1ec13b2edbc7af2621b111d718e8a8f31b97e04d08b | {
"func_code_index": [
923,
1059
]
} | 13,214 |
|
PACOIN | PACOIN.sol | 0xaf470d6dc7d02c301e3b2b871e63f075be6ce207 | Solidity | TokenERC20 | contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
} | TokenERC20 | function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
| /**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/ | NatSpecMultiLine | v0.4.25-nightly.2018.6.14+commit.baeabe1c | bzzr://10e3f690a68caa6e8b1cd1ec13b2edbc7af2621b111d718e8a8f31b97e04d08b | {
"func_code_index": [
890,
1453
]
} | 13,215 |
|||
PACOIN | PACOIN.sol | 0xaf470d6dc7d02c301e3b2b871e63f075be6ce207 | Solidity | TokenERC20 | contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
} | _transfer | function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
| /**
* Internal transfer, only can be called by this contract
*/ | NatSpecMultiLine | v0.4.25-nightly.2018.6.14+commit.baeabe1c | bzzr://10e3f690a68caa6e8b1cd1ec13b2edbc7af2621b111d718e8a8f31b97e04d08b | {
"func_code_index": [
1548,
2422
]
} | 13,216 |
|||
PACOIN | PACOIN.sol | 0xaf470d6dc7d02c301e3b2b871e63f075be6ce207 | Solidity | TokenERC20 | contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
} | transfer | function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
| /**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/ | NatSpecMultiLine | v0.4.25-nightly.2018.6.14+commit.baeabe1c | bzzr://10e3f690a68caa6e8b1cd1ec13b2edbc7af2621b111d718e8a8f31b97e04d08b | {
"func_code_index": [
2649,
2765
]
} | 13,217 |
|||
PACOIN | PACOIN.sol | 0xaf470d6dc7d02c301e3b2b871e63f075be6ce207 | Solidity | TokenERC20 | contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
} | transferFrom | function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
| /**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/ | NatSpecMultiLine | v0.4.25-nightly.2018.6.14+commit.baeabe1c | bzzr://10e3f690a68caa6e8b1cd1ec13b2edbc7af2621b111d718e8a8f31b97e04d08b | {
"func_code_index": [
3063,
3374
]
} | 13,218 |
|||
PACOIN | PACOIN.sol | 0xaf470d6dc7d02c301e3b2b871e63f075be6ce207 | Solidity | TokenERC20 | contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
} | approve | function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
| /**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/ | NatSpecMultiLine | v0.4.25-nightly.2018.6.14+commit.baeabe1c | bzzr://10e3f690a68caa6e8b1cd1ec13b2edbc7af2621b111d718e8a8f31b97e04d08b | {
"func_code_index": [
3659,
3843
]
} | 13,219 |
|||
PACOIN | PACOIN.sol | 0xaf470d6dc7d02c301e3b2b871e63f075be6ce207 | Solidity | TokenERC20 | contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
} | approveAndCall | function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
| /**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/ | NatSpecMultiLine | v0.4.25-nightly.2018.6.14+commit.baeabe1c | bzzr://10e3f690a68caa6e8b1cd1ec13b2edbc7af2621b111d718e8a8f31b97e04d08b | {
"func_code_index": [
4260,
4628
]
} | 13,220 |
|||
PACOIN | PACOIN.sol | 0xaf470d6dc7d02c301e3b2b871e63f075be6ce207 | Solidity | TokenERC20 | contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
} | burn | function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
| /**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/ | NatSpecMultiLine | v0.4.25-nightly.2018.6.14+commit.baeabe1c | bzzr://10e3f690a68caa6e8b1cd1ec13b2edbc7af2621b111d718e8a8f31b97e04d08b | {
"func_code_index": [
4817,
5203
]
} | 13,221 |
|||
PACOIN | PACOIN.sol | 0xaf470d6dc7d02c301e3b2b871e63f075be6ce207 | Solidity | TokenERC20 | contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
} | burnFrom | function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
| /**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/ | NatSpecMultiLine | v0.4.25-nightly.2018.6.14+commit.baeabe1c | bzzr://10e3f690a68caa6e8b1cd1ec13b2edbc7af2621b111d718e8a8f31b97e04d08b | {
"func_code_index": [
5482,
6109
]
} | 13,222 |
|||
PACOIN | PACOIN.sol | 0xaf470d6dc7d02c301e3b2b871e63f075be6ce207 | Solidity | PACOIN | contract PACOIN is owned, TokenERC20 {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
using SafeMath for uint256;
/* Initializes contract with initial supply tokens to the creator of the contract */
function PACOIN(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(_from, _to, _value);
}
function batchTransfer(address[] _tos, uint256[] _amount) onlyOwner public returns (bool success) {
require(_tos.length == _amount.length);
uint256 i;
uint256 sum = 0;
for(i = 0; i < _amount.length; i++) {
sum = sum.add(_amount[i]);
require(_tos[i] != address(0));
}
require(balanceOf[msg.sender] >= sum);
for(i = 0; i < _tos.length; i++){
transfer(_tos[i], _amount[i]);
return true;
}
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/// @notice Buy tokens from contract by sending ether
function buy() payable public {
uint amount = msg.value / buyPrice; // calculates the amount
_transfer(this, msg.sender, amount); // makes the transfers
}
/// @notice Sell `amount` tokens to contract
/// @param amount amount of tokens to be sold
function sell(uint256 amount) public {
require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy
_transfer(msg.sender, this, amount); // makes the transfers
msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
} | /******************************************/ | NatSpecMultiLine | PACOIN | function PACOIN(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {}
| /* Initializes contract with initial supply tokens to the creator of the contract */ | Comment | v0.4.25-nightly.2018.6.14+commit.baeabe1c | bzzr://10e3f690a68caa6e8b1cd1ec13b2edbc7af2621b111d718e8a8f31b97e04d08b | {
"func_code_index": [
452,
635
]
} | 13,223 |
|
PACOIN | PACOIN.sol | 0xaf470d6dc7d02c301e3b2b871e63f075be6ce207 | Solidity | PACOIN | contract PACOIN is owned, TokenERC20 {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
using SafeMath for uint256;
/* Initializes contract with initial supply tokens to the creator of the contract */
function PACOIN(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(_from, _to, _value);
}
function batchTransfer(address[] _tos, uint256[] _amount) onlyOwner public returns (bool success) {
require(_tos.length == _amount.length);
uint256 i;
uint256 sum = 0;
for(i = 0; i < _amount.length; i++) {
sum = sum.add(_amount[i]);
require(_tos[i] != address(0));
}
require(balanceOf[msg.sender] >= sum);
for(i = 0; i < _tos.length; i++){
transfer(_tos[i], _amount[i]);
return true;
}
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/// @notice Buy tokens from contract by sending ether
function buy() payable public {
uint amount = msg.value / buyPrice; // calculates the amount
_transfer(this, msg.sender, amount); // makes the transfers
}
/// @notice Sell `amount` tokens to contract
/// @param amount amount of tokens to be sold
function sell(uint256 amount) public {
require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy
_transfer(msg.sender, this, amount); // makes the transfers
msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
} | /******************************************/ | NatSpecMultiLine | _transfer | function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(_from, _to, _value);
}
| /* Internal transfer, only can be called by this contract */ | Comment | v0.4.25-nightly.2018.6.14+commit.baeabe1c | bzzr://10e3f690a68caa6e8b1cd1ec13b2edbc7af2621b111d718e8a8f31b97e04d08b | {
"func_code_index": [
711,
1511
]
} | 13,224 |
|
PACOIN | PACOIN.sol | 0xaf470d6dc7d02c301e3b2b871e63f075be6ce207 | Solidity | PACOIN | contract PACOIN is owned, TokenERC20 {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
using SafeMath for uint256;
/* Initializes contract with initial supply tokens to the creator of the contract */
function PACOIN(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(_from, _to, _value);
}
function batchTransfer(address[] _tos, uint256[] _amount) onlyOwner public returns (bool success) {
require(_tos.length == _amount.length);
uint256 i;
uint256 sum = 0;
for(i = 0; i < _amount.length; i++) {
sum = sum.add(_amount[i]);
require(_tos[i] != address(0));
}
require(balanceOf[msg.sender] >= sum);
for(i = 0; i < _tos.length; i++){
transfer(_tos[i], _amount[i]);
return true;
}
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/// @notice Buy tokens from contract by sending ether
function buy() payable public {
uint amount = msg.value / buyPrice; // calculates the amount
_transfer(this, msg.sender, amount); // makes the transfers
}
/// @notice Sell `amount` tokens to contract
/// @param amount amount of tokens to be sold
function sell(uint256 amount) public {
require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy
_transfer(msg.sender, this, amount); // makes the transfers
msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
} | /******************************************/ | NatSpecMultiLine | mintToken | function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
| /// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive | NatSpecSingleLine | v0.4.25-nightly.2018.6.14+commit.baeabe1c | bzzr://10e3f690a68caa6e8b1cd1ec13b2edbc7af2621b111d718e8a8f31b97e04d08b | {
"func_code_index": [
2246,
2514
]
} | 13,225 |
|
PACOIN | PACOIN.sol | 0xaf470d6dc7d02c301e3b2b871e63f075be6ce207 | Solidity | PACOIN | contract PACOIN is owned, TokenERC20 {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
using SafeMath for uint256;
/* Initializes contract with initial supply tokens to the creator of the contract */
function PACOIN(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(_from, _to, _value);
}
function batchTransfer(address[] _tos, uint256[] _amount) onlyOwner public returns (bool success) {
require(_tos.length == _amount.length);
uint256 i;
uint256 sum = 0;
for(i = 0; i < _amount.length; i++) {
sum = sum.add(_amount[i]);
require(_tos[i] != address(0));
}
require(balanceOf[msg.sender] >= sum);
for(i = 0; i < _tos.length; i++){
transfer(_tos[i], _amount[i]);
return true;
}
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/// @notice Buy tokens from contract by sending ether
function buy() payable public {
uint amount = msg.value / buyPrice; // calculates the amount
_transfer(this, msg.sender, amount); // makes the transfers
}
/// @notice Sell `amount` tokens to contract
/// @param amount amount of tokens to be sold
function sell(uint256 amount) public {
require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy
_transfer(msg.sender, this, amount); // makes the transfers
msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
} | /******************************************/ | NatSpecMultiLine | freezeAccount | function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
| /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not | NatSpecSingleLine | v0.4.25-nightly.2018.6.14+commit.baeabe1c | bzzr://10e3f690a68caa6e8b1cd1ec13b2edbc7af2621b111d718e8a8f31b97e04d08b | {
"func_code_index": [
2706,
2873
]
} | 13,226 |
|
PACOIN | PACOIN.sol | 0xaf470d6dc7d02c301e3b2b871e63f075be6ce207 | Solidity | PACOIN | contract PACOIN is owned, TokenERC20 {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
using SafeMath for uint256;
/* Initializes contract with initial supply tokens to the creator of the contract */
function PACOIN(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(_from, _to, _value);
}
function batchTransfer(address[] _tos, uint256[] _amount) onlyOwner public returns (bool success) {
require(_tos.length == _amount.length);
uint256 i;
uint256 sum = 0;
for(i = 0; i < _amount.length; i++) {
sum = sum.add(_amount[i]);
require(_tos[i] != address(0));
}
require(balanceOf[msg.sender] >= sum);
for(i = 0; i < _tos.length; i++){
transfer(_tos[i], _amount[i]);
return true;
}
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/// @notice Buy tokens from contract by sending ether
function buy() payable public {
uint amount = msg.value / buyPrice; // calculates the amount
_transfer(this, msg.sender, amount); // makes the transfers
}
/// @notice Sell `amount` tokens to contract
/// @param amount amount of tokens to be sold
function sell(uint256 amount) public {
require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy
_transfer(msg.sender, this, amount); // makes the transfers
msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
} | /******************************************/ | NatSpecMultiLine | setPrices | function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
| /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract | NatSpecSingleLine | v0.4.25-nightly.2018.6.14+commit.baeabe1c | bzzr://10e3f690a68caa6e8b1cd1ec13b2edbc7af2621b111d718e8a8f31b97e04d08b | {
"func_code_index": [
3127,
3293
]
} | 13,227 |
|
PACOIN | PACOIN.sol | 0xaf470d6dc7d02c301e3b2b871e63f075be6ce207 | Solidity | PACOIN | contract PACOIN is owned, TokenERC20 {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
using SafeMath for uint256;
/* Initializes contract with initial supply tokens to the creator of the contract */
function PACOIN(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(_from, _to, _value);
}
function batchTransfer(address[] _tos, uint256[] _amount) onlyOwner public returns (bool success) {
require(_tos.length == _amount.length);
uint256 i;
uint256 sum = 0;
for(i = 0; i < _amount.length; i++) {
sum = sum.add(_amount[i]);
require(_tos[i] != address(0));
}
require(balanceOf[msg.sender] >= sum);
for(i = 0; i < _tos.length; i++){
transfer(_tos[i], _amount[i]);
return true;
}
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/// @notice Buy tokens from contract by sending ether
function buy() payable public {
uint amount = msg.value / buyPrice; // calculates the amount
_transfer(this, msg.sender, amount); // makes the transfers
}
/// @notice Sell `amount` tokens to contract
/// @param amount amount of tokens to be sold
function sell(uint256 amount) public {
require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy
_transfer(msg.sender, this, amount); // makes the transfers
msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
} | /******************************************/ | NatSpecMultiLine | buy | function buy() payable public {
uint amount = msg.value / buyPrice; // calculates the amount
_transfer(this, msg.sender, amount); // makes the transfers
}
| /// @notice Buy tokens from contract by sending ether | NatSpecSingleLine | v0.4.25-nightly.2018.6.14+commit.baeabe1c | bzzr://10e3f690a68caa6e8b1cd1ec13b2edbc7af2621b111d718e8a8f31b97e04d08b | {
"func_code_index": [
3362,
3577
]
} | 13,228 |
|
PACOIN | PACOIN.sol | 0xaf470d6dc7d02c301e3b2b871e63f075be6ce207 | Solidity | PACOIN | contract PACOIN is owned, TokenERC20 {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
using SafeMath for uint256;
/* Initializes contract with initial supply tokens to the creator of the contract */
function PACOIN(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
require(!frozenAccount[_from]); // Check if sender is frozen
require(!frozenAccount[_to]); // Check if recipient is frozen
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(_from, _to, _value);
}
function batchTransfer(address[] _tos, uint256[] _amount) onlyOwner public returns (bool success) {
require(_tos.length == _amount.length);
uint256 i;
uint256 sum = 0;
for(i = 0; i < _amount.length; i++) {
sum = sum.add(_amount[i]);
require(_tos[i] != address(0));
}
require(balanceOf[msg.sender] >= sum);
for(i = 0; i < _tos.length; i++){
transfer(_tos[i], _amount[i]);
return true;
}
}
/// @notice Create `mintedAmount` tokens and send it to `target`
/// @param target Address to receive the tokens
/// @param mintedAmount the amount of tokens it will receive
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param target Address to be frozen
/// @param freeze either to freeze it or not
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
/// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth
/// @param newSellPrice Price the users can sell to the contract
/// @param newBuyPrice Price users can buy from the contract
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
/// @notice Buy tokens from contract by sending ether
function buy() payable public {
uint amount = msg.value / buyPrice; // calculates the amount
_transfer(this, msg.sender, amount); // makes the transfers
}
/// @notice Sell `amount` tokens to contract
/// @param amount amount of tokens to be sold
function sell(uint256 amount) public {
require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy
_transfer(msg.sender, this, amount); // makes the transfers
msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
} | /******************************************/ | NatSpecMultiLine | sell | function sell(uint256 amount) public {
require(this.balance >= amount * sellPrice); // checks if the contract has enough ether to buy
_transfer(msg.sender, this, amount); // makes the transfers
msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks
}
| /// @notice Sell `amount` tokens to contract
/// @param amount amount of tokens to be sold | NatSpecSingleLine | v0.4.25-nightly.2018.6.14+commit.baeabe1c | bzzr://10e3f690a68caa6e8b1cd1ec13b2edbc7af2621b111d718e8a8f31b97e04d08b | {
"func_code_index": [
3690,
4086
]
} | 13,229 |
|
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | Roles | library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
} | /**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/ | NatSpecMultiLine | add | function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
| /**
* @dev give an account access to this role
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
155,
346
]
} | 13,230 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | Roles | library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
} | /**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/ | NatSpecMultiLine | remove | function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
| /**
* @dev remove an account's access to this role
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
420,
614
]
} | 13,231 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | Roles | library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
} | /**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/ | NatSpecMultiLine | has | function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
| /**
* @dev check if an account has this role
* @return bool
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
703,
873
]
} | 13,232 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | Pausable | contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
} | /**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/ | NatSpecMultiLine | paused | function paused() public view returns (bool) {
return _paused;
}
| /**
* @return true if the contract is paused, false otherwise.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
289,
372
]
} | 13,233 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | Pausable | contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
} | /**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/ | NatSpecMultiLine | pause | function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
| /**
* @dev called by the owner to pause, triggers stopped state
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
825,
946
]
} | 13,234 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | Pausable | contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
} | /**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/ | NatSpecMultiLine | unpause | function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
| /**
* @dev called by the owner to unpause, returns to normal state
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
1036,
1159
]
} | 13,235 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | Ownable | contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | owner | function owner() public view returns (address) {
return _owner;
}
| /**
* @return the address of the owner.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
457,
541
]
} | 13,236 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | Ownable | contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | isOwner | function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
| /**
* @return true if `msg.sender` is the owner of the contract.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
792,
889
]
} | 13,237 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | Ownable | contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | renounceOwnership | function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
| /**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
1247,
1392
]
} | 13,238 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | Ownable | contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | transferOwnership | function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
| /**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
1564,
1678
]
} | 13,239 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | Ownable | contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | _transferOwnership | function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| /**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
1823,
2015
]
} | 13,240 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | /**
* @title SafeMath
* @dev Unsigned 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 unsigned integers, reverts on overflow.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
106,
544
]
} | 13,241 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | /**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/ | NatSpecMultiLine | div | function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| /**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
674,
982
]
} | 13,242 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | /**
* @title SafeMath
* @dev Unsigned 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 unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
1115,
1270
]
} | 13,243 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | /**
* @title SafeMath
* @dev Unsigned 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 unsigned integers, reverts on overflow.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
1353,
1508
]
} | 13,244 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | SafeMath | library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | /**
* @title SafeMath
* @dev Unsigned 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 unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
1664,
1793
]
} | 13,245 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/ | NatSpecMultiLine | totalSupply | function totalSupply() public view returns (uint256) {
return _totalSupply;
}
| /**
* @dev Total number of tokens in existence
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
297,
393
]
} | 13,246 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
| /**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
607,
718
]
} | 13,247 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/ | NatSpecMultiLine | allowance | function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
| /**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
1052,
1188
]
} | 13,248 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/ | NatSpecMultiLine | transfer | function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
| /**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
1357,
1502
]
} | 13,249 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/ | NatSpecMultiLine | approve | function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
| /**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
2144,
2297
]
} | 13,250 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/ | NatSpecMultiLine | transferFrom | function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
| /**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
2765,
2998
]
} | 13,251 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/ | NatSpecMultiLine | increaseAllowance | function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
| /**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
3519,
3727
]
} | 13,252 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/ | NatSpecMultiLine | decreaseAllowance | function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
| /**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
4253,
4471
]
} | 13,253 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/ | NatSpecMultiLine | _transfer | function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
| /**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
4693,
4960
]
} | 13,254 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/ | NatSpecMultiLine | _mint | function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
| /**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
5307,
5581
]
} | 13,255 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/ | NatSpecMultiLine | _burn | function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
| /**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
5810,
6084
]
} | 13,256 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/ | NatSpecMultiLine | _approve | function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
| /**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
6352,
6611
]
} | 13,257 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | ERC20 | contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/ | NatSpecMultiLine | _burnFrom | function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
| /**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
7005,
7192
]
} | 13,258 |
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | BlackList | contract BlackList is Ownable {
/////// Getter to allow the same blacklist to be used also by other contracts (including upgraded Deep Network) ///////
function getBlackListStatus(address _maker) external view returns (bool) {
return isBlackListed[_maker];
}
mapping (address => bool) public isBlackListed;
function addBlackList (address _evilUser) public onlyOwner {
isBlackListed[_evilUser] = true;
emit AddedBlackList(_evilUser);
}
function removeBlackList (address _clearedUser) public onlyOwner {
isBlackListed[_clearedUser] = false;
emit RemovedBlackList(_clearedUser);
}
event AddedBlackList(address indexed _user);
event RemovedBlackList(address indexed _user);
} | getBlackListStatus | function getBlackListStatus(address _maker) external view returns (bool) {
return isBlackListed[_maker];
}
| /////// Getter to allow the same blacklist to be used also by other contracts (including upgraded Deep Network) /////// | NatSpecSingleLine | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
160,
285
]
} | 13,259 |
||
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | DeepNetworkToken | contract DeepNetworkToken is Pausable, StandardTokenWithFees, BlackList {
address public upgradedAddress;
bool public deprecated;
// The contract can be initialized with a number of tokens
// All the tokens are deposited to the owner address
//
// @param _balance Initial supply of the contract
// @param _name Token Name
// @param _symbol Token symbol
// @param _decimals Token decimals
constructor (uint _initialSupply, string memory _name, string memory _symbol, uint8 _decimals) public {
_mint(owner(), _initialSupply);
name = _name;
symbol = _symbol;
decimals = _decimals;
deprecated = false;
emit Issue(_initialSupply);
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transfer(address _to, uint _value) public whenNotPaused returns (bool) {
require(!isBlackListed[msg.sender]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
} else {
return super.transfer(_to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transferFrom(address _from, address _to, uint _value) public whenNotPaused returns (bool) {
require(!isBlackListed[_from]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);
} else {
return super.transferFrom(_from, _to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function balanceOf(address who) public view returns (uint) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).balanceOf(who);
} else {
return super.balanceOf(who);
}
}
// Allow checks of balance at time of deprecation
function oldBalanceOf(address who) public view returns (uint) {
if (deprecated) {
return super.balanceOf(who);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function approve(address _spender, uint _value) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value);
} else {
return super.approve(_spender, _value);
}
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).increaseApprovalByLegacy(msg.sender, _spender, _addedValue);
} else {
return super.increaseAllowance(_spender, _addedValue);
}
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).decreaseApprovalByLegacy(msg.sender, _spender, _subtractedValue);
} else {
return super.decreaseAllowance(_spender, _subtractedValue);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function allowance(address _owner, address _spender) public view returns (uint remaining) {
if (deprecated) {
return IERC20(upgradedAddress).allowance(_owner, _spender);
} else {
return super.allowance(_owner, _spender);
}
}
// deprecate current contract in favour of a new one
function deprecate(address _upgradedAddress) public onlyOwner {
require(_upgradedAddress != address(0));
deprecated = true;
upgradedAddress = _upgradedAddress;
emit Deprecate(_upgradedAddress);
}
// deprecate current contract if favour of a new one
function totalSupply() public view returns (uint) {
if (deprecated) {
return IERC20(upgradedAddress).totalSupply();
} else {
return super.totalSupply();
}
}
// Issue a new amount of tokens
// these tokens are deposited into the owner address
//
// @param _amount Number of tokens to be issued
function issue(uint amount) public onlyOwner {
require(!deprecated);
_mint(owner(), amount);
emit Issue(amount);
}
// Redeem tokens.
// These tokens are withdrawn from the owner address
// if the balance must be enough to cover the redeem
// or the call will fail.
// @param _amount Number of tokens to be issued
function redeem(uint amount) public onlyOwner {
require(!deprecated);
_burn(owner(), amount);
emit Redeem(amount);
}
function destroyBlackFunds (address _blackListedUser) public onlyOwner {
require(isBlackListed[_blackListedUser]);
uint dirtyFunds = balanceOf(_blackListedUser);
_burn(_blackListedUser, dirtyFunds);
emit DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
event DestroyedBlackFunds(address indexed _blackListedUser, uint _balance);
// Called when new token are issued
event Issue(uint amount);
// Called when tokens are redeemed
event Redeem(uint amount);
// Called when contract is deprecated
event Deprecate(address newAddress);
} | transfer | function transfer(address _to, uint _value) public whenNotPaused returns (bool) {
require(!isBlackListed[msg.sender]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
} else {
return super.transfer(_to, _value);
}
}
| // Forward ERC20 methods to upgraded contract if this one is deprecated | LineComment | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
823,
1169
]
} | 13,260 |
||
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | DeepNetworkToken | contract DeepNetworkToken is Pausable, StandardTokenWithFees, BlackList {
address public upgradedAddress;
bool public deprecated;
// The contract can be initialized with a number of tokens
// All the tokens are deposited to the owner address
//
// @param _balance Initial supply of the contract
// @param _name Token Name
// @param _symbol Token symbol
// @param _decimals Token decimals
constructor (uint _initialSupply, string memory _name, string memory _symbol, uint8 _decimals) public {
_mint(owner(), _initialSupply);
name = _name;
symbol = _symbol;
decimals = _decimals;
deprecated = false;
emit Issue(_initialSupply);
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transfer(address _to, uint _value) public whenNotPaused returns (bool) {
require(!isBlackListed[msg.sender]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
} else {
return super.transfer(_to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transferFrom(address _from, address _to, uint _value) public whenNotPaused returns (bool) {
require(!isBlackListed[_from]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);
} else {
return super.transferFrom(_from, _to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function balanceOf(address who) public view returns (uint) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).balanceOf(who);
} else {
return super.balanceOf(who);
}
}
// Allow checks of balance at time of deprecation
function oldBalanceOf(address who) public view returns (uint) {
if (deprecated) {
return super.balanceOf(who);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function approve(address _spender, uint _value) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value);
} else {
return super.approve(_spender, _value);
}
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).increaseApprovalByLegacy(msg.sender, _spender, _addedValue);
} else {
return super.increaseAllowance(_spender, _addedValue);
}
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).decreaseApprovalByLegacy(msg.sender, _spender, _subtractedValue);
} else {
return super.decreaseAllowance(_spender, _subtractedValue);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function allowance(address _owner, address _spender) public view returns (uint remaining) {
if (deprecated) {
return IERC20(upgradedAddress).allowance(_owner, _spender);
} else {
return super.allowance(_owner, _spender);
}
}
// deprecate current contract in favour of a new one
function deprecate(address _upgradedAddress) public onlyOwner {
require(_upgradedAddress != address(0));
deprecated = true;
upgradedAddress = _upgradedAddress;
emit Deprecate(_upgradedAddress);
}
// deprecate current contract if favour of a new one
function totalSupply() public view returns (uint) {
if (deprecated) {
return IERC20(upgradedAddress).totalSupply();
} else {
return super.totalSupply();
}
}
// Issue a new amount of tokens
// these tokens are deposited into the owner address
//
// @param _amount Number of tokens to be issued
function issue(uint amount) public onlyOwner {
require(!deprecated);
_mint(owner(), amount);
emit Issue(amount);
}
// Redeem tokens.
// These tokens are withdrawn from the owner address
// if the balance must be enough to cover the redeem
// or the call will fail.
// @param _amount Number of tokens to be issued
function redeem(uint amount) public onlyOwner {
require(!deprecated);
_burn(owner(), amount);
emit Redeem(amount);
}
function destroyBlackFunds (address _blackListedUser) public onlyOwner {
require(isBlackListed[_blackListedUser]);
uint dirtyFunds = balanceOf(_blackListedUser);
_burn(_blackListedUser, dirtyFunds);
emit DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
event DestroyedBlackFunds(address indexed _blackListedUser, uint _balance);
// Called when new token are issued
event Issue(uint amount);
// Called when tokens are redeemed
event Redeem(uint amount);
// Called when contract is deprecated
event Deprecate(address newAddress);
} | transferFrom | function transferFrom(address _from, address _to, uint _value) public whenNotPaused returns (bool) {
require(!isBlackListed[_from]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);
} else {
return super.transferFrom(_from, _to, _value);
}
}
| // Forward ERC20 methods to upgraded contract if this one is deprecated | LineComment | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
1249,
1631
]
} | 13,261 |
||
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | DeepNetworkToken | contract DeepNetworkToken is Pausable, StandardTokenWithFees, BlackList {
address public upgradedAddress;
bool public deprecated;
// The contract can be initialized with a number of tokens
// All the tokens are deposited to the owner address
//
// @param _balance Initial supply of the contract
// @param _name Token Name
// @param _symbol Token symbol
// @param _decimals Token decimals
constructor (uint _initialSupply, string memory _name, string memory _symbol, uint8 _decimals) public {
_mint(owner(), _initialSupply);
name = _name;
symbol = _symbol;
decimals = _decimals;
deprecated = false;
emit Issue(_initialSupply);
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transfer(address _to, uint _value) public whenNotPaused returns (bool) {
require(!isBlackListed[msg.sender]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
} else {
return super.transfer(_to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transferFrom(address _from, address _to, uint _value) public whenNotPaused returns (bool) {
require(!isBlackListed[_from]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);
} else {
return super.transferFrom(_from, _to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function balanceOf(address who) public view returns (uint) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).balanceOf(who);
} else {
return super.balanceOf(who);
}
}
// Allow checks of balance at time of deprecation
function oldBalanceOf(address who) public view returns (uint) {
if (deprecated) {
return super.balanceOf(who);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function approve(address _spender, uint _value) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value);
} else {
return super.approve(_spender, _value);
}
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).increaseApprovalByLegacy(msg.sender, _spender, _addedValue);
} else {
return super.increaseAllowance(_spender, _addedValue);
}
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).decreaseApprovalByLegacy(msg.sender, _spender, _subtractedValue);
} else {
return super.decreaseAllowance(_spender, _subtractedValue);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function allowance(address _owner, address _spender) public view returns (uint remaining) {
if (deprecated) {
return IERC20(upgradedAddress).allowance(_owner, _spender);
} else {
return super.allowance(_owner, _spender);
}
}
// deprecate current contract in favour of a new one
function deprecate(address _upgradedAddress) public onlyOwner {
require(_upgradedAddress != address(0));
deprecated = true;
upgradedAddress = _upgradedAddress;
emit Deprecate(_upgradedAddress);
}
// deprecate current contract if favour of a new one
function totalSupply() public view returns (uint) {
if (deprecated) {
return IERC20(upgradedAddress).totalSupply();
} else {
return super.totalSupply();
}
}
// Issue a new amount of tokens
// these tokens are deposited into the owner address
//
// @param _amount Number of tokens to be issued
function issue(uint amount) public onlyOwner {
require(!deprecated);
_mint(owner(), amount);
emit Issue(amount);
}
// Redeem tokens.
// These tokens are withdrawn from the owner address
// if the balance must be enough to cover the redeem
// or the call will fail.
// @param _amount Number of tokens to be issued
function redeem(uint amount) public onlyOwner {
require(!deprecated);
_burn(owner(), amount);
emit Redeem(amount);
}
function destroyBlackFunds (address _blackListedUser) public onlyOwner {
require(isBlackListed[_blackListedUser]);
uint dirtyFunds = balanceOf(_blackListedUser);
_burn(_blackListedUser, dirtyFunds);
emit DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
event DestroyedBlackFunds(address indexed _blackListedUser, uint _balance);
// Called when new token are issued
event Issue(uint amount);
// Called when tokens are redeemed
event Redeem(uint amount);
// Called when contract is deprecated
event Deprecate(address newAddress);
} | balanceOf | function balanceOf(address who) public view returns (uint) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).balanceOf(who);
} else {
return super.balanceOf(who);
}
}
| // Forward ERC20 methods to upgraded contract if this one is deprecated | LineComment | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
1711,
1956
]
} | 13,262 |
||
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | DeepNetworkToken | contract DeepNetworkToken is Pausable, StandardTokenWithFees, BlackList {
address public upgradedAddress;
bool public deprecated;
// The contract can be initialized with a number of tokens
// All the tokens are deposited to the owner address
//
// @param _balance Initial supply of the contract
// @param _name Token Name
// @param _symbol Token symbol
// @param _decimals Token decimals
constructor (uint _initialSupply, string memory _name, string memory _symbol, uint8 _decimals) public {
_mint(owner(), _initialSupply);
name = _name;
symbol = _symbol;
decimals = _decimals;
deprecated = false;
emit Issue(_initialSupply);
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transfer(address _to, uint _value) public whenNotPaused returns (bool) {
require(!isBlackListed[msg.sender]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
} else {
return super.transfer(_to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transferFrom(address _from, address _to, uint _value) public whenNotPaused returns (bool) {
require(!isBlackListed[_from]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);
} else {
return super.transferFrom(_from, _to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function balanceOf(address who) public view returns (uint) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).balanceOf(who);
} else {
return super.balanceOf(who);
}
}
// Allow checks of balance at time of deprecation
function oldBalanceOf(address who) public view returns (uint) {
if (deprecated) {
return super.balanceOf(who);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function approve(address _spender, uint _value) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value);
} else {
return super.approve(_spender, _value);
}
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).increaseApprovalByLegacy(msg.sender, _spender, _addedValue);
} else {
return super.increaseAllowance(_spender, _addedValue);
}
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).decreaseApprovalByLegacy(msg.sender, _spender, _subtractedValue);
} else {
return super.decreaseAllowance(_spender, _subtractedValue);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function allowance(address _owner, address _spender) public view returns (uint remaining) {
if (deprecated) {
return IERC20(upgradedAddress).allowance(_owner, _spender);
} else {
return super.allowance(_owner, _spender);
}
}
// deprecate current contract in favour of a new one
function deprecate(address _upgradedAddress) public onlyOwner {
require(_upgradedAddress != address(0));
deprecated = true;
upgradedAddress = _upgradedAddress;
emit Deprecate(_upgradedAddress);
}
// deprecate current contract if favour of a new one
function totalSupply() public view returns (uint) {
if (deprecated) {
return IERC20(upgradedAddress).totalSupply();
} else {
return super.totalSupply();
}
}
// Issue a new amount of tokens
// these tokens are deposited into the owner address
//
// @param _amount Number of tokens to be issued
function issue(uint amount) public onlyOwner {
require(!deprecated);
_mint(owner(), amount);
emit Issue(amount);
}
// Redeem tokens.
// These tokens are withdrawn from the owner address
// if the balance must be enough to cover the redeem
// or the call will fail.
// @param _amount Number of tokens to be issued
function redeem(uint amount) public onlyOwner {
require(!deprecated);
_burn(owner(), amount);
emit Redeem(amount);
}
function destroyBlackFunds (address _blackListedUser) public onlyOwner {
require(isBlackListed[_blackListedUser]);
uint dirtyFunds = balanceOf(_blackListedUser);
_burn(_blackListedUser, dirtyFunds);
emit DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
event DestroyedBlackFunds(address indexed _blackListedUser, uint _balance);
// Called when new token are issued
event Issue(uint amount);
// Called when tokens are redeemed
event Redeem(uint amount);
// Called when contract is deprecated
event Deprecate(address newAddress);
} | oldBalanceOf | function oldBalanceOf(address who) public view returns (uint) {
if (deprecated) {
return super.balanceOf(who);
}
}
| // Allow checks of balance at time of deprecation | LineComment | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
2014,
2169
]
} | 13,263 |
||
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | DeepNetworkToken | contract DeepNetworkToken is Pausable, StandardTokenWithFees, BlackList {
address public upgradedAddress;
bool public deprecated;
// The contract can be initialized with a number of tokens
// All the tokens are deposited to the owner address
//
// @param _balance Initial supply of the contract
// @param _name Token Name
// @param _symbol Token symbol
// @param _decimals Token decimals
constructor (uint _initialSupply, string memory _name, string memory _symbol, uint8 _decimals) public {
_mint(owner(), _initialSupply);
name = _name;
symbol = _symbol;
decimals = _decimals;
deprecated = false;
emit Issue(_initialSupply);
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transfer(address _to, uint _value) public whenNotPaused returns (bool) {
require(!isBlackListed[msg.sender]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
} else {
return super.transfer(_to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transferFrom(address _from, address _to, uint _value) public whenNotPaused returns (bool) {
require(!isBlackListed[_from]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);
} else {
return super.transferFrom(_from, _to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function balanceOf(address who) public view returns (uint) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).balanceOf(who);
} else {
return super.balanceOf(who);
}
}
// Allow checks of balance at time of deprecation
function oldBalanceOf(address who) public view returns (uint) {
if (deprecated) {
return super.balanceOf(who);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function approve(address _spender, uint _value) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value);
} else {
return super.approve(_spender, _value);
}
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).increaseApprovalByLegacy(msg.sender, _spender, _addedValue);
} else {
return super.increaseAllowance(_spender, _addedValue);
}
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).decreaseApprovalByLegacy(msg.sender, _spender, _subtractedValue);
} else {
return super.decreaseAllowance(_spender, _subtractedValue);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function allowance(address _owner, address _spender) public view returns (uint remaining) {
if (deprecated) {
return IERC20(upgradedAddress).allowance(_owner, _spender);
} else {
return super.allowance(_owner, _spender);
}
}
// deprecate current contract in favour of a new one
function deprecate(address _upgradedAddress) public onlyOwner {
require(_upgradedAddress != address(0));
deprecated = true;
upgradedAddress = _upgradedAddress;
emit Deprecate(_upgradedAddress);
}
// deprecate current contract if favour of a new one
function totalSupply() public view returns (uint) {
if (deprecated) {
return IERC20(upgradedAddress).totalSupply();
} else {
return super.totalSupply();
}
}
// Issue a new amount of tokens
// these tokens are deposited into the owner address
//
// @param _amount Number of tokens to be issued
function issue(uint amount) public onlyOwner {
require(!deprecated);
_mint(owner(), amount);
emit Issue(amount);
}
// Redeem tokens.
// These tokens are withdrawn from the owner address
// if the balance must be enough to cover the redeem
// or the call will fail.
// @param _amount Number of tokens to be issued
function redeem(uint amount) public onlyOwner {
require(!deprecated);
_burn(owner(), amount);
emit Redeem(amount);
}
function destroyBlackFunds (address _blackListedUser) public onlyOwner {
require(isBlackListed[_blackListedUser]);
uint dirtyFunds = balanceOf(_blackListedUser);
_burn(_blackListedUser, dirtyFunds);
emit DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
event DestroyedBlackFunds(address indexed _blackListedUser, uint _balance);
// Called when new token are issued
event Issue(uint amount);
// Called when tokens are redeemed
event Redeem(uint amount);
// Called when contract is deprecated
event Deprecate(address newAddress);
} | approve | function approve(address _spender, uint _value) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value);
} else {
return super.approve(_spender, _value);
}
}
| // Forward ERC20 methods to upgraded contract if this one is deprecated | LineComment | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
2249,
2561
]
} | 13,264 |
||
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | DeepNetworkToken | contract DeepNetworkToken is Pausable, StandardTokenWithFees, BlackList {
address public upgradedAddress;
bool public deprecated;
// The contract can be initialized with a number of tokens
// All the tokens are deposited to the owner address
//
// @param _balance Initial supply of the contract
// @param _name Token Name
// @param _symbol Token symbol
// @param _decimals Token decimals
constructor (uint _initialSupply, string memory _name, string memory _symbol, uint8 _decimals) public {
_mint(owner(), _initialSupply);
name = _name;
symbol = _symbol;
decimals = _decimals;
deprecated = false;
emit Issue(_initialSupply);
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transfer(address _to, uint _value) public whenNotPaused returns (bool) {
require(!isBlackListed[msg.sender]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
} else {
return super.transfer(_to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transferFrom(address _from, address _to, uint _value) public whenNotPaused returns (bool) {
require(!isBlackListed[_from]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);
} else {
return super.transferFrom(_from, _to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function balanceOf(address who) public view returns (uint) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).balanceOf(who);
} else {
return super.balanceOf(who);
}
}
// Allow checks of balance at time of deprecation
function oldBalanceOf(address who) public view returns (uint) {
if (deprecated) {
return super.balanceOf(who);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function approve(address _spender, uint _value) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value);
} else {
return super.approve(_spender, _value);
}
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).increaseApprovalByLegacy(msg.sender, _spender, _addedValue);
} else {
return super.increaseAllowance(_spender, _addedValue);
}
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).decreaseApprovalByLegacy(msg.sender, _spender, _subtractedValue);
} else {
return super.decreaseAllowance(_spender, _subtractedValue);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function allowance(address _owner, address _spender) public view returns (uint remaining) {
if (deprecated) {
return IERC20(upgradedAddress).allowance(_owner, _spender);
} else {
return super.allowance(_owner, _spender);
}
}
// deprecate current contract in favour of a new one
function deprecate(address _upgradedAddress) public onlyOwner {
require(_upgradedAddress != address(0));
deprecated = true;
upgradedAddress = _upgradedAddress;
emit Deprecate(_upgradedAddress);
}
// deprecate current contract if favour of a new one
function totalSupply() public view returns (uint) {
if (deprecated) {
return IERC20(upgradedAddress).totalSupply();
} else {
return super.totalSupply();
}
}
// Issue a new amount of tokens
// these tokens are deposited into the owner address
//
// @param _amount Number of tokens to be issued
function issue(uint amount) public onlyOwner {
require(!deprecated);
_mint(owner(), amount);
emit Issue(amount);
}
// Redeem tokens.
// These tokens are withdrawn from the owner address
// if the balance must be enough to cover the redeem
// or the call will fail.
// @param _amount Number of tokens to be issued
function redeem(uint amount) public onlyOwner {
require(!deprecated);
_burn(owner(), amount);
emit Redeem(amount);
}
function destroyBlackFunds (address _blackListedUser) public onlyOwner {
require(isBlackListed[_blackListedUser]);
uint dirtyFunds = balanceOf(_blackListedUser);
_burn(_blackListedUser, dirtyFunds);
emit DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
event DestroyedBlackFunds(address indexed _blackListedUser, uint _balance);
// Called when new token are issued
event Issue(uint amount);
// Called when tokens are redeemed
event Redeem(uint amount);
// Called when contract is deprecated
event Deprecate(address newAddress);
} | allowance | function allowance(address _owner, address _spender) public view returns (uint remaining) {
if (deprecated) {
return IERC20(upgradedAddress).allowance(_owner, _spender);
} else {
return super.allowance(_owner, _spender);
}
}
| // Forward ERC20 methods to upgraded contract if this one is deprecated | LineComment | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
3372,
3659
]
} | 13,265 |
||
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | DeepNetworkToken | contract DeepNetworkToken is Pausable, StandardTokenWithFees, BlackList {
address public upgradedAddress;
bool public deprecated;
// The contract can be initialized with a number of tokens
// All the tokens are deposited to the owner address
//
// @param _balance Initial supply of the contract
// @param _name Token Name
// @param _symbol Token symbol
// @param _decimals Token decimals
constructor (uint _initialSupply, string memory _name, string memory _symbol, uint8 _decimals) public {
_mint(owner(), _initialSupply);
name = _name;
symbol = _symbol;
decimals = _decimals;
deprecated = false;
emit Issue(_initialSupply);
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transfer(address _to, uint _value) public whenNotPaused returns (bool) {
require(!isBlackListed[msg.sender]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
} else {
return super.transfer(_to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transferFrom(address _from, address _to, uint _value) public whenNotPaused returns (bool) {
require(!isBlackListed[_from]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);
} else {
return super.transferFrom(_from, _to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function balanceOf(address who) public view returns (uint) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).balanceOf(who);
} else {
return super.balanceOf(who);
}
}
// Allow checks of balance at time of deprecation
function oldBalanceOf(address who) public view returns (uint) {
if (deprecated) {
return super.balanceOf(who);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function approve(address _spender, uint _value) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value);
} else {
return super.approve(_spender, _value);
}
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).increaseApprovalByLegacy(msg.sender, _spender, _addedValue);
} else {
return super.increaseAllowance(_spender, _addedValue);
}
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).decreaseApprovalByLegacy(msg.sender, _spender, _subtractedValue);
} else {
return super.decreaseAllowance(_spender, _subtractedValue);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function allowance(address _owner, address _spender) public view returns (uint remaining) {
if (deprecated) {
return IERC20(upgradedAddress).allowance(_owner, _spender);
} else {
return super.allowance(_owner, _spender);
}
}
// deprecate current contract in favour of a new one
function deprecate(address _upgradedAddress) public onlyOwner {
require(_upgradedAddress != address(0));
deprecated = true;
upgradedAddress = _upgradedAddress;
emit Deprecate(_upgradedAddress);
}
// deprecate current contract if favour of a new one
function totalSupply() public view returns (uint) {
if (deprecated) {
return IERC20(upgradedAddress).totalSupply();
} else {
return super.totalSupply();
}
}
// Issue a new amount of tokens
// these tokens are deposited into the owner address
//
// @param _amount Number of tokens to be issued
function issue(uint amount) public onlyOwner {
require(!deprecated);
_mint(owner(), amount);
emit Issue(amount);
}
// Redeem tokens.
// These tokens are withdrawn from the owner address
// if the balance must be enough to cover the redeem
// or the call will fail.
// @param _amount Number of tokens to be issued
function redeem(uint amount) public onlyOwner {
require(!deprecated);
_burn(owner(), amount);
emit Redeem(amount);
}
function destroyBlackFunds (address _blackListedUser) public onlyOwner {
require(isBlackListed[_blackListedUser]);
uint dirtyFunds = balanceOf(_blackListedUser);
_burn(_blackListedUser, dirtyFunds);
emit DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
event DestroyedBlackFunds(address indexed _blackListedUser, uint _balance);
// Called when new token are issued
event Issue(uint amount);
// Called when tokens are redeemed
event Redeem(uint amount);
// Called when contract is deprecated
event Deprecate(address newAddress);
} | deprecate | function deprecate(address _upgradedAddress) public onlyOwner {
require(_upgradedAddress != address(0));
deprecated = true;
upgradedAddress = _upgradedAddress;
emit Deprecate(_upgradedAddress);
}
| // deprecate current contract in favour of a new one | LineComment | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
3720,
3961
]
} | 13,266 |
||
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | DeepNetworkToken | contract DeepNetworkToken is Pausable, StandardTokenWithFees, BlackList {
address public upgradedAddress;
bool public deprecated;
// The contract can be initialized with a number of tokens
// All the tokens are deposited to the owner address
//
// @param _balance Initial supply of the contract
// @param _name Token Name
// @param _symbol Token symbol
// @param _decimals Token decimals
constructor (uint _initialSupply, string memory _name, string memory _symbol, uint8 _decimals) public {
_mint(owner(), _initialSupply);
name = _name;
symbol = _symbol;
decimals = _decimals;
deprecated = false;
emit Issue(_initialSupply);
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transfer(address _to, uint _value) public whenNotPaused returns (bool) {
require(!isBlackListed[msg.sender]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
} else {
return super.transfer(_to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transferFrom(address _from, address _to, uint _value) public whenNotPaused returns (bool) {
require(!isBlackListed[_from]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);
} else {
return super.transferFrom(_from, _to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function balanceOf(address who) public view returns (uint) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).balanceOf(who);
} else {
return super.balanceOf(who);
}
}
// Allow checks of balance at time of deprecation
function oldBalanceOf(address who) public view returns (uint) {
if (deprecated) {
return super.balanceOf(who);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function approve(address _spender, uint _value) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value);
} else {
return super.approve(_spender, _value);
}
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).increaseApprovalByLegacy(msg.sender, _spender, _addedValue);
} else {
return super.increaseAllowance(_spender, _addedValue);
}
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).decreaseApprovalByLegacy(msg.sender, _spender, _subtractedValue);
} else {
return super.decreaseAllowance(_spender, _subtractedValue);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function allowance(address _owner, address _spender) public view returns (uint remaining) {
if (deprecated) {
return IERC20(upgradedAddress).allowance(_owner, _spender);
} else {
return super.allowance(_owner, _spender);
}
}
// deprecate current contract in favour of a new one
function deprecate(address _upgradedAddress) public onlyOwner {
require(_upgradedAddress != address(0));
deprecated = true;
upgradedAddress = _upgradedAddress;
emit Deprecate(_upgradedAddress);
}
// deprecate current contract if favour of a new one
function totalSupply() public view returns (uint) {
if (deprecated) {
return IERC20(upgradedAddress).totalSupply();
} else {
return super.totalSupply();
}
}
// Issue a new amount of tokens
// these tokens are deposited into the owner address
//
// @param _amount Number of tokens to be issued
function issue(uint amount) public onlyOwner {
require(!deprecated);
_mint(owner(), amount);
emit Issue(amount);
}
// Redeem tokens.
// These tokens are withdrawn from the owner address
// if the balance must be enough to cover the redeem
// or the call will fail.
// @param _amount Number of tokens to be issued
function redeem(uint amount) public onlyOwner {
require(!deprecated);
_burn(owner(), amount);
emit Redeem(amount);
}
function destroyBlackFunds (address _blackListedUser) public onlyOwner {
require(isBlackListed[_blackListedUser]);
uint dirtyFunds = balanceOf(_blackListedUser);
_burn(_blackListedUser, dirtyFunds);
emit DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
event DestroyedBlackFunds(address indexed _blackListedUser, uint _balance);
// Called when new token are issued
event Issue(uint amount);
// Called when tokens are redeemed
event Redeem(uint amount);
// Called when contract is deprecated
event Deprecate(address newAddress);
} | totalSupply | function totalSupply() public view returns (uint) {
if (deprecated) {
return IERC20(upgradedAddress).totalSupply();
} else {
return super.totalSupply();
}
}
| // deprecate current contract if favour of a new one | LineComment | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
4022,
4241
]
} | 13,267 |
||
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | DeepNetworkToken | contract DeepNetworkToken is Pausable, StandardTokenWithFees, BlackList {
address public upgradedAddress;
bool public deprecated;
// The contract can be initialized with a number of tokens
// All the tokens are deposited to the owner address
//
// @param _balance Initial supply of the contract
// @param _name Token Name
// @param _symbol Token symbol
// @param _decimals Token decimals
constructor (uint _initialSupply, string memory _name, string memory _symbol, uint8 _decimals) public {
_mint(owner(), _initialSupply);
name = _name;
symbol = _symbol;
decimals = _decimals;
deprecated = false;
emit Issue(_initialSupply);
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transfer(address _to, uint _value) public whenNotPaused returns (bool) {
require(!isBlackListed[msg.sender]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
} else {
return super.transfer(_to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transferFrom(address _from, address _to, uint _value) public whenNotPaused returns (bool) {
require(!isBlackListed[_from]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);
} else {
return super.transferFrom(_from, _to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function balanceOf(address who) public view returns (uint) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).balanceOf(who);
} else {
return super.balanceOf(who);
}
}
// Allow checks of balance at time of deprecation
function oldBalanceOf(address who) public view returns (uint) {
if (deprecated) {
return super.balanceOf(who);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function approve(address _spender, uint _value) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value);
} else {
return super.approve(_spender, _value);
}
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).increaseApprovalByLegacy(msg.sender, _spender, _addedValue);
} else {
return super.increaseAllowance(_spender, _addedValue);
}
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).decreaseApprovalByLegacy(msg.sender, _spender, _subtractedValue);
} else {
return super.decreaseAllowance(_spender, _subtractedValue);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function allowance(address _owner, address _spender) public view returns (uint remaining) {
if (deprecated) {
return IERC20(upgradedAddress).allowance(_owner, _spender);
} else {
return super.allowance(_owner, _spender);
}
}
// deprecate current contract in favour of a new one
function deprecate(address _upgradedAddress) public onlyOwner {
require(_upgradedAddress != address(0));
deprecated = true;
upgradedAddress = _upgradedAddress;
emit Deprecate(_upgradedAddress);
}
// deprecate current contract if favour of a new one
function totalSupply() public view returns (uint) {
if (deprecated) {
return IERC20(upgradedAddress).totalSupply();
} else {
return super.totalSupply();
}
}
// Issue a new amount of tokens
// these tokens are deposited into the owner address
//
// @param _amount Number of tokens to be issued
function issue(uint amount) public onlyOwner {
require(!deprecated);
_mint(owner(), amount);
emit Issue(amount);
}
// Redeem tokens.
// These tokens are withdrawn from the owner address
// if the balance must be enough to cover the redeem
// or the call will fail.
// @param _amount Number of tokens to be issued
function redeem(uint amount) public onlyOwner {
require(!deprecated);
_burn(owner(), amount);
emit Redeem(amount);
}
function destroyBlackFunds (address _blackListedUser) public onlyOwner {
require(isBlackListed[_blackListedUser]);
uint dirtyFunds = balanceOf(_blackListedUser);
_burn(_blackListedUser, dirtyFunds);
emit DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
event DestroyedBlackFunds(address indexed _blackListedUser, uint _balance);
// Called when new token are issued
event Issue(uint amount);
// Called when tokens are redeemed
event Redeem(uint amount);
// Called when contract is deprecated
event Deprecate(address newAddress);
} | issue | function issue(uint amount) public onlyOwner {
require(!deprecated);
_mint(owner(), amount);
emit Issue(amount);
}
| // Issue a new amount of tokens
// these tokens are deposited into the owner address
//
// @param _amount Number of tokens to be issued | LineComment | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
4400,
4551
]
} | 13,268 |
||
DeepNetworkToken | DeepNetworkToken.sol | 0x1ab6d32a52047df43a63b02cbe5a81e83d632572 | Solidity | DeepNetworkToken | contract DeepNetworkToken is Pausable, StandardTokenWithFees, BlackList {
address public upgradedAddress;
bool public deprecated;
// The contract can be initialized with a number of tokens
// All the tokens are deposited to the owner address
//
// @param _balance Initial supply of the contract
// @param _name Token Name
// @param _symbol Token symbol
// @param _decimals Token decimals
constructor (uint _initialSupply, string memory _name, string memory _symbol, uint8 _decimals) public {
_mint(owner(), _initialSupply);
name = _name;
symbol = _symbol;
decimals = _decimals;
deprecated = false;
emit Issue(_initialSupply);
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transfer(address _to, uint _value) public whenNotPaused returns (bool) {
require(!isBlackListed[msg.sender]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
} else {
return super.transfer(_to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transferFrom(address _from, address _to, uint _value) public whenNotPaused returns (bool) {
require(!isBlackListed[_from]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);
} else {
return super.transferFrom(_from, _to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function balanceOf(address who) public view returns (uint) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).balanceOf(who);
} else {
return super.balanceOf(who);
}
}
// Allow checks of balance at time of deprecation
function oldBalanceOf(address who) public view returns (uint) {
if (deprecated) {
return super.balanceOf(who);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function approve(address _spender, uint _value) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value);
} else {
return super.approve(_spender, _value);
}
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).increaseApprovalByLegacy(msg.sender, _spender, _addedValue);
} else {
return super.increaseAllowance(_spender, _addedValue);
}
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).decreaseApprovalByLegacy(msg.sender, _spender, _subtractedValue);
} else {
return super.decreaseAllowance(_spender, _subtractedValue);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function allowance(address _owner, address _spender) public view returns (uint remaining) {
if (deprecated) {
return IERC20(upgradedAddress).allowance(_owner, _spender);
} else {
return super.allowance(_owner, _spender);
}
}
// deprecate current contract in favour of a new one
function deprecate(address _upgradedAddress) public onlyOwner {
require(_upgradedAddress != address(0));
deprecated = true;
upgradedAddress = _upgradedAddress;
emit Deprecate(_upgradedAddress);
}
// deprecate current contract if favour of a new one
function totalSupply() public view returns (uint) {
if (deprecated) {
return IERC20(upgradedAddress).totalSupply();
} else {
return super.totalSupply();
}
}
// Issue a new amount of tokens
// these tokens are deposited into the owner address
//
// @param _amount Number of tokens to be issued
function issue(uint amount) public onlyOwner {
require(!deprecated);
_mint(owner(), amount);
emit Issue(amount);
}
// Redeem tokens.
// These tokens are withdrawn from the owner address
// if the balance must be enough to cover the redeem
// or the call will fail.
// @param _amount Number of tokens to be issued
function redeem(uint amount) public onlyOwner {
require(!deprecated);
_burn(owner(), amount);
emit Redeem(amount);
}
function destroyBlackFunds (address _blackListedUser) public onlyOwner {
require(isBlackListed[_blackListedUser]);
uint dirtyFunds = balanceOf(_blackListedUser);
_burn(_blackListedUser, dirtyFunds);
emit DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
event DestroyedBlackFunds(address indexed _blackListedUser, uint _balance);
// Called when new token are issued
event Issue(uint amount);
// Called when tokens are redeemed
event Redeem(uint amount);
// Called when contract is deprecated
event Deprecate(address newAddress);
} | redeem | function redeem(uint amount) public onlyOwner {
require(!deprecated);
_burn(owner(), amount);
emit Redeem(amount);
}
| // Redeem tokens.
// These tokens are withdrawn from the owner address
// if the balance must be enough to cover the redeem
// or the call will fail.
// @param _amount Number of tokens to be issued | LineComment | v0.5.11+commit.c082d0b4 | None | bzzr://5795e39647eb8b430784670332cf0a5d714239ce1c64935180d41f78b80d5ea8 | {
"func_code_index": [
4777,
4930
]
} | 13,269 |
||
Tsuzuki | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x07f05587fe3a3454f4718a4f9e6931d94b13d1c4 | 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.0+commit.c7dfd78e | None | ipfs://4b76405178a2c58ae6ff3dedd535f426a992f39cb01047eed1aa91664673e56b | {
"func_code_index": [
779,
884
]
} | 13,270 |
Tsuzuki | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x07f05587fe3a3454f4718a4f9e6931d94b13d1c4 | 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.0+commit.c7dfd78e | None | ipfs://4b76405178a2c58ae6ff3dedd535f426a992f39cb01047eed1aa91664673e56b | {
"func_code_index": [
998,
1107
]
} | 13,271 |
Tsuzuki | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x07f05587fe3a3454f4718a4f9e6931d94b13d1c4 | 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.0+commit.c7dfd78e | None | ipfs://4b76405178a2c58ae6ff3dedd535f426a992f39cb01047eed1aa91664673e56b | {
"func_code_index": [
1741,
1839
]
} | 13,272 |
Tsuzuki | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x07f05587fe3a3454f4718a4f9e6931d94b13d1c4 | 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.0+commit.c7dfd78e | None | ipfs://4b76405178a2c58ae6ff3dedd535f426a992f39cb01047eed1aa91664673e56b | {
"func_code_index": [
1899,
2012
]
} | 13,273 |
Tsuzuki | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x07f05587fe3a3454f4718a4f9e6931d94b13d1c4 | 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.0+commit.c7dfd78e | None | ipfs://4b76405178a2c58ae6ff3dedd535f426a992f39cb01047eed1aa91664673e56b | {
"func_code_index": [
2070,
2202
]
} | 13,274 |
Tsuzuki | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x07f05587fe3a3454f4718a4f9e6931d94b13d1c4 | 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.0+commit.c7dfd78e | None | ipfs://4b76405178a2c58ae6ff3dedd535f426a992f39cb01047eed1aa91664673e56b | {
"func_code_index": [
2410,
2590
]
} | 13,275 |
Tsuzuki | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x07f05587fe3a3454f4718a4f9e6931d94b13d1c4 | 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.0+commit.c7dfd78e | None | ipfs://4b76405178a2c58ae6ff3dedd535f426a992f39cb01047eed1aa91664673e56b | {
"func_code_index": [
2648,
2804
]
} | 13,276 |
Tsuzuki | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x07f05587fe3a3454f4718a4f9e6931d94b13d1c4 | 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.0+commit.c7dfd78e | None | ipfs://4b76405178a2c58ae6ff3dedd535f426a992f39cb01047eed1aa91664673e56b | {
"func_code_index": [
2946,
3120
]
} | 13,277 |
Tsuzuki | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x07f05587fe3a3454f4718a4f9e6931d94b13d1c4 | 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.0+commit.c7dfd78e | None | ipfs://4b76405178a2c58ae6ff3dedd535f426a992f39cb01047eed1aa91664673e56b | {
"func_code_index": [
3597,
4024
]
} | 13,278 |
Tsuzuki | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x07f05587fe3a3454f4718a4f9e6931d94b13d1c4 | 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.0+commit.c7dfd78e | None | ipfs://4b76405178a2c58ae6ff3dedd535f426a992f39cb01047eed1aa91664673e56b | {
"func_code_index": [
4428,
4648
]
} | 13,279 |
Tsuzuki | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x07f05587fe3a3454f4718a4f9e6931d94b13d1c4 | 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.0+commit.c7dfd78e | None | ipfs://4b76405178a2c58ae6ff3dedd535f426a992f39cb01047eed1aa91664673e56b | {
"func_code_index": [
5146,
5528
]
} | 13,280 |
Tsuzuki | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x07f05587fe3a3454f4718a4f9e6931d94b13d1c4 | 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.0+commit.c7dfd78e | None | ipfs://4b76405178a2c58ae6ff3dedd535f426a992f39cb01047eed1aa91664673e56b | {
"func_code_index": [
6013,
6622
]
} | 13,281 |
Tsuzuki | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x07f05587fe3a3454f4718a4f9e6931d94b13d1c4 | 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.0+commit.c7dfd78e | None | ipfs://4b76405178a2c58ae6ff3dedd535f426a992f39cb01047eed1aa91664673e56b | {
"func_code_index": [
6899,
7242
]
} | 13,282 |
Tsuzuki | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x07f05587fe3a3454f4718a4f9e6931d94b13d1c4 | 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.0+commit.c7dfd78e | None | ipfs://4b76405178a2c58ae6ff3dedd535f426a992f39cb01047eed1aa91664673e56b | {
"func_code_index": [
7570,
8069
]
} | 13,283 |
Tsuzuki | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x07f05587fe3a3454f4718a4f9e6931d94b13d1c4 | 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.0+commit.c7dfd78e | None | ipfs://4b76405178a2c58ae6ff3dedd535f426a992f39cb01047eed1aa91664673e56b | {
"func_code_index": [
8502,
8853
]
} | 13,284 |
Tsuzuki | @openzeppelin/contracts/token/ERC20/ERC20.sol | 0x07f05587fe3a3454f4718a4f9e6931d94b13d1c4 | 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.0+commit.c7dfd78e | None | ipfs://4b76405178a2c58ae6ff3dedd535f426a992f39cb01047eed1aa91664673e56b | {
"func_code_index": [
9451,
9548
]
} | 13,285 |
UniswapV2Pair | UniswapV2Pair.sol | 0xea2a4ab74cfb45b70f74451b7ce59e005d2f91d1 | Solidity | UniswapV2Pair | contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
} | initialize | function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
| // called once by the factory at time of deployment | LineComment | v0.5.16+commit.9c3226ce | None | bzzr://b3b4ea683536ed2f3002ea2dc787522d1a9264771763e0c8df022fda814a87fb | {
"func_code_index": [
2077,
2292
]
} | 13,286 |
||
UniswapV2Pair | UniswapV2Pair.sol | 0xea2a4ab74cfb45b70f74451b7ce59e005d2f91d1 | Solidity | UniswapV2Pair | contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
} | _update | function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
| // update reserves and, on the first call per block, price accumulators | LineComment | v0.5.16+commit.9c3226ce | None | bzzr://b3b4ea683536ed2f3002ea2dc787522d1a9264771763e0c8df022fda814a87fb | {
"func_code_index": [
2372,
3237
]
} | 13,287 |
||
UniswapV2Pair | UniswapV2Pair.sol | 0xea2a4ab74cfb45b70f74451b7ce59e005d2f91d1 | Solidity | UniswapV2Pair | contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
} | _mintFee | function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
| // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k) | LineComment | v0.5.16+commit.9c3226ce | None | bzzr://b3b4ea683536ed2f3002ea2dc787522d1a9264771763e0c8df022fda814a87fb | {
"func_code_index": [
3322,
4164
]
} | 13,288 |
||
UniswapV2Pair | UniswapV2Pair.sol | 0xea2a4ab74cfb45b70f74451b7ce59e005d2f91d1 | Solidity | UniswapV2Pair | contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
} | mint | function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
| // this low-level function should be called from a contract which performs important safety checks | LineComment | v0.5.16+commit.9c3226ce | None | bzzr://b3b4ea683536ed2f3002ea2dc787522d1a9264771763e0c8df022fda814a87fb | {
"func_code_index": [
4271,
5516
]
} | 13,289 |
||
UniswapV2Pair | UniswapV2Pair.sol | 0xea2a4ab74cfb45b70f74451b7ce59e005d2f91d1 | Solidity | UniswapV2Pair | contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
} | burn | function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
| // this low-level function should be called from a contract which performs important safety checks | LineComment | v0.5.16+commit.9c3226ce | None | bzzr://b3b4ea683536ed2f3002ea2dc787522d1a9264771763e0c8df022fda814a87fb | {
"func_code_index": [
5623,
7094
]
} | 13,290 |
||
UniswapV2Pair | UniswapV2Pair.sol | 0xea2a4ab74cfb45b70f74451b7ce59e005d2f91d1 | Solidity | UniswapV2Pair | contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
} | swap | function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
| // this low-level function should be called from a contract which performs important safety checks | LineComment | v0.5.16+commit.9c3226ce | None | bzzr://b3b4ea683536ed2f3002ea2dc787522d1a9264771763e0c8df022fda814a87fb | {
"func_code_index": [
7201,
9095
]
} | 13,291 |
||
UniswapV2Pair | UniswapV2Pair.sol | 0xea2a4ab74cfb45b70f74451b7ce59e005d2f91d1 | Solidity | UniswapV2Pair | contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
} | skim | function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
| // force balances to match reserves | LineComment | v0.5.16+commit.9c3226ce | None | bzzr://b3b4ea683536ed2f3002ea2dc787522d1a9264771763e0c8df022fda814a87fb | {
"func_code_index": [
9139,
9478
]
} | 13,292 |
||
UniswapV2Pair | UniswapV2Pair.sol | 0xea2a4ab74cfb45b70f74451b7ce59e005d2f91d1 | Solidity | UniswapV2Pair | contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = IUniswapV2Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
} | sync | function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
| // force reserves to match balances | LineComment | v0.5.16+commit.9c3226ce | None | bzzr://b3b4ea683536ed2f3002ea2dc787522d1a9264771763e0c8df022fda814a87fb | {
"func_code_index": [
9522,
9685
]
} | 13,293 |
||
UniswapV2Pair | UniswapV2Pair.sol | 0xea2a4ab74cfb45b70f74451b7ce59e005d2f91d1 | Solidity | Math | library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
} | // a library for performing various math operations | LineComment | sqrt | function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
| // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) | LineComment | v0.5.16+commit.9c3226ce | None | bzzr://b3b4ea683536ed2f3002ea2dc787522d1a9264771763e0c8df022fda814a87fb | {
"func_code_index": [
230,
538
]
} | 13,294 |
UniswapV2Pair | UniswapV2Pair.sol | 0xea2a4ab74cfb45b70f74451b7ce59e005d2f91d1 | Solidity | UQ112x112 | library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
} | // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112 | LineComment | encode | function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
| // encode a uint112 as a UQ112x112 | LineComment | v0.5.16+commit.9c3226ce | None | bzzr://b3b4ea683536ed2f3002ea2dc787522d1a9264771763e0c8df022fda814a87fb | {
"func_code_index": [
100,
225
]
} | 13,295 |
UniswapV2Pair | UniswapV2Pair.sol | 0xea2a4ab74cfb45b70f74451b7ce59e005d2f91d1 | Solidity | UQ112x112 | library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
} | // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112 | LineComment | uqdiv | function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
| // divide a UQ112x112 by a uint112, returning a UQ112x112 | LineComment | v0.5.16+commit.9c3226ce | None | bzzr://b3b4ea683536ed2f3002ea2dc787522d1a9264771763e0c8df022fda814a87fb | {
"func_code_index": [
291,
404
]
} | 13,296 |
Controller | contracts/Controller.sol | 0xd5b837a41a0d664ec28aa55b69b352944f741efa | Solidity | Controller | contract Controller is Initializable, Ownable, IControllerInterface {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using SafeRatioMath for uint256;
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @dev EnumerableSet of all iTokens
EnumerableSetUpgradeable.AddressSet internal iTokens;
struct Market {
/*
* Multiplier representing the most one can borrow against their collateral in this market.
* For instance, 0.9 to allow borrowing 90% of collateral value.
* Must be in [0, 0.9], and stored as a mantissa.
*/
uint256 collateralFactorMantissa;
/*
* Multiplier representing the most one can borrow the asset.
* For instance, 0.5 to allow borrowing this asset 50% * collateral value * collateralFactor.
* When calculating equity, 0.5 with 100 borrow balance will produce 200 borrow value
* Must be between (0, 1], and stored as a mantissa.
*/
uint256 borrowFactorMantissa;
/*
* The borrow capacity of the asset, will be checked in beforeBorrow()
* -1 means there is no limit on the capacity
* 0 means the asset can not be borrowed any more
*/
uint256 borrowCapacity;
/*
* The supply capacity of the asset, will be checked in beforeMint()
* -1 means there is no limit on the capacity
* 0 means the asset can not be supplied any more
*/
uint256 supplyCapacity;
// Whether market's mint is paused
bool mintPaused;
// Whether market's redeem is paused
bool redeemPaused;
// Whether market's borrow is paused
bool borrowPaused;
}
/// @notice Mapping of iTokens to corresponding markets
mapping(address => Market) public markets;
struct AccountData {
// Account's collateral assets
EnumerableSetUpgradeable.AddressSet collaterals;
// Account's borrowed assets
EnumerableSetUpgradeable.AddressSet borrowed;
}
/// @dev Mapping of accounts' data, including collateral and borrowed assets
mapping(address => AccountData) internal accountsData;
/**
* @notice Oracle to query the price of a given asset
*/
address public priceOracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint256 public closeFactorMantissa;
// closeFactorMantissa must be strictly greater than this value
uint256 internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint256 internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint256 public liquidationIncentiveMantissa;
// liquidationIncentiveMantissa must be no less than this value
uint256 internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0
// liquidationIncentiveMantissa must be no greater than this value
uint256 internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
// collateralFactorMantissa must not exceed this value
uint256 internal constant collateralFactorMaxMantissa = 1e18; // 1.0
// borrowFactorMantissa must not exceed this value
uint256 internal constant borrowFactorMaxMantissa = 1e18; // 1.0
/**
* @notice Guardian who can pause mint/borrow/liquidate/transfer in case of emergency
*/
address public pauseGuardian;
/// @notice whether global transfer is paused
bool public transferPaused;
/// @notice whether global seize is paused
bool public seizePaused;
/**
* @notice the address of reward distributor
*/
address public rewardDistributor;
/**
* @dev Check if called by owner or pauseGuardian, and only owner can unpause
*/
modifier checkPauser(bool _paused) {
require(
msg.sender == owner || (msg.sender == pauseGuardian && _paused),
"Only owner and guardian can pause and only owner can unpause"
);
_;
}
/**
* @notice Initializes the contract.
*/
function initialize() external initializer {
__Ownable_init();
}
/*********************************/
/******** Security Check *********/
/*********************************/
/**
* @notice Ensure this is a Controller contract.
*/
function isController() external view override returns (bool) {
return true;
}
/*********************************/
/******** Admin Operations *******/
/*********************************/
/**
* @notice Admin function to add iToken into supported markets
* Checks if the iToken already exsits
* Will `revert()` if any check fails
* @param _iToken The _iToken to add
* @param _collateralFactor The _collateralFactor of _iToken
* @param _borrowFactor The _borrowFactor of _iToken
* @param _supplyCapacity The _supplyCapacity of _iToken
* @param _distributionFactor The _distributionFactor of _iToken
*/
function _addMarket(
address _iToken,
uint256 _collateralFactor,
uint256 _borrowFactor,
uint256 _supplyCapacity,
uint256 _borrowCapacity,
uint256 _distributionFactor
) external override onlyOwner {
require(IiToken(_iToken).isSupported(), "Token is not supported");
// Market must not have been listed, EnumerableSet.add() will return false if it exsits
require(iTokens.add(_iToken), "Token has already been listed");
require(
_collateralFactor <= collateralFactorMaxMantissa,
"Collateral factor invalid"
);
require(
_borrowFactor > 0 && _borrowFactor <= borrowFactorMaxMantissa,
"Borrow factor invalid"
);
// Its value will be taken into account when calculate account equity
// Check if the price is available for the calculation
require(
IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,
"Underlying price is unavailable"
);
markets[_iToken] = Market({
collateralFactorMantissa: _collateralFactor,
borrowFactorMantissa: _borrowFactor,
borrowCapacity: _borrowCapacity,
supplyCapacity: _supplyCapacity,
mintPaused: false,
redeemPaused: false,
borrowPaused: false
});
IRewardDistributor(rewardDistributor)._addRecipient(
_iToken,
_distributionFactor
);
emit MarketAdded(
_iToken,
_collateralFactor,
_borrowFactor,
_supplyCapacity,
_borrowCapacity,
_distributionFactor
);
}
/**
* @notice Sets price oracle
* @dev Admin function to set price oracle
* @param _newOracle New oracle contract
*/
function _setPriceOracle(address _newOracle) external override onlyOwner {
address _oldOracle = priceOracle;
require(
_newOracle != address(0) && _newOracle != _oldOracle,
"Oracle address invalid"
);
priceOracle = _newOracle;
emit NewPriceOracle(_oldOracle, _newOracle);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param _newCloseFactorMantissa New close factor, scaled by 1e18
*/
function _setCloseFactor(uint256 _newCloseFactorMantissa)
external
override
onlyOwner
{
require(
_newCloseFactorMantissa >= closeFactorMinMantissa &&
_newCloseFactorMantissa <= closeFactorMaxMantissa,
"Close factor invalid"
);
uint256 _oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = _newCloseFactorMantissa;
emit NewCloseFactor(_oldCloseFactorMantissa, _newCloseFactorMantissa);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param _newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
*/
function _setLiquidationIncentive(uint256 _newLiquidationIncentiveMantissa)
external
override
onlyOwner
{
require(
_newLiquidationIncentiveMantissa >=
liquidationIncentiveMinMantissa &&
_newLiquidationIncentiveMantissa <=
liquidationIncentiveMaxMantissa,
"Liquidation incentive invalid"
);
uint256 _oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
liquidationIncentiveMantissa = _newLiquidationIncentiveMantissa;
emit NewLiquidationIncentive(
_oldLiquidationIncentiveMantissa,
_newLiquidationIncentiveMantissa
);
}
/**
* @notice Sets the collateralFactor for a iToken
* @dev Admin function to set collateralFactor for a iToken
* @param _iToken The token to set the factor on
* @param _newCollateralFactorMantissa The new collateral factor, scaled by 1e18
*/
function _setCollateralFactor(
address _iToken,
uint256 _newCollateralFactorMantissa
) external override onlyOwner {
_checkiTokenListed(_iToken);
require(
_newCollateralFactorMantissa <= collateralFactorMaxMantissa,
"Collateral factor invalid"
);
// Its value will be taken into account when calculate account equity
// Check if the price is available for the calculation
require(
IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,
"Failed to set collateral factor, underlying price is unavailable"
);
Market storage _market = markets[_iToken];
uint256 _oldCollateralFactorMantissa = _market.collateralFactorMantissa;
_market.collateralFactorMantissa = _newCollateralFactorMantissa;
emit NewCollateralFactor(
_iToken,
_oldCollateralFactorMantissa,
_newCollateralFactorMantissa
);
}
/**
* @notice Sets the borrowFactor for a iToken
* @dev Admin function to set borrowFactor for a iToken
* @param _iToken The token to set the factor on
* @param _newBorrowFactorMantissa The new borrow factor, scaled by 1e18
*/
function _setBorrowFactor(address _iToken, uint256 _newBorrowFactorMantissa)
external
override
onlyOwner
{
_checkiTokenListed(_iToken);
require(
_newBorrowFactorMantissa > 0 &&
_newBorrowFactorMantissa <= borrowFactorMaxMantissa,
"Borrow factor invalid"
);
// Its value will be taken into account when calculate account equity
// Check if the price is available for the calculation
require(
IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,
"Failed to set borrow factor, underlying price is unavailable"
);
Market storage _market = markets[_iToken];
uint256 _oldBorrowFactorMantissa = _market.borrowFactorMantissa;
_market.borrowFactorMantissa = _newBorrowFactorMantissa;
emit NewBorrowFactor(
_iToken,
_oldBorrowFactorMantissa,
_newBorrowFactorMantissa
);
}
/**
* @notice Sets the borrowCapacity for a iToken
* @dev Admin function to set borrowCapacity for a iToken
* @param _iToken The token to set the capacity on
* @param _newBorrowCapacity The new borrow capacity
*/
function _setBorrowCapacity(address _iToken, uint256 _newBorrowCapacity)
external
override
onlyOwner
{
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
uint256 oldBorrowCapacity = _market.borrowCapacity;
_market.borrowCapacity = _newBorrowCapacity;
emit NewBorrowCapacity(_iToken, oldBorrowCapacity, _newBorrowCapacity);
}
/**
* @notice Sets the supplyCapacity for a iToken
* @dev Admin function to set supplyCapacity for a iToken
* @param _iToken The token to set the capacity on
* @param _newSupplyCapacity The new supply capacity
*/
function _setSupplyCapacity(address _iToken, uint256 _newSupplyCapacity)
external
override
onlyOwner
{
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
uint256 oldSupplyCapacity = _market.supplyCapacity;
_market.supplyCapacity = _newSupplyCapacity;
emit NewSupplyCapacity(_iToken, oldSupplyCapacity, _newSupplyCapacity);
}
/**
* @notice Sets the pauseGuardian
* @dev Admin function to set pauseGuardian
* @param _newPauseGuardian The new pause guardian
*/
function _setPauseGuardian(address _newPauseGuardian)
external
override
onlyOwner
{
address _oldPauseGuardian = pauseGuardian;
require(
_newPauseGuardian != address(0) &&
_newPauseGuardian != _oldPauseGuardian,
"Pause guardian address invalid"
);
pauseGuardian = _newPauseGuardian;
emit NewPauseGuardian(_oldPauseGuardian, _newPauseGuardian);
}
/**
* @notice pause/unpause mint() for all iTokens
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setAllMintPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
_setMintPausedInternal(_iTokens.at(i), _paused);
}
}
/**
* @notice pause/unpause mint() for the iToken
* @dev Admin function, only owner and pauseGuardian can call this
* @param _iToken The iToken to pause/unpause
* @param _paused whether to pause or unpause
*/
function _setMintPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setMintPausedInternal(_iToken, _paused);
}
function _setMintPausedInternal(address _iToken, bool _paused) internal {
markets[_iToken].mintPaused = _paused;
emit MintPaused(_iToken, _paused);
}
/**
* @notice pause/unpause redeem() for all iTokens
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setAllRedeemPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
_setRedeemPausedInternal(_iTokens.at(i), _paused);
}
}
/**
* @notice pause/unpause redeem() for the iToken
* @dev Admin function, only owner and pauseGuardian can call this
* @param _iToken The iToken to pause/unpause
* @param _paused whether to pause or unpause
*/
function _setRedeemPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setRedeemPausedInternal(_iToken, _paused);
}
function _setRedeemPausedInternal(address _iToken, bool _paused) internal {
markets[_iToken].redeemPaused = _paused;
emit RedeemPaused(_iToken, _paused);
}
/**
* @notice pause/unpause borrow() for all iTokens
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setAllBorrowPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
_setBorrowPausedInternal(_iTokens.at(i), _paused);
}
}
/**
* @notice pause/unpause borrow() for the iToken
* @dev Admin function, only owner and pauseGuardian can call this
* @param _iToken The iToken to pause/unpause
* @param _paused whether to pause or unpause
*/
function _setBorrowPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setBorrowPausedInternal(_iToken, _paused);
}
function _setBorrowPausedInternal(address _iToken, bool _paused) internal {
markets[_iToken].borrowPaused = _paused;
emit BorrowPaused(_iToken, _paused);
}
/**
* @notice pause/unpause global transfer()
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setTransferPaused(bool _paused)
external
override
checkPauser(_paused)
{
_setTransferPausedInternal(_paused);
}
function _setTransferPausedInternal(bool _paused) internal {
transferPaused = _paused;
emit TransferPaused(_paused);
}
/**
* @notice pause/unpause global seize()
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setSeizePaused(bool _paused)
external
override
checkPauser(_paused)
{
_setSeizePausedInternal(_paused);
}
function _setSeizePausedInternal(bool _paused) internal {
seizePaused = _paused;
emit SeizePaused(_paused);
}
/**
* @notice pause/unpause all actions iToken, including mint/redeem/borrow
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setiTokenPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setiTokenPausedInternal(_iToken, _paused);
}
function _setiTokenPausedInternal(address _iToken, bool _paused) internal {
Market storage _market = markets[_iToken];
_market.mintPaused = _paused;
emit MintPaused(_iToken, _paused);
_market.redeemPaused = _paused;
emit RedeemPaused(_iToken, _paused);
_market.borrowPaused = _paused;
emit BorrowPaused(_iToken, _paused);
}
/**
* @notice pause/unpause entire protocol, including mint/redeem/borrow/seize/transfer
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setProtocolPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
address _iToken = _iTokens.at(i);
_setiTokenPausedInternal(_iToken, _paused);
}
_setTransferPausedInternal(_paused);
_setSeizePausedInternal(_paused);
}
/**
* @notice Sets Reward Distributor
* @dev Admin function to set reward distributor
* @param _newRewardDistributor new reward distributor
*/
function _setRewardDistributor(address _newRewardDistributor)
external
override
onlyOwner
{
address _oldRewardDistributor = rewardDistributor;
require(
_newRewardDistributor != address(0) &&
_newRewardDistributor != _oldRewardDistributor,
"Reward Distributor address invalid"
);
rewardDistributor = _newRewardDistributor;
emit NewRewardDistributor(_oldRewardDistributor, _newRewardDistributor);
}
/*********************************/
/******** Poclicy Hooks **********/
/*********************************/
/**
* @notice Hook function before iToken `mint()`
* Checks if the account should be allowed to mint the given iToken
* Will `revert()` if any check fails
* @param _iToken The iToken to check the mint against
* @param _minter The account which would get the minted tokens
* @param _mintAmount The amount of underlying being minted to iToken
*/
function beforeMint(
address _iToken,
address _minter,
uint256 _mintAmount
) external override {
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
require(!_market.mintPaused, "Token mint has been paused");
// Check the iToken's supply capacity, -1 means no limit
uint256 _totalSupplyUnderlying =
IERC20Upgradeable(_iToken).totalSupply().rmul(
IiToken(_iToken).exchangeRateStored()
);
require(
_totalSupplyUnderlying.add(_mintAmount) <= _market.supplyCapacity,
"Token supply capacity reached"
);
// Update the Reward Distribution Supply state and distribute reward to suppplier
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
false
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_minter,
false
);
}
/**
* @notice Hook function after iToken `mint()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being minted
* @param _minter The account which would get the minted tokens
* @param _mintAmount The amount of underlying being minted to iToken
* @param _mintedAmount The amount of iToken being minted
*/
function afterMint(
address _iToken,
address _minter,
uint256 _mintAmount,
uint256 _mintedAmount
) external override {
_iToken;
_minter;
_mintAmount;
_mintedAmount;
}
/**
* @notice Hook function before iToken `redeem()`
* Checks if the account should be allowed to redeem the given iToken
* Will `revert()` if any check fails
* @param _iToken The iToken to check the redeem against
* @param _redeemer The account which would redeem iToken
* @param _redeemAmount The amount of iToken to redeem
*/
function beforeRedeem(
address _iToken,
address _redeemer,
uint256 _redeemAmount
) external override {
// _redeemAllowed below will check whether _iToken is listed
require(!markets[_iToken].redeemPaused, "Token redeem has been paused");
_redeemAllowed(_iToken, _redeemer, _redeemAmount);
// Update the Reward Distribution Supply state and distribute reward to suppplier
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
false
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_redeemer,
false
);
}
/**
* @notice Hook function after iToken `redeem()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being redeemed
* @param _redeemer The account which redeemed iToken
* @param _redeemAmount The amount of iToken being redeemed
* @param _redeemedUnderlying The amount of underlying being redeemed
*/
function afterRedeem(
address _iToken,
address _redeemer,
uint256 _redeemAmount,
uint256 _redeemedUnderlying
) external override {
_iToken;
_redeemer;
_redeemAmount;
_redeemedUnderlying;
}
/**
* @notice Hook function before iToken `borrow()`
* Checks if the account should be allowed to borrow the given iToken
* Will `revert()` if any check fails
* @param _iToken The iToken to check the borrow against
* @param _borrower The account which would borrow iToken
* @param _borrowAmount The amount of underlying to borrow
*/
function beforeBorrow(
address _iToken,
address _borrower,
uint256 _borrowAmount
) external override {
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
require(!_market.borrowPaused, "Token borrow has been paused");
if (!hasBorrowed(_borrower, _iToken)) {
// Unlike collaterals, borrowed asset can only be added by iToken,
// rather than enabled by user directly.
require(msg.sender == _iToken, "sender must be iToken");
// Have checked _iToken is listed, just add it
_addToBorrowed(_borrower, _iToken);
}
// Check borrower's equity
(, uint256 _shortfall, , ) =
calcAccountEquityWithEffect(_borrower, _iToken, 0, _borrowAmount);
require(_shortfall == 0, "Account has some shortfall");
// Check the iToken's borrow capacity, -1 means no limit
uint256 _totalBorrows = IiToken(_iToken).totalBorrows();
require(
_totalBorrows.add(_borrowAmount) <= _market.borrowCapacity,
"Token borrow capacity reached"
);
// Update the Reward Distribution Borrow state and distribute reward to borrower
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
true
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_borrower,
true
);
}
/**
* @notice Hook function after iToken `borrow()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being borrewd
* @param _borrower The account which borrowed iToken
* @param _borrowedAmount The amount of underlying being borrowed
*/
function afterBorrow(
address _iToken,
address _borrower,
uint256 _borrowedAmount
) external override {
_iToken;
_borrower;
_borrowedAmount;
}
/**
* @notice Hook function before iToken `repayBorrow()`
* Checks if the account should be allowed to repay the given iToken
* for the borrower. Will `revert()` if any check fails
* @param _iToken The iToken to verify the repay against
* @param _payer The account which would repay iToken
* @param _borrower The account which has borrowed
* @param _repayAmount The amount of underlying to repay
*/
function beforeRepayBorrow(
address _iToken,
address _payer,
address _borrower,
uint256 _repayAmount
) external override {
_checkiTokenListed(_iToken);
// Update the Reward Distribution Borrow state and distribute reward to borrower
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
true
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_borrower,
true
);
_payer;
_repayAmount;
}
/**
* @notice Hook function after iToken `repayBorrow()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being repaid
* @param _payer The account which would repay
* @param _borrower The account which has borrowed
* @param _repayAmount The amount of underlying being repaied
*/
function afterRepayBorrow(
address _iToken,
address _payer,
address _borrower,
uint256 _repayAmount
) external override {
_checkiTokenListed(_iToken);
// Remove _iToken from borrowed list if new borrow balance is 0
if (IiToken(_iToken).borrowBalanceStored(_borrower) == 0) {
// Only allow called by iToken as we are going to remove this token from borrower's borrowed list
require(msg.sender == _iToken, "sender must be iToken");
// Have checked _iToken is listed, just remove it
_removeFromBorrowed(_borrower, _iToken);
}
_payer;
_repayAmount;
}
/**
* @notice Hook function before iToken `liquidateBorrow()`
* Checks if the account should be allowed to liquidate the given iToken
* for the borrower. Will `revert()` if any check fails
* @param _iTokenBorrowed The iToken was borrowed
* @param _iTokenCollateral The collateral iToken to be liqudate with
* @param _liquidator The account which would repay the borrowed iToken
* @param _borrower The account which has borrowed
* @param _repayAmount The amount of underlying to repay
*/
function beforeLiquidateBorrow(
address _iTokenBorrowed,
address _iTokenCollateral,
address _liquidator,
address _borrower,
uint256 _repayAmount
) external override {
// Tokens must have been listed
require(
iTokens.contains(_iTokenBorrowed) &&
iTokens.contains(_iTokenCollateral),
"Tokens have not been listed"
);
(, uint256 _shortfall, , ) = calcAccountEquity(_borrower);
require(_shortfall > 0, "Account does not have shortfall");
// Only allowed to repay the borrow balance's close factor
uint256 _borrowBalance =
IiToken(_iTokenBorrowed).borrowBalanceStored(_borrower);
uint256 _maxRepay = _borrowBalance.rmul(closeFactorMantissa);
require(_repayAmount <= _maxRepay, "Repay exceeds max repay allowed");
_liquidator;
}
/**
* @notice Hook function after iToken `liquidateBorrow()`
* Will `revert()` if any operation fails
* @param _iTokenBorrowed The iToken was borrowed
* @param _iTokenCollateral The collateral iToken to be seized
* @param _liquidator The account which would repay and seize
* @param _borrower The account which has borrowed
* @param _repaidAmount The amount of underlying being repaied
* @param _seizedAmount The amount of collateral being seized
*/
function afterLiquidateBorrow(
address _iTokenBorrowed,
address _iTokenCollateral,
address _liquidator,
address _borrower,
uint256 _repaidAmount,
uint256 _seizedAmount
) external override {
_iTokenBorrowed;
_iTokenCollateral;
_liquidator;
_borrower;
_repaidAmount;
_seizedAmount;
// Unlike repayBorrow, liquidateBorrow does not allow to repay all borrow balance
// No need to check whether should remove from borrowed asset list
}
/**
* @notice Hook function before iToken `seize()`
* Checks if the liquidator should be allowed to seize the collateral iToken
* Will `revert()` if any check fails
* @param _iTokenCollateral The collateral iToken to be seize
* @param _iTokenBorrowed The iToken was borrowed
* @param _liquidator The account which has repaid the borrowed iToken
* @param _borrower The account which has borrowed
* @param _seizeAmount The amount of collateral iToken to seize
*/
function beforeSeize(
address _iTokenCollateral,
address _iTokenBorrowed,
address _liquidator,
address _borrower,
uint256 _seizeAmount
) external override {
require(!seizePaused, "Seize has been paused");
// Markets must have been listed
require(
iTokens.contains(_iTokenBorrowed) &&
iTokens.contains(_iTokenCollateral),
"Tokens have not been listed"
);
// Sanity Check the controllers
require(
IiToken(_iTokenBorrowed).controller() ==
IiToken(_iTokenCollateral).controller(),
"Controller mismatch between Borrowed and Collateral"
);
// Update the Reward Distribution Supply state on collateral
IRewardDistributor(rewardDistributor).updateDistributionState(
_iTokenCollateral,
false
);
// Update reward of liquidator and borrower on collateral
IRewardDistributor(rewardDistributor).updateReward(
_iTokenCollateral,
_liquidator,
false
);
IRewardDistributor(rewardDistributor).updateReward(
_iTokenCollateral,
_borrower,
false
);
_seizeAmount;
}
/**
* @notice Hook function after iToken `seize()`
* Will `revert()` if any operation fails
* @param _iTokenCollateral The collateral iToken to be seized
* @param _iTokenBorrowed The iToken was borrowed
* @param _liquidator The account which has repaid and seized
* @param _borrower The account which has borrowed
* @param _seizedAmount The amount of collateral being seized
*/
function afterSeize(
address _iTokenCollateral,
address _iTokenBorrowed,
address _liquidator,
address _borrower,
uint256 _seizedAmount
) external override {
_iTokenBorrowed;
_iTokenCollateral;
_liquidator;
_borrower;
_seizedAmount;
}
/**
* @notice Hook function before iToken `transfer()`
* Checks if the transfer should be allowed
* Will `revert()` if any check fails
* @param _iToken The iToken to be transfered
* @param _from The account to be transfered from
* @param _to The account to be transfered to
* @param _amount The amount to be transfered
*/
function beforeTransfer(
address _iToken,
address _from,
address _to,
uint256 _amount
) external override {
// _redeemAllowed below will check whether _iToken is listed
require(!transferPaused, "Transfer has been paused");
// Check account equity with this amount to decide whether the transfer is allowed
_redeemAllowed(_iToken, _from, _amount);
// Update the Reward Distribution supply state
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
false
);
// Update reward of from and to
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_from,
false
);
IRewardDistributor(rewardDistributor).updateReward(_iToken, _to, false);
}
/**
* @notice Hook function after iToken `transfer()`
* Will `revert()` if any operation fails
* @param _iToken The iToken was transfered
* @param _from The account was transfer from
* @param _to The account was transfer to
* @param _amount The amount was transfered
*/
function afterTransfer(
address _iToken,
address _from,
address _to,
uint256 _amount
) external override {
_iToken;
_from;
_to;
_amount;
}
/**
* @notice Hook function before iToken `flashloan()`
* Checks if the flashloan should be allowed
* Will `revert()` if any check fails
* @param _iToken The iToken to be flashloaned
* @param _to The account flashloaned transfer to
* @param _amount The amount to be flashloaned
*/
function beforeFlashloan(
address _iToken,
address _to,
uint256 _amount
) external override {
// Flashloan share the same pause state with borrow
require(!markets[_iToken].borrowPaused, "Token borrow has been paused");
_checkiTokenListed(_iToken);
_to;
_amount;
// Update the Reward Distribution Borrow state
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
true
);
}
/**
* @notice Hook function after iToken `flashloan()`
* Will `revert()` if any operation fails
* @param _iToken The iToken was flashloaned
* @param _to The account flashloan transfer to
* @param _amount The amount was flashloaned
*/
function afterFlashloan(
address _iToken,
address _to,
uint256 _amount
) external override {
_iToken;
_to;
_amount;
}
/*********************************/
/***** Internal Functions *******/
/*********************************/
function _redeemAllowed(
address _iToken,
address _redeemer,
uint256 _amount
) private view {
_checkiTokenListed(_iToken);
// No need to check liquidity if _redeemer has not used _iToken as collateral
if (!accountsData[_redeemer].collaterals.contains(_iToken)) {
return;
}
(, uint256 _shortfall, , ) =
calcAccountEquityWithEffect(_redeemer, _iToken, _amount, 0);
require(_shortfall == 0, "Account has some shortfall");
}
/**
* @dev Check if _iToken is listed
*/
function _checkiTokenListed(address _iToken) private view {
require(iTokens.contains(_iToken), "Token has not been listed");
}
/*********************************/
/** Account equity calculation ***/
/*********************************/
/**
* @notice Calculates current account equity
* @param _account The account to query equity of
* @return account equity, shortfall, collateral value, borrowed value.
*/
function calcAccountEquity(address _account)
public
view
override
returns (
uint256,
uint256,
uint256,
uint256
)
{
return calcAccountEquityWithEffect(_account, address(0), 0, 0);
}
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `iTokenBalance` is the number of iTokens the account owns in the collateral,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountEquityLocalVars {
uint256 sumCollateral;
uint256 sumBorrowed;
uint256 iTokenBalance;
uint256 borrowBalance;
uint256 exchangeRateMantissa;
uint256 underlyingPrice;
uint256 collateralValue;
uint256 borrowValue;
}
/**
* @notice Calculates current account equity plus some token and amount to effect
* @param _account The account to query equity of
* @param _tokenToEffect The token address to add some additional redeeem/borrow
* @param _redeemAmount The additional amount to redeem
* @param _borrowAmount The additional amount to borrow
* @return account euqity, shortfall, collateral value, borrowed value plus the effect.
*/
function calcAccountEquityWithEffect(
address _account,
address _tokenToEffect,
uint256 _redeemAmount,
uint256 _borrowAmount
)
internal
view
virtual
returns (
uint256,
uint256,
uint256,
uint256
)
{
AccountEquityLocalVars memory _local;
AccountData storage _accountData = accountsData[_account];
// Calculate value of all collaterals
// collateralValuePerToken = underlyingPrice * exchangeRate * collateralFactor
// collateralValue = balance * collateralValuePerToken
// sumCollateral += collateralValue
uint256 _len = _accountData.collaterals.length();
for (uint256 i = 0; i < _len; i++) {
IiToken _token = IiToken(_accountData.collaterals.at(i));
_local.iTokenBalance = IERC20Upgradeable(address(_token)).balanceOf(
_account
);
_local.exchangeRateMantissa = _token.exchangeRateStored();
if (_tokenToEffect == address(_token) && _redeemAmount > 0) {
_local.iTokenBalance = _local.iTokenBalance.sub(_redeemAmount);
}
_local.underlyingPrice = IPriceOracle(priceOracle)
.getUnderlyingPrice(address(_token));
require(
_local.underlyingPrice != 0,
"Invalid price to calculate account equity"
);
_local.collateralValue = _local
.iTokenBalance
.mul(_local.underlyingPrice)
.rmul(_local.exchangeRateMantissa)
.rmul(markets[address(_token)].collateralFactorMantissa);
_local.sumCollateral = _local.sumCollateral.add(
_local.collateralValue
);
}
// Calculate all borrowed value
// borrowValue = underlyingPrice * underlyingBorrowed / borrowFactor
// sumBorrowed += borrowValue
_len = _accountData.borrowed.length();
for (uint256 i = 0; i < _len; i++) {
IiToken _token = IiToken(_accountData.borrowed.at(i));
_local.borrowBalance = _token.borrowBalanceStored(_account);
if (_tokenToEffect == address(_token) && _borrowAmount > 0) {
_local.borrowBalance = _local.borrowBalance.add(_borrowAmount);
}
_local.underlyingPrice = IPriceOracle(priceOracle)
.getUnderlyingPrice(address(_token));
require(
_local.underlyingPrice != 0,
"Invalid price to calculate account equity"
);
// borrowFactorMantissa can not be set to 0
_local.borrowValue = _local
.borrowBalance
.mul(_local.underlyingPrice)
.rdiv(markets[address(_token)].borrowFactorMantissa);
_local.sumBorrowed = _local.sumBorrowed.add(_local.borrowValue);
}
// Should never underflow
return
_local.sumCollateral > _local.sumBorrowed
? (
_local.sumCollateral - _local.sumBorrowed,
uint256(0),
_local.sumCollateral,
_local.sumBorrowed
)
: (
uint256(0),
_local.sumBorrowed - _local.sumCollateral,
_local.sumCollateral,
_local.sumBorrowed
);
}
/**
* @notice Calculate amount of collateral iToken to seize after repaying an underlying amount
* @dev Used in liquidation
* @param _iTokenBorrowed The iToken was borrowed
* @param _iTokenCollateral The collateral iToken to be seized
* @param _actualRepayAmount The amount of underlying token liquidator has repaied
* @return _seizedTokenCollateral amount of iTokenCollateral tokens to be seized
*/
function liquidateCalculateSeizeTokens(
address _iTokenBorrowed,
address _iTokenCollateral,
uint256 _actualRepayAmount
) external view virtual override returns (uint256 _seizedTokenCollateral) {
/* Read oracle prices for borrowed and collateral assets */
uint256 _priceBorrowed =
IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenBorrowed);
uint256 _priceCollateral =
IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenCollateral);
require(
_priceBorrowed != 0 && _priceCollateral != 0,
"Borrowed or Collateral asset price is invalid"
);
uint256 _valueRepayPlusIncentive =
_actualRepayAmount.mul(_priceBorrowed).rmul(
liquidationIncentiveMantissa
);
// Use stored value here as it is view function
uint256 _exchangeRateMantissa =
IiToken(_iTokenCollateral).exchangeRateStored();
// seizedTokenCollateral = valueRepayPlusIncentive / valuePerTokenCollateral
// valuePerTokenCollateral = exchangeRateMantissa * priceCollateral
_seizedTokenCollateral = _valueRepayPlusIncentive
.rdiv(_exchangeRateMantissa)
.div(_priceCollateral);
}
/*********************************/
/*** Account Markets Operation ***/
/*********************************/
/**
* @notice Returns the markets list the account has entered
* @param _account The address of the account to query
* @return _accountCollaterals The markets list the account has entered
*/
function getEnteredMarkets(address _account)
external
view
override
returns (address[] memory _accountCollaterals)
{
AccountData storage _accountData = accountsData[_account];
uint256 _len = _accountData.collaterals.length();
_accountCollaterals = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_accountCollaterals[i] = _accountData.collaterals.at(i);
}
}
/**
* @notice Add markets to `msg.sender`'s markets list for liquidity calculations
* @param _iTokens The list of addresses of the iToken markets to be entered
* @return _results Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] calldata _iTokens)
external
override
returns (bool[] memory _results)
{
uint256 _len = _iTokens.length;
_results = new bool[](_len);
for (uint256 i = 0; i < _len; i++) {
_results[i] = _enterMarket(_iTokens[i], msg.sender);
}
}
/**
* @notice Add the market to the account's markets list for liquidity calculations
* @param _iToken The market to enter
* @param _account The address of the account to modify
* @return True if entered successfully, false for non-listed market or other errors
*/
function _enterMarket(address _iToken, address _account)
internal
returns (bool)
{
// Market not listed, skip it
if (!iTokens.contains(_iToken)) {
return false;
}
// add() will return false if iToken is in account's market list
if (accountsData[_account].collaterals.add(_iToken)) {
emit MarketEntered(_iToken, _account);
}
return true;
}
/**
* @notice Only expect to be called by iToken contract.
* @dev Add the market to the account's markets list for liquidity calculations
* @param _account The address of the account to modify
*/
function enterMarketFromiToken(address _account)
external
override
{
require(
_enterMarket(msg.sender, _account),
"enterMarketFromiToken: Only can be called by a supported iToken!"
);
}
/**
* @notice Returns whether the given account has entered the market
* @param _account The address of the account to check
* @param _iToken The iToken to check against
* @return True if the account has entered the market, otherwise false.
*/
function hasEnteredMarket(address _account, address _iToken)
external
view
override
returns (bool)
{
return accountsData[_account].collaterals.contains(_iToken);
}
/**
* @notice Remove markets from `msg.sender`'s collaterals for liquidity calculations
* @param _iTokens The list of addresses of the iToken to exit
* @return _results Success indicators for whether each corresponding market was exited
*/
function exitMarkets(address[] calldata _iTokens)
external
override
returns (bool[] memory _results)
{
uint256 _len = _iTokens.length;
_results = new bool[](_len);
for (uint256 i = 0; i < _len; i++) {
_results[i] = _exitMarket(_iTokens[i], msg.sender);
}
}
/**
* @notice Remove the market to the account's markets list for liquidity calculations
* @param _iToken The market to exit
* @param _account The address of the account to modify
* @return True if exit successfully, false for non-listed market or other errors
*/
function _exitMarket(address _iToken, address _account)
internal
returns (bool)
{
// Market not listed, skip it
if (!iTokens.contains(_iToken)) {
return true;
}
// Account has not entered this market, skip it
if (!accountsData[_account].collaterals.contains(_iToken)) {
return true;
}
// Get the iToken balance
uint256 _balance = IERC20Upgradeable(_iToken).balanceOf(_account);
// Check account's equity if all balance are redeemed
// which means iToken can be removed from collaterals
_redeemAllowed(_iToken, _account, _balance);
// Have checked account has entered market before
accountsData[_account].collaterals.remove(_iToken);
emit MarketExited(_iToken, _account);
return true;
}
/**
* @notice Returns the asset list the account has borrowed
* @param _account The address of the account to query
* @return _borrowedAssets The asset list the account has borrowed
*/
function getBorrowedAssets(address _account)
external
view
override
returns (address[] memory _borrowedAssets)
{
AccountData storage _accountData = accountsData[_account];
uint256 _len = _accountData.borrowed.length();
_borrowedAssets = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_borrowedAssets[i] = _accountData.borrowed.at(i);
}
}
/**
* @notice Add the market to the account's borrowed list for equity calculations
* @param _iToken The iToken of underlying to borrow
* @param _account The address of the account to modify
*/
function _addToBorrowed(address _account, address _iToken) internal {
// add() will return false if iToken is in account's market list
if (accountsData[_account].borrowed.add(_iToken)) {
emit BorrowedAdded(_iToken, _account);
}
}
/**
* @notice Returns whether the given account has borrowed the given iToken
* @param _account The address of the account to check
* @param _iToken The iToken to check against
* @return True if the account has borrowed the iToken, otherwise false.
*/
function hasBorrowed(address _account, address _iToken)
public
view
override
returns (bool)
{
return accountsData[_account].borrowed.contains(_iToken);
}
/**
* @notice Remove the iToken from the account's borrowed list
* @param _iToken The iToken to remove
* @param _account The address of the account to modify
*/
function _removeFromBorrowed(address _account, address _iToken) internal {
// remove() will return false if iToken does not exist in account's borrowed list
if (accountsData[_account].borrowed.remove(_iToken)) {
emit BorrowedRemoved(_iToken, _account);
}
}
/*********************************/
/****** General Information ******/
/*********************************/
/**
* @notice Return all of the iTokens
* @return _alliTokens The list of iToken addresses
*/
function getAlliTokens()
public
view
override
returns (address[] memory _alliTokens)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
_alliTokens = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_alliTokens[i] = _iTokens.at(i);
}
}
/**
* @notice Check whether a iToken is listed in controller
* @param _iToken The iToken to check for
* @return true if the iToken is listed otherwise false
*/
function hasiToken(address _iToken) public view override returns (bool) {
return iTokens.contains(_iToken);
}
} | /**
* @title dForce's lending controller Contract
* @author dForce
*/ | NatSpecMultiLine | initialize | function initialize() external initializer {
__Ownable_init();
}
| /**
* @notice Initializes the contract.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
4316,
4396
]
} | 13,297 |
||
Controller | contracts/Controller.sol | 0xd5b837a41a0d664ec28aa55b69b352944f741efa | Solidity | Controller | contract Controller is Initializable, Ownable, IControllerInterface {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using SafeRatioMath for uint256;
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @dev EnumerableSet of all iTokens
EnumerableSetUpgradeable.AddressSet internal iTokens;
struct Market {
/*
* Multiplier representing the most one can borrow against their collateral in this market.
* For instance, 0.9 to allow borrowing 90% of collateral value.
* Must be in [0, 0.9], and stored as a mantissa.
*/
uint256 collateralFactorMantissa;
/*
* Multiplier representing the most one can borrow the asset.
* For instance, 0.5 to allow borrowing this asset 50% * collateral value * collateralFactor.
* When calculating equity, 0.5 with 100 borrow balance will produce 200 borrow value
* Must be between (0, 1], and stored as a mantissa.
*/
uint256 borrowFactorMantissa;
/*
* The borrow capacity of the asset, will be checked in beforeBorrow()
* -1 means there is no limit on the capacity
* 0 means the asset can not be borrowed any more
*/
uint256 borrowCapacity;
/*
* The supply capacity of the asset, will be checked in beforeMint()
* -1 means there is no limit on the capacity
* 0 means the asset can not be supplied any more
*/
uint256 supplyCapacity;
// Whether market's mint is paused
bool mintPaused;
// Whether market's redeem is paused
bool redeemPaused;
// Whether market's borrow is paused
bool borrowPaused;
}
/// @notice Mapping of iTokens to corresponding markets
mapping(address => Market) public markets;
struct AccountData {
// Account's collateral assets
EnumerableSetUpgradeable.AddressSet collaterals;
// Account's borrowed assets
EnumerableSetUpgradeable.AddressSet borrowed;
}
/// @dev Mapping of accounts' data, including collateral and borrowed assets
mapping(address => AccountData) internal accountsData;
/**
* @notice Oracle to query the price of a given asset
*/
address public priceOracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint256 public closeFactorMantissa;
// closeFactorMantissa must be strictly greater than this value
uint256 internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint256 internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint256 public liquidationIncentiveMantissa;
// liquidationIncentiveMantissa must be no less than this value
uint256 internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0
// liquidationIncentiveMantissa must be no greater than this value
uint256 internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
// collateralFactorMantissa must not exceed this value
uint256 internal constant collateralFactorMaxMantissa = 1e18; // 1.0
// borrowFactorMantissa must not exceed this value
uint256 internal constant borrowFactorMaxMantissa = 1e18; // 1.0
/**
* @notice Guardian who can pause mint/borrow/liquidate/transfer in case of emergency
*/
address public pauseGuardian;
/// @notice whether global transfer is paused
bool public transferPaused;
/// @notice whether global seize is paused
bool public seizePaused;
/**
* @notice the address of reward distributor
*/
address public rewardDistributor;
/**
* @dev Check if called by owner or pauseGuardian, and only owner can unpause
*/
modifier checkPauser(bool _paused) {
require(
msg.sender == owner || (msg.sender == pauseGuardian && _paused),
"Only owner and guardian can pause and only owner can unpause"
);
_;
}
/**
* @notice Initializes the contract.
*/
function initialize() external initializer {
__Ownable_init();
}
/*********************************/
/******** Security Check *********/
/*********************************/
/**
* @notice Ensure this is a Controller contract.
*/
function isController() external view override returns (bool) {
return true;
}
/*********************************/
/******** Admin Operations *******/
/*********************************/
/**
* @notice Admin function to add iToken into supported markets
* Checks if the iToken already exsits
* Will `revert()` if any check fails
* @param _iToken The _iToken to add
* @param _collateralFactor The _collateralFactor of _iToken
* @param _borrowFactor The _borrowFactor of _iToken
* @param _supplyCapacity The _supplyCapacity of _iToken
* @param _distributionFactor The _distributionFactor of _iToken
*/
function _addMarket(
address _iToken,
uint256 _collateralFactor,
uint256 _borrowFactor,
uint256 _supplyCapacity,
uint256 _borrowCapacity,
uint256 _distributionFactor
) external override onlyOwner {
require(IiToken(_iToken).isSupported(), "Token is not supported");
// Market must not have been listed, EnumerableSet.add() will return false if it exsits
require(iTokens.add(_iToken), "Token has already been listed");
require(
_collateralFactor <= collateralFactorMaxMantissa,
"Collateral factor invalid"
);
require(
_borrowFactor > 0 && _borrowFactor <= borrowFactorMaxMantissa,
"Borrow factor invalid"
);
// Its value will be taken into account when calculate account equity
// Check if the price is available for the calculation
require(
IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,
"Underlying price is unavailable"
);
markets[_iToken] = Market({
collateralFactorMantissa: _collateralFactor,
borrowFactorMantissa: _borrowFactor,
borrowCapacity: _borrowCapacity,
supplyCapacity: _supplyCapacity,
mintPaused: false,
redeemPaused: false,
borrowPaused: false
});
IRewardDistributor(rewardDistributor)._addRecipient(
_iToken,
_distributionFactor
);
emit MarketAdded(
_iToken,
_collateralFactor,
_borrowFactor,
_supplyCapacity,
_borrowCapacity,
_distributionFactor
);
}
/**
* @notice Sets price oracle
* @dev Admin function to set price oracle
* @param _newOracle New oracle contract
*/
function _setPriceOracle(address _newOracle) external override onlyOwner {
address _oldOracle = priceOracle;
require(
_newOracle != address(0) && _newOracle != _oldOracle,
"Oracle address invalid"
);
priceOracle = _newOracle;
emit NewPriceOracle(_oldOracle, _newOracle);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param _newCloseFactorMantissa New close factor, scaled by 1e18
*/
function _setCloseFactor(uint256 _newCloseFactorMantissa)
external
override
onlyOwner
{
require(
_newCloseFactorMantissa >= closeFactorMinMantissa &&
_newCloseFactorMantissa <= closeFactorMaxMantissa,
"Close factor invalid"
);
uint256 _oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = _newCloseFactorMantissa;
emit NewCloseFactor(_oldCloseFactorMantissa, _newCloseFactorMantissa);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param _newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
*/
function _setLiquidationIncentive(uint256 _newLiquidationIncentiveMantissa)
external
override
onlyOwner
{
require(
_newLiquidationIncentiveMantissa >=
liquidationIncentiveMinMantissa &&
_newLiquidationIncentiveMantissa <=
liquidationIncentiveMaxMantissa,
"Liquidation incentive invalid"
);
uint256 _oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
liquidationIncentiveMantissa = _newLiquidationIncentiveMantissa;
emit NewLiquidationIncentive(
_oldLiquidationIncentiveMantissa,
_newLiquidationIncentiveMantissa
);
}
/**
* @notice Sets the collateralFactor for a iToken
* @dev Admin function to set collateralFactor for a iToken
* @param _iToken The token to set the factor on
* @param _newCollateralFactorMantissa The new collateral factor, scaled by 1e18
*/
function _setCollateralFactor(
address _iToken,
uint256 _newCollateralFactorMantissa
) external override onlyOwner {
_checkiTokenListed(_iToken);
require(
_newCollateralFactorMantissa <= collateralFactorMaxMantissa,
"Collateral factor invalid"
);
// Its value will be taken into account when calculate account equity
// Check if the price is available for the calculation
require(
IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,
"Failed to set collateral factor, underlying price is unavailable"
);
Market storage _market = markets[_iToken];
uint256 _oldCollateralFactorMantissa = _market.collateralFactorMantissa;
_market.collateralFactorMantissa = _newCollateralFactorMantissa;
emit NewCollateralFactor(
_iToken,
_oldCollateralFactorMantissa,
_newCollateralFactorMantissa
);
}
/**
* @notice Sets the borrowFactor for a iToken
* @dev Admin function to set borrowFactor for a iToken
* @param _iToken The token to set the factor on
* @param _newBorrowFactorMantissa The new borrow factor, scaled by 1e18
*/
function _setBorrowFactor(address _iToken, uint256 _newBorrowFactorMantissa)
external
override
onlyOwner
{
_checkiTokenListed(_iToken);
require(
_newBorrowFactorMantissa > 0 &&
_newBorrowFactorMantissa <= borrowFactorMaxMantissa,
"Borrow factor invalid"
);
// Its value will be taken into account when calculate account equity
// Check if the price is available for the calculation
require(
IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,
"Failed to set borrow factor, underlying price is unavailable"
);
Market storage _market = markets[_iToken];
uint256 _oldBorrowFactorMantissa = _market.borrowFactorMantissa;
_market.borrowFactorMantissa = _newBorrowFactorMantissa;
emit NewBorrowFactor(
_iToken,
_oldBorrowFactorMantissa,
_newBorrowFactorMantissa
);
}
/**
* @notice Sets the borrowCapacity for a iToken
* @dev Admin function to set borrowCapacity for a iToken
* @param _iToken The token to set the capacity on
* @param _newBorrowCapacity The new borrow capacity
*/
function _setBorrowCapacity(address _iToken, uint256 _newBorrowCapacity)
external
override
onlyOwner
{
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
uint256 oldBorrowCapacity = _market.borrowCapacity;
_market.borrowCapacity = _newBorrowCapacity;
emit NewBorrowCapacity(_iToken, oldBorrowCapacity, _newBorrowCapacity);
}
/**
* @notice Sets the supplyCapacity for a iToken
* @dev Admin function to set supplyCapacity for a iToken
* @param _iToken The token to set the capacity on
* @param _newSupplyCapacity The new supply capacity
*/
function _setSupplyCapacity(address _iToken, uint256 _newSupplyCapacity)
external
override
onlyOwner
{
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
uint256 oldSupplyCapacity = _market.supplyCapacity;
_market.supplyCapacity = _newSupplyCapacity;
emit NewSupplyCapacity(_iToken, oldSupplyCapacity, _newSupplyCapacity);
}
/**
* @notice Sets the pauseGuardian
* @dev Admin function to set pauseGuardian
* @param _newPauseGuardian The new pause guardian
*/
function _setPauseGuardian(address _newPauseGuardian)
external
override
onlyOwner
{
address _oldPauseGuardian = pauseGuardian;
require(
_newPauseGuardian != address(0) &&
_newPauseGuardian != _oldPauseGuardian,
"Pause guardian address invalid"
);
pauseGuardian = _newPauseGuardian;
emit NewPauseGuardian(_oldPauseGuardian, _newPauseGuardian);
}
/**
* @notice pause/unpause mint() for all iTokens
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setAllMintPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
_setMintPausedInternal(_iTokens.at(i), _paused);
}
}
/**
* @notice pause/unpause mint() for the iToken
* @dev Admin function, only owner and pauseGuardian can call this
* @param _iToken The iToken to pause/unpause
* @param _paused whether to pause or unpause
*/
function _setMintPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setMintPausedInternal(_iToken, _paused);
}
function _setMintPausedInternal(address _iToken, bool _paused) internal {
markets[_iToken].mintPaused = _paused;
emit MintPaused(_iToken, _paused);
}
/**
* @notice pause/unpause redeem() for all iTokens
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setAllRedeemPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
_setRedeemPausedInternal(_iTokens.at(i), _paused);
}
}
/**
* @notice pause/unpause redeem() for the iToken
* @dev Admin function, only owner and pauseGuardian can call this
* @param _iToken The iToken to pause/unpause
* @param _paused whether to pause or unpause
*/
function _setRedeemPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setRedeemPausedInternal(_iToken, _paused);
}
function _setRedeemPausedInternal(address _iToken, bool _paused) internal {
markets[_iToken].redeemPaused = _paused;
emit RedeemPaused(_iToken, _paused);
}
/**
* @notice pause/unpause borrow() for all iTokens
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setAllBorrowPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
_setBorrowPausedInternal(_iTokens.at(i), _paused);
}
}
/**
* @notice pause/unpause borrow() for the iToken
* @dev Admin function, only owner and pauseGuardian can call this
* @param _iToken The iToken to pause/unpause
* @param _paused whether to pause or unpause
*/
function _setBorrowPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setBorrowPausedInternal(_iToken, _paused);
}
function _setBorrowPausedInternal(address _iToken, bool _paused) internal {
markets[_iToken].borrowPaused = _paused;
emit BorrowPaused(_iToken, _paused);
}
/**
* @notice pause/unpause global transfer()
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setTransferPaused(bool _paused)
external
override
checkPauser(_paused)
{
_setTransferPausedInternal(_paused);
}
function _setTransferPausedInternal(bool _paused) internal {
transferPaused = _paused;
emit TransferPaused(_paused);
}
/**
* @notice pause/unpause global seize()
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setSeizePaused(bool _paused)
external
override
checkPauser(_paused)
{
_setSeizePausedInternal(_paused);
}
function _setSeizePausedInternal(bool _paused) internal {
seizePaused = _paused;
emit SeizePaused(_paused);
}
/**
* @notice pause/unpause all actions iToken, including mint/redeem/borrow
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setiTokenPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setiTokenPausedInternal(_iToken, _paused);
}
function _setiTokenPausedInternal(address _iToken, bool _paused) internal {
Market storage _market = markets[_iToken];
_market.mintPaused = _paused;
emit MintPaused(_iToken, _paused);
_market.redeemPaused = _paused;
emit RedeemPaused(_iToken, _paused);
_market.borrowPaused = _paused;
emit BorrowPaused(_iToken, _paused);
}
/**
* @notice pause/unpause entire protocol, including mint/redeem/borrow/seize/transfer
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setProtocolPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
address _iToken = _iTokens.at(i);
_setiTokenPausedInternal(_iToken, _paused);
}
_setTransferPausedInternal(_paused);
_setSeizePausedInternal(_paused);
}
/**
* @notice Sets Reward Distributor
* @dev Admin function to set reward distributor
* @param _newRewardDistributor new reward distributor
*/
function _setRewardDistributor(address _newRewardDistributor)
external
override
onlyOwner
{
address _oldRewardDistributor = rewardDistributor;
require(
_newRewardDistributor != address(0) &&
_newRewardDistributor != _oldRewardDistributor,
"Reward Distributor address invalid"
);
rewardDistributor = _newRewardDistributor;
emit NewRewardDistributor(_oldRewardDistributor, _newRewardDistributor);
}
/*********************************/
/******** Poclicy Hooks **********/
/*********************************/
/**
* @notice Hook function before iToken `mint()`
* Checks if the account should be allowed to mint the given iToken
* Will `revert()` if any check fails
* @param _iToken The iToken to check the mint against
* @param _minter The account which would get the minted tokens
* @param _mintAmount The amount of underlying being minted to iToken
*/
function beforeMint(
address _iToken,
address _minter,
uint256 _mintAmount
) external override {
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
require(!_market.mintPaused, "Token mint has been paused");
// Check the iToken's supply capacity, -1 means no limit
uint256 _totalSupplyUnderlying =
IERC20Upgradeable(_iToken).totalSupply().rmul(
IiToken(_iToken).exchangeRateStored()
);
require(
_totalSupplyUnderlying.add(_mintAmount) <= _market.supplyCapacity,
"Token supply capacity reached"
);
// Update the Reward Distribution Supply state and distribute reward to suppplier
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
false
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_minter,
false
);
}
/**
* @notice Hook function after iToken `mint()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being minted
* @param _minter The account which would get the minted tokens
* @param _mintAmount The amount of underlying being minted to iToken
* @param _mintedAmount The amount of iToken being minted
*/
function afterMint(
address _iToken,
address _minter,
uint256 _mintAmount,
uint256 _mintedAmount
) external override {
_iToken;
_minter;
_mintAmount;
_mintedAmount;
}
/**
* @notice Hook function before iToken `redeem()`
* Checks if the account should be allowed to redeem the given iToken
* Will `revert()` if any check fails
* @param _iToken The iToken to check the redeem against
* @param _redeemer The account which would redeem iToken
* @param _redeemAmount The amount of iToken to redeem
*/
function beforeRedeem(
address _iToken,
address _redeemer,
uint256 _redeemAmount
) external override {
// _redeemAllowed below will check whether _iToken is listed
require(!markets[_iToken].redeemPaused, "Token redeem has been paused");
_redeemAllowed(_iToken, _redeemer, _redeemAmount);
// Update the Reward Distribution Supply state and distribute reward to suppplier
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
false
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_redeemer,
false
);
}
/**
* @notice Hook function after iToken `redeem()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being redeemed
* @param _redeemer The account which redeemed iToken
* @param _redeemAmount The amount of iToken being redeemed
* @param _redeemedUnderlying The amount of underlying being redeemed
*/
function afterRedeem(
address _iToken,
address _redeemer,
uint256 _redeemAmount,
uint256 _redeemedUnderlying
) external override {
_iToken;
_redeemer;
_redeemAmount;
_redeemedUnderlying;
}
/**
* @notice Hook function before iToken `borrow()`
* Checks if the account should be allowed to borrow the given iToken
* Will `revert()` if any check fails
* @param _iToken The iToken to check the borrow against
* @param _borrower The account which would borrow iToken
* @param _borrowAmount The amount of underlying to borrow
*/
function beforeBorrow(
address _iToken,
address _borrower,
uint256 _borrowAmount
) external override {
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
require(!_market.borrowPaused, "Token borrow has been paused");
if (!hasBorrowed(_borrower, _iToken)) {
// Unlike collaterals, borrowed asset can only be added by iToken,
// rather than enabled by user directly.
require(msg.sender == _iToken, "sender must be iToken");
// Have checked _iToken is listed, just add it
_addToBorrowed(_borrower, _iToken);
}
// Check borrower's equity
(, uint256 _shortfall, , ) =
calcAccountEquityWithEffect(_borrower, _iToken, 0, _borrowAmount);
require(_shortfall == 0, "Account has some shortfall");
// Check the iToken's borrow capacity, -1 means no limit
uint256 _totalBorrows = IiToken(_iToken).totalBorrows();
require(
_totalBorrows.add(_borrowAmount) <= _market.borrowCapacity,
"Token borrow capacity reached"
);
// Update the Reward Distribution Borrow state and distribute reward to borrower
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
true
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_borrower,
true
);
}
/**
* @notice Hook function after iToken `borrow()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being borrewd
* @param _borrower The account which borrowed iToken
* @param _borrowedAmount The amount of underlying being borrowed
*/
function afterBorrow(
address _iToken,
address _borrower,
uint256 _borrowedAmount
) external override {
_iToken;
_borrower;
_borrowedAmount;
}
/**
* @notice Hook function before iToken `repayBorrow()`
* Checks if the account should be allowed to repay the given iToken
* for the borrower. Will `revert()` if any check fails
* @param _iToken The iToken to verify the repay against
* @param _payer The account which would repay iToken
* @param _borrower The account which has borrowed
* @param _repayAmount The amount of underlying to repay
*/
function beforeRepayBorrow(
address _iToken,
address _payer,
address _borrower,
uint256 _repayAmount
) external override {
_checkiTokenListed(_iToken);
// Update the Reward Distribution Borrow state and distribute reward to borrower
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
true
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_borrower,
true
);
_payer;
_repayAmount;
}
/**
* @notice Hook function after iToken `repayBorrow()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being repaid
* @param _payer The account which would repay
* @param _borrower The account which has borrowed
* @param _repayAmount The amount of underlying being repaied
*/
function afterRepayBorrow(
address _iToken,
address _payer,
address _borrower,
uint256 _repayAmount
) external override {
_checkiTokenListed(_iToken);
// Remove _iToken from borrowed list if new borrow balance is 0
if (IiToken(_iToken).borrowBalanceStored(_borrower) == 0) {
// Only allow called by iToken as we are going to remove this token from borrower's borrowed list
require(msg.sender == _iToken, "sender must be iToken");
// Have checked _iToken is listed, just remove it
_removeFromBorrowed(_borrower, _iToken);
}
_payer;
_repayAmount;
}
/**
* @notice Hook function before iToken `liquidateBorrow()`
* Checks if the account should be allowed to liquidate the given iToken
* for the borrower. Will `revert()` if any check fails
* @param _iTokenBorrowed The iToken was borrowed
* @param _iTokenCollateral The collateral iToken to be liqudate with
* @param _liquidator The account which would repay the borrowed iToken
* @param _borrower The account which has borrowed
* @param _repayAmount The amount of underlying to repay
*/
function beforeLiquidateBorrow(
address _iTokenBorrowed,
address _iTokenCollateral,
address _liquidator,
address _borrower,
uint256 _repayAmount
) external override {
// Tokens must have been listed
require(
iTokens.contains(_iTokenBorrowed) &&
iTokens.contains(_iTokenCollateral),
"Tokens have not been listed"
);
(, uint256 _shortfall, , ) = calcAccountEquity(_borrower);
require(_shortfall > 0, "Account does not have shortfall");
// Only allowed to repay the borrow balance's close factor
uint256 _borrowBalance =
IiToken(_iTokenBorrowed).borrowBalanceStored(_borrower);
uint256 _maxRepay = _borrowBalance.rmul(closeFactorMantissa);
require(_repayAmount <= _maxRepay, "Repay exceeds max repay allowed");
_liquidator;
}
/**
* @notice Hook function after iToken `liquidateBorrow()`
* Will `revert()` if any operation fails
* @param _iTokenBorrowed The iToken was borrowed
* @param _iTokenCollateral The collateral iToken to be seized
* @param _liquidator The account which would repay and seize
* @param _borrower The account which has borrowed
* @param _repaidAmount The amount of underlying being repaied
* @param _seizedAmount The amount of collateral being seized
*/
function afterLiquidateBorrow(
address _iTokenBorrowed,
address _iTokenCollateral,
address _liquidator,
address _borrower,
uint256 _repaidAmount,
uint256 _seizedAmount
) external override {
_iTokenBorrowed;
_iTokenCollateral;
_liquidator;
_borrower;
_repaidAmount;
_seizedAmount;
// Unlike repayBorrow, liquidateBorrow does not allow to repay all borrow balance
// No need to check whether should remove from borrowed asset list
}
/**
* @notice Hook function before iToken `seize()`
* Checks if the liquidator should be allowed to seize the collateral iToken
* Will `revert()` if any check fails
* @param _iTokenCollateral The collateral iToken to be seize
* @param _iTokenBorrowed The iToken was borrowed
* @param _liquidator The account which has repaid the borrowed iToken
* @param _borrower The account which has borrowed
* @param _seizeAmount The amount of collateral iToken to seize
*/
function beforeSeize(
address _iTokenCollateral,
address _iTokenBorrowed,
address _liquidator,
address _borrower,
uint256 _seizeAmount
) external override {
require(!seizePaused, "Seize has been paused");
// Markets must have been listed
require(
iTokens.contains(_iTokenBorrowed) &&
iTokens.contains(_iTokenCollateral),
"Tokens have not been listed"
);
// Sanity Check the controllers
require(
IiToken(_iTokenBorrowed).controller() ==
IiToken(_iTokenCollateral).controller(),
"Controller mismatch between Borrowed and Collateral"
);
// Update the Reward Distribution Supply state on collateral
IRewardDistributor(rewardDistributor).updateDistributionState(
_iTokenCollateral,
false
);
// Update reward of liquidator and borrower on collateral
IRewardDistributor(rewardDistributor).updateReward(
_iTokenCollateral,
_liquidator,
false
);
IRewardDistributor(rewardDistributor).updateReward(
_iTokenCollateral,
_borrower,
false
);
_seizeAmount;
}
/**
* @notice Hook function after iToken `seize()`
* Will `revert()` if any operation fails
* @param _iTokenCollateral The collateral iToken to be seized
* @param _iTokenBorrowed The iToken was borrowed
* @param _liquidator The account which has repaid and seized
* @param _borrower The account which has borrowed
* @param _seizedAmount The amount of collateral being seized
*/
function afterSeize(
address _iTokenCollateral,
address _iTokenBorrowed,
address _liquidator,
address _borrower,
uint256 _seizedAmount
) external override {
_iTokenBorrowed;
_iTokenCollateral;
_liquidator;
_borrower;
_seizedAmount;
}
/**
* @notice Hook function before iToken `transfer()`
* Checks if the transfer should be allowed
* Will `revert()` if any check fails
* @param _iToken The iToken to be transfered
* @param _from The account to be transfered from
* @param _to The account to be transfered to
* @param _amount The amount to be transfered
*/
function beforeTransfer(
address _iToken,
address _from,
address _to,
uint256 _amount
) external override {
// _redeemAllowed below will check whether _iToken is listed
require(!transferPaused, "Transfer has been paused");
// Check account equity with this amount to decide whether the transfer is allowed
_redeemAllowed(_iToken, _from, _amount);
// Update the Reward Distribution supply state
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
false
);
// Update reward of from and to
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_from,
false
);
IRewardDistributor(rewardDistributor).updateReward(_iToken, _to, false);
}
/**
* @notice Hook function after iToken `transfer()`
* Will `revert()` if any operation fails
* @param _iToken The iToken was transfered
* @param _from The account was transfer from
* @param _to The account was transfer to
* @param _amount The amount was transfered
*/
function afterTransfer(
address _iToken,
address _from,
address _to,
uint256 _amount
) external override {
_iToken;
_from;
_to;
_amount;
}
/**
* @notice Hook function before iToken `flashloan()`
* Checks if the flashloan should be allowed
* Will `revert()` if any check fails
* @param _iToken The iToken to be flashloaned
* @param _to The account flashloaned transfer to
* @param _amount The amount to be flashloaned
*/
function beforeFlashloan(
address _iToken,
address _to,
uint256 _amount
) external override {
// Flashloan share the same pause state with borrow
require(!markets[_iToken].borrowPaused, "Token borrow has been paused");
_checkiTokenListed(_iToken);
_to;
_amount;
// Update the Reward Distribution Borrow state
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
true
);
}
/**
* @notice Hook function after iToken `flashloan()`
* Will `revert()` if any operation fails
* @param _iToken The iToken was flashloaned
* @param _to The account flashloan transfer to
* @param _amount The amount was flashloaned
*/
function afterFlashloan(
address _iToken,
address _to,
uint256 _amount
) external override {
_iToken;
_to;
_amount;
}
/*********************************/
/***** Internal Functions *******/
/*********************************/
function _redeemAllowed(
address _iToken,
address _redeemer,
uint256 _amount
) private view {
_checkiTokenListed(_iToken);
// No need to check liquidity if _redeemer has not used _iToken as collateral
if (!accountsData[_redeemer].collaterals.contains(_iToken)) {
return;
}
(, uint256 _shortfall, , ) =
calcAccountEquityWithEffect(_redeemer, _iToken, _amount, 0);
require(_shortfall == 0, "Account has some shortfall");
}
/**
* @dev Check if _iToken is listed
*/
function _checkiTokenListed(address _iToken) private view {
require(iTokens.contains(_iToken), "Token has not been listed");
}
/*********************************/
/** Account equity calculation ***/
/*********************************/
/**
* @notice Calculates current account equity
* @param _account The account to query equity of
* @return account equity, shortfall, collateral value, borrowed value.
*/
function calcAccountEquity(address _account)
public
view
override
returns (
uint256,
uint256,
uint256,
uint256
)
{
return calcAccountEquityWithEffect(_account, address(0), 0, 0);
}
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `iTokenBalance` is the number of iTokens the account owns in the collateral,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountEquityLocalVars {
uint256 sumCollateral;
uint256 sumBorrowed;
uint256 iTokenBalance;
uint256 borrowBalance;
uint256 exchangeRateMantissa;
uint256 underlyingPrice;
uint256 collateralValue;
uint256 borrowValue;
}
/**
* @notice Calculates current account equity plus some token and amount to effect
* @param _account The account to query equity of
* @param _tokenToEffect The token address to add some additional redeeem/borrow
* @param _redeemAmount The additional amount to redeem
* @param _borrowAmount The additional amount to borrow
* @return account euqity, shortfall, collateral value, borrowed value plus the effect.
*/
function calcAccountEquityWithEffect(
address _account,
address _tokenToEffect,
uint256 _redeemAmount,
uint256 _borrowAmount
)
internal
view
virtual
returns (
uint256,
uint256,
uint256,
uint256
)
{
AccountEquityLocalVars memory _local;
AccountData storage _accountData = accountsData[_account];
// Calculate value of all collaterals
// collateralValuePerToken = underlyingPrice * exchangeRate * collateralFactor
// collateralValue = balance * collateralValuePerToken
// sumCollateral += collateralValue
uint256 _len = _accountData.collaterals.length();
for (uint256 i = 0; i < _len; i++) {
IiToken _token = IiToken(_accountData.collaterals.at(i));
_local.iTokenBalance = IERC20Upgradeable(address(_token)).balanceOf(
_account
);
_local.exchangeRateMantissa = _token.exchangeRateStored();
if (_tokenToEffect == address(_token) && _redeemAmount > 0) {
_local.iTokenBalance = _local.iTokenBalance.sub(_redeemAmount);
}
_local.underlyingPrice = IPriceOracle(priceOracle)
.getUnderlyingPrice(address(_token));
require(
_local.underlyingPrice != 0,
"Invalid price to calculate account equity"
);
_local.collateralValue = _local
.iTokenBalance
.mul(_local.underlyingPrice)
.rmul(_local.exchangeRateMantissa)
.rmul(markets[address(_token)].collateralFactorMantissa);
_local.sumCollateral = _local.sumCollateral.add(
_local.collateralValue
);
}
// Calculate all borrowed value
// borrowValue = underlyingPrice * underlyingBorrowed / borrowFactor
// sumBorrowed += borrowValue
_len = _accountData.borrowed.length();
for (uint256 i = 0; i < _len; i++) {
IiToken _token = IiToken(_accountData.borrowed.at(i));
_local.borrowBalance = _token.borrowBalanceStored(_account);
if (_tokenToEffect == address(_token) && _borrowAmount > 0) {
_local.borrowBalance = _local.borrowBalance.add(_borrowAmount);
}
_local.underlyingPrice = IPriceOracle(priceOracle)
.getUnderlyingPrice(address(_token));
require(
_local.underlyingPrice != 0,
"Invalid price to calculate account equity"
);
// borrowFactorMantissa can not be set to 0
_local.borrowValue = _local
.borrowBalance
.mul(_local.underlyingPrice)
.rdiv(markets[address(_token)].borrowFactorMantissa);
_local.sumBorrowed = _local.sumBorrowed.add(_local.borrowValue);
}
// Should never underflow
return
_local.sumCollateral > _local.sumBorrowed
? (
_local.sumCollateral - _local.sumBorrowed,
uint256(0),
_local.sumCollateral,
_local.sumBorrowed
)
: (
uint256(0),
_local.sumBorrowed - _local.sumCollateral,
_local.sumCollateral,
_local.sumBorrowed
);
}
/**
* @notice Calculate amount of collateral iToken to seize after repaying an underlying amount
* @dev Used in liquidation
* @param _iTokenBorrowed The iToken was borrowed
* @param _iTokenCollateral The collateral iToken to be seized
* @param _actualRepayAmount The amount of underlying token liquidator has repaied
* @return _seizedTokenCollateral amount of iTokenCollateral tokens to be seized
*/
function liquidateCalculateSeizeTokens(
address _iTokenBorrowed,
address _iTokenCollateral,
uint256 _actualRepayAmount
) external view virtual override returns (uint256 _seizedTokenCollateral) {
/* Read oracle prices for borrowed and collateral assets */
uint256 _priceBorrowed =
IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenBorrowed);
uint256 _priceCollateral =
IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenCollateral);
require(
_priceBorrowed != 0 && _priceCollateral != 0,
"Borrowed or Collateral asset price is invalid"
);
uint256 _valueRepayPlusIncentive =
_actualRepayAmount.mul(_priceBorrowed).rmul(
liquidationIncentiveMantissa
);
// Use stored value here as it is view function
uint256 _exchangeRateMantissa =
IiToken(_iTokenCollateral).exchangeRateStored();
// seizedTokenCollateral = valueRepayPlusIncentive / valuePerTokenCollateral
// valuePerTokenCollateral = exchangeRateMantissa * priceCollateral
_seizedTokenCollateral = _valueRepayPlusIncentive
.rdiv(_exchangeRateMantissa)
.div(_priceCollateral);
}
/*********************************/
/*** Account Markets Operation ***/
/*********************************/
/**
* @notice Returns the markets list the account has entered
* @param _account The address of the account to query
* @return _accountCollaterals The markets list the account has entered
*/
function getEnteredMarkets(address _account)
external
view
override
returns (address[] memory _accountCollaterals)
{
AccountData storage _accountData = accountsData[_account];
uint256 _len = _accountData.collaterals.length();
_accountCollaterals = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_accountCollaterals[i] = _accountData.collaterals.at(i);
}
}
/**
* @notice Add markets to `msg.sender`'s markets list for liquidity calculations
* @param _iTokens The list of addresses of the iToken markets to be entered
* @return _results Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] calldata _iTokens)
external
override
returns (bool[] memory _results)
{
uint256 _len = _iTokens.length;
_results = new bool[](_len);
for (uint256 i = 0; i < _len; i++) {
_results[i] = _enterMarket(_iTokens[i], msg.sender);
}
}
/**
* @notice Add the market to the account's markets list for liquidity calculations
* @param _iToken The market to enter
* @param _account The address of the account to modify
* @return True if entered successfully, false for non-listed market or other errors
*/
function _enterMarket(address _iToken, address _account)
internal
returns (bool)
{
// Market not listed, skip it
if (!iTokens.contains(_iToken)) {
return false;
}
// add() will return false if iToken is in account's market list
if (accountsData[_account].collaterals.add(_iToken)) {
emit MarketEntered(_iToken, _account);
}
return true;
}
/**
* @notice Only expect to be called by iToken contract.
* @dev Add the market to the account's markets list for liquidity calculations
* @param _account The address of the account to modify
*/
function enterMarketFromiToken(address _account)
external
override
{
require(
_enterMarket(msg.sender, _account),
"enterMarketFromiToken: Only can be called by a supported iToken!"
);
}
/**
* @notice Returns whether the given account has entered the market
* @param _account The address of the account to check
* @param _iToken The iToken to check against
* @return True if the account has entered the market, otherwise false.
*/
function hasEnteredMarket(address _account, address _iToken)
external
view
override
returns (bool)
{
return accountsData[_account].collaterals.contains(_iToken);
}
/**
* @notice Remove markets from `msg.sender`'s collaterals for liquidity calculations
* @param _iTokens The list of addresses of the iToken to exit
* @return _results Success indicators for whether each corresponding market was exited
*/
function exitMarkets(address[] calldata _iTokens)
external
override
returns (bool[] memory _results)
{
uint256 _len = _iTokens.length;
_results = new bool[](_len);
for (uint256 i = 0; i < _len; i++) {
_results[i] = _exitMarket(_iTokens[i], msg.sender);
}
}
/**
* @notice Remove the market to the account's markets list for liquidity calculations
* @param _iToken The market to exit
* @param _account The address of the account to modify
* @return True if exit successfully, false for non-listed market or other errors
*/
function _exitMarket(address _iToken, address _account)
internal
returns (bool)
{
// Market not listed, skip it
if (!iTokens.contains(_iToken)) {
return true;
}
// Account has not entered this market, skip it
if (!accountsData[_account].collaterals.contains(_iToken)) {
return true;
}
// Get the iToken balance
uint256 _balance = IERC20Upgradeable(_iToken).balanceOf(_account);
// Check account's equity if all balance are redeemed
// which means iToken can be removed from collaterals
_redeemAllowed(_iToken, _account, _balance);
// Have checked account has entered market before
accountsData[_account].collaterals.remove(_iToken);
emit MarketExited(_iToken, _account);
return true;
}
/**
* @notice Returns the asset list the account has borrowed
* @param _account The address of the account to query
* @return _borrowedAssets The asset list the account has borrowed
*/
function getBorrowedAssets(address _account)
external
view
override
returns (address[] memory _borrowedAssets)
{
AccountData storage _accountData = accountsData[_account];
uint256 _len = _accountData.borrowed.length();
_borrowedAssets = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_borrowedAssets[i] = _accountData.borrowed.at(i);
}
}
/**
* @notice Add the market to the account's borrowed list for equity calculations
* @param _iToken The iToken of underlying to borrow
* @param _account The address of the account to modify
*/
function _addToBorrowed(address _account, address _iToken) internal {
// add() will return false if iToken is in account's market list
if (accountsData[_account].borrowed.add(_iToken)) {
emit BorrowedAdded(_iToken, _account);
}
}
/**
* @notice Returns whether the given account has borrowed the given iToken
* @param _account The address of the account to check
* @param _iToken The iToken to check against
* @return True if the account has borrowed the iToken, otherwise false.
*/
function hasBorrowed(address _account, address _iToken)
public
view
override
returns (bool)
{
return accountsData[_account].borrowed.contains(_iToken);
}
/**
* @notice Remove the iToken from the account's borrowed list
* @param _iToken The iToken to remove
* @param _account The address of the account to modify
*/
function _removeFromBorrowed(address _account, address _iToken) internal {
// remove() will return false if iToken does not exist in account's borrowed list
if (accountsData[_account].borrowed.remove(_iToken)) {
emit BorrowedRemoved(_iToken, _account);
}
}
/*********************************/
/****** General Information ******/
/*********************************/
/**
* @notice Return all of the iTokens
* @return _alliTokens The list of iToken addresses
*/
function getAlliTokens()
public
view
override
returns (address[] memory _alliTokens)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
_alliTokens = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_alliTokens[i] = _iTokens.at(i);
}
}
/**
* @notice Check whether a iToken is listed in controller
* @param _iToken The iToken to check for
* @return true if the iToken is listed otherwise false
*/
function hasiToken(address _iToken) public view override returns (bool) {
return iTokens.contains(_iToken);
}
} | /**
* @title dForce's lending controller Contract
* @author dForce
*/ | NatSpecMultiLine | isController | function isController() external view override returns (bool) {
return true;
}
| /**
* @notice Ensure this is a Controller contract.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
4588,
4682
]
} | 13,298 |
||
Controller | contracts/Controller.sol | 0xd5b837a41a0d664ec28aa55b69b352944f741efa | Solidity | Controller | contract Controller is Initializable, Ownable, IControllerInterface {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using SafeRatioMath for uint256;
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @dev EnumerableSet of all iTokens
EnumerableSetUpgradeable.AddressSet internal iTokens;
struct Market {
/*
* Multiplier representing the most one can borrow against their collateral in this market.
* For instance, 0.9 to allow borrowing 90% of collateral value.
* Must be in [0, 0.9], and stored as a mantissa.
*/
uint256 collateralFactorMantissa;
/*
* Multiplier representing the most one can borrow the asset.
* For instance, 0.5 to allow borrowing this asset 50% * collateral value * collateralFactor.
* When calculating equity, 0.5 with 100 borrow balance will produce 200 borrow value
* Must be between (0, 1], and stored as a mantissa.
*/
uint256 borrowFactorMantissa;
/*
* The borrow capacity of the asset, will be checked in beforeBorrow()
* -1 means there is no limit on the capacity
* 0 means the asset can not be borrowed any more
*/
uint256 borrowCapacity;
/*
* The supply capacity of the asset, will be checked in beforeMint()
* -1 means there is no limit on the capacity
* 0 means the asset can not be supplied any more
*/
uint256 supplyCapacity;
// Whether market's mint is paused
bool mintPaused;
// Whether market's redeem is paused
bool redeemPaused;
// Whether market's borrow is paused
bool borrowPaused;
}
/// @notice Mapping of iTokens to corresponding markets
mapping(address => Market) public markets;
struct AccountData {
// Account's collateral assets
EnumerableSetUpgradeable.AddressSet collaterals;
// Account's borrowed assets
EnumerableSetUpgradeable.AddressSet borrowed;
}
/// @dev Mapping of accounts' data, including collateral and borrowed assets
mapping(address => AccountData) internal accountsData;
/**
* @notice Oracle to query the price of a given asset
*/
address public priceOracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint256 public closeFactorMantissa;
// closeFactorMantissa must be strictly greater than this value
uint256 internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint256 internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint256 public liquidationIncentiveMantissa;
// liquidationIncentiveMantissa must be no less than this value
uint256 internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0
// liquidationIncentiveMantissa must be no greater than this value
uint256 internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
// collateralFactorMantissa must not exceed this value
uint256 internal constant collateralFactorMaxMantissa = 1e18; // 1.0
// borrowFactorMantissa must not exceed this value
uint256 internal constant borrowFactorMaxMantissa = 1e18; // 1.0
/**
* @notice Guardian who can pause mint/borrow/liquidate/transfer in case of emergency
*/
address public pauseGuardian;
/// @notice whether global transfer is paused
bool public transferPaused;
/// @notice whether global seize is paused
bool public seizePaused;
/**
* @notice the address of reward distributor
*/
address public rewardDistributor;
/**
* @dev Check if called by owner or pauseGuardian, and only owner can unpause
*/
modifier checkPauser(bool _paused) {
require(
msg.sender == owner || (msg.sender == pauseGuardian && _paused),
"Only owner and guardian can pause and only owner can unpause"
);
_;
}
/**
* @notice Initializes the contract.
*/
function initialize() external initializer {
__Ownable_init();
}
/*********************************/
/******** Security Check *********/
/*********************************/
/**
* @notice Ensure this is a Controller contract.
*/
function isController() external view override returns (bool) {
return true;
}
/*********************************/
/******** Admin Operations *******/
/*********************************/
/**
* @notice Admin function to add iToken into supported markets
* Checks if the iToken already exsits
* Will `revert()` if any check fails
* @param _iToken The _iToken to add
* @param _collateralFactor The _collateralFactor of _iToken
* @param _borrowFactor The _borrowFactor of _iToken
* @param _supplyCapacity The _supplyCapacity of _iToken
* @param _distributionFactor The _distributionFactor of _iToken
*/
function _addMarket(
address _iToken,
uint256 _collateralFactor,
uint256 _borrowFactor,
uint256 _supplyCapacity,
uint256 _borrowCapacity,
uint256 _distributionFactor
) external override onlyOwner {
require(IiToken(_iToken).isSupported(), "Token is not supported");
// Market must not have been listed, EnumerableSet.add() will return false if it exsits
require(iTokens.add(_iToken), "Token has already been listed");
require(
_collateralFactor <= collateralFactorMaxMantissa,
"Collateral factor invalid"
);
require(
_borrowFactor > 0 && _borrowFactor <= borrowFactorMaxMantissa,
"Borrow factor invalid"
);
// Its value will be taken into account when calculate account equity
// Check if the price is available for the calculation
require(
IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,
"Underlying price is unavailable"
);
markets[_iToken] = Market({
collateralFactorMantissa: _collateralFactor,
borrowFactorMantissa: _borrowFactor,
borrowCapacity: _borrowCapacity,
supplyCapacity: _supplyCapacity,
mintPaused: false,
redeemPaused: false,
borrowPaused: false
});
IRewardDistributor(rewardDistributor)._addRecipient(
_iToken,
_distributionFactor
);
emit MarketAdded(
_iToken,
_collateralFactor,
_borrowFactor,
_supplyCapacity,
_borrowCapacity,
_distributionFactor
);
}
/**
* @notice Sets price oracle
* @dev Admin function to set price oracle
* @param _newOracle New oracle contract
*/
function _setPriceOracle(address _newOracle) external override onlyOwner {
address _oldOracle = priceOracle;
require(
_newOracle != address(0) && _newOracle != _oldOracle,
"Oracle address invalid"
);
priceOracle = _newOracle;
emit NewPriceOracle(_oldOracle, _newOracle);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param _newCloseFactorMantissa New close factor, scaled by 1e18
*/
function _setCloseFactor(uint256 _newCloseFactorMantissa)
external
override
onlyOwner
{
require(
_newCloseFactorMantissa >= closeFactorMinMantissa &&
_newCloseFactorMantissa <= closeFactorMaxMantissa,
"Close factor invalid"
);
uint256 _oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = _newCloseFactorMantissa;
emit NewCloseFactor(_oldCloseFactorMantissa, _newCloseFactorMantissa);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param _newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
*/
function _setLiquidationIncentive(uint256 _newLiquidationIncentiveMantissa)
external
override
onlyOwner
{
require(
_newLiquidationIncentiveMantissa >=
liquidationIncentiveMinMantissa &&
_newLiquidationIncentiveMantissa <=
liquidationIncentiveMaxMantissa,
"Liquidation incentive invalid"
);
uint256 _oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
liquidationIncentiveMantissa = _newLiquidationIncentiveMantissa;
emit NewLiquidationIncentive(
_oldLiquidationIncentiveMantissa,
_newLiquidationIncentiveMantissa
);
}
/**
* @notice Sets the collateralFactor for a iToken
* @dev Admin function to set collateralFactor for a iToken
* @param _iToken The token to set the factor on
* @param _newCollateralFactorMantissa The new collateral factor, scaled by 1e18
*/
function _setCollateralFactor(
address _iToken,
uint256 _newCollateralFactorMantissa
) external override onlyOwner {
_checkiTokenListed(_iToken);
require(
_newCollateralFactorMantissa <= collateralFactorMaxMantissa,
"Collateral factor invalid"
);
// Its value will be taken into account when calculate account equity
// Check if the price is available for the calculation
require(
IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,
"Failed to set collateral factor, underlying price is unavailable"
);
Market storage _market = markets[_iToken];
uint256 _oldCollateralFactorMantissa = _market.collateralFactorMantissa;
_market.collateralFactorMantissa = _newCollateralFactorMantissa;
emit NewCollateralFactor(
_iToken,
_oldCollateralFactorMantissa,
_newCollateralFactorMantissa
);
}
/**
* @notice Sets the borrowFactor for a iToken
* @dev Admin function to set borrowFactor for a iToken
* @param _iToken The token to set the factor on
* @param _newBorrowFactorMantissa The new borrow factor, scaled by 1e18
*/
function _setBorrowFactor(address _iToken, uint256 _newBorrowFactorMantissa)
external
override
onlyOwner
{
_checkiTokenListed(_iToken);
require(
_newBorrowFactorMantissa > 0 &&
_newBorrowFactorMantissa <= borrowFactorMaxMantissa,
"Borrow factor invalid"
);
// Its value will be taken into account when calculate account equity
// Check if the price is available for the calculation
require(
IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,
"Failed to set borrow factor, underlying price is unavailable"
);
Market storage _market = markets[_iToken];
uint256 _oldBorrowFactorMantissa = _market.borrowFactorMantissa;
_market.borrowFactorMantissa = _newBorrowFactorMantissa;
emit NewBorrowFactor(
_iToken,
_oldBorrowFactorMantissa,
_newBorrowFactorMantissa
);
}
/**
* @notice Sets the borrowCapacity for a iToken
* @dev Admin function to set borrowCapacity for a iToken
* @param _iToken The token to set the capacity on
* @param _newBorrowCapacity The new borrow capacity
*/
function _setBorrowCapacity(address _iToken, uint256 _newBorrowCapacity)
external
override
onlyOwner
{
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
uint256 oldBorrowCapacity = _market.borrowCapacity;
_market.borrowCapacity = _newBorrowCapacity;
emit NewBorrowCapacity(_iToken, oldBorrowCapacity, _newBorrowCapacity);
}
/**
* @notice Sets the supplyCapacity for a iToken
* @dev Admin function to set supplyCapacity for a iToken
* @param _iToken The token to set the capacity on
* @param _newSupplyCapacity The new supply capacity
*/
function _setSupplyCapacity(address _iToken, uint256 _newSupplyCapacity)
external
override
onlyOwner
{
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
uint256 oldSupplyCapacity = _market.supplyCapacity;
_market.supplyCapacity = _newSupplyCapacity;
emit NewSupplyCapacity(_iToken, oldSupplyCapacity, _newSupplyCapacity);
}
/**
* @notice Sets the pauseGuardian
* @dev Admin function to set pauseGuardian
* @param _newPauseGuardian The new pause guardian
*/
function _setPauseGuardian(address _newPauseGuardian)
external
override
onlyOwner
{
address _oldPauseGuardian = pauseGuardian;
require(
_newPauseGuardian != address(0) &&
_newPauseGuardian != _oldPauseGuardian,
"Pause guardian address invalid"
);
pauseGuardian = _newPauseGuardian;
emit NewPauseGuardian(_oldPauseGuardian, _newPauseGuardian);
}
/**
* @notice pause/unpause mint() for all iTokens
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setAllMintPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
_setMintPausedInternal(_iTokens.at(i), _paused);
}
}
/**
* @notice pause/unpause mint() for the iToken
* @dev Admin function, only owner and pauseGuardian can call this
* @param _iToken The iToken to pause/unpause
* @param _paused whether to pause or unpause
*/
function _setMintPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setMintPausedInternal(_iToken, _paused);
}
function _setMintPausedInternal(address _iToken, bool _paused) internal {
markets[_iToken].mintPaused = _paused;
emit MintPaused(_iToken, _paused);
}
/**
* @notice pause/unpause redeem() for all iTokens
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setAllRedeemPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
_setRedeemPausedInternal(_iTokens.at(i), _paused);
}
}
/**
* @notice pause/unpause redeem() for the iToken
* @dev Admin function, only owner and pauseGuardian can call this
* @param _iToken The iToken to pause/unpause
* @param _paused whether to pause or unpause
*/
function _setRedeemPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setRedeemPausedInternal(_iToken, _paused);
}
function _setRedeemPausedInternal(address _iToken, bool _paused) internal {
markets[_iToken].redeemPaused = _paused;
emit RedeemPaused(_iToken, _paused);
}
/**
* @notice pause/unpause borrow() for all iTokens
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setAllBorrowPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
_setBorrowPausedInternal(_iTokens.at(i), _paused);
}
}
/**
* @notice pause/unpause borrow() for the iToken
* @dev Admin function, only owner and pauseGuardian can call this
* @param _iToken The iToken to pause/unpause
* @param _paused whether to pause or unpause
*/
function _setBorrowPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setBorrowPausedInternal(_iToken, _paused);
}
function _setBorrowPausedInternal(address _iToken, bool _paused) internal {
markets[_iToken].borrowPaused = _paused;
emit BorrowPaused(_iToken, _paused);
}
/**
* @notice pause/unpause global transfer()
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setTransferPaused(bool _paused)
external
override
checkPauser(_paused)
{
_setTransferPausedInternal(_paused);
}
function _setTransferPausedInternal(bool _paused) internal {
transferPaused = _paused;
emit TransferPaused(_paused);
}
/**
* @notice pause/unpause global seize()
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setSeizePaused(bool _paused)
external
override
checkPauser(_paused)
{
_setSeizePausedInternal(_paused);
}
function _setSeizePausedInternal(bool _paused) internal {
seizePaused = _paused;
emit SeizePaused(_paused);
}
/**
* @notice pause/unpause all actions iToken, including mint/redeem/borrow
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setiTokenPaused(address _iToken, bool _paused)
external
override
checkPauser(_paused)
{
_checkiTokenListed(_iToken);
_setiTokenPausedInternal(_iToken, _paused);
}
function _setiTokenPausedInternal(address _iToken, bool _paused) internal {
Market storage _market = markets[_iToken];
_market.mintPaused = _paused;
emit MintPaused(_iToken, _paused);
_market.redeemPaused = _paused;
emit RedeemPaused(_iToken, _paused);
_market.borrowPaused = _paused;
emit BorrowPaused(_iToken, _paused);
}
/**
* @notice pause/unpause entire protocol, including mint/redeem/borrow/seize/transfer
* @dev Admin function, only owner and pauseGuardian can call this
* @param _paused whether to pause or unpause
*/
function _setProtocolPaused(bool _paused)
external
override
checkPauser(_paused)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
for (uint256 i = 0; i < _len; i++) {
address _iToken = _iTokens.at(i);
_setiTokenPausedInternal(_iToken, _paused);
}
_setTransferPausedInternal(_paused);
_setSeizePausedInternal(_paused);
}
/**
* @notice Sets Reward Distributor
* @dev Admin function to set reward distributor
* @param _newRewardDistributor new reward distributor
*/
function _setRewardDistributor(address _newRewardDistributor)
external
override
onlyOwner
{
address _oldRewardDistributor = rewardDistributor;
require(
_newRewardDistributor != address(0) &&
_newRewardDistributor != _oldRewardDistributor,
"Reward Distributor address invalid"
);
rewardDistributor = _newRewardDistributor;
emit NewRewardDistributor(_oldRewardDistributor, _newRewardDistributor);
}
/*********************************/
/******** Poclicy Hooks **********/
/*********************************/
/**
* @notice Hook function before iToken `mint()`
* Checks if the account should be allowed to mint the given iToken
* Will `revert()` if any check fails
* @param _iToken The iToken to check the mint against
* @param _minter The account which would get the minted tokens
* @param _mintAmount The amount of underlying being minted to iToken
*/
function beforeMint(
address _iToken,
address _minter,
uint256 _mintAmount
) external override {
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
require(!_market.mintPaused, "Token mint has been paused");
// Check the iToken's supply capacity, -1 means no limit
uint256 _totalSupplyUnderlying =
IERC20Upgradeable(_iToken).totalSupply().rmul(
IiToken(_iToken).exchangeRateStored()
);
require(
_totalSupplyUnderlying.add(_mintAmount) <= _market.supplyCapacity,
"Token supply capacity reached"
);
// Update the Reward Distribution Supply state and distribute reward to suppplier
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
false
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_minter,
false
);
}
/**
* @notice Hook function after iToken `mint()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being minted
* @param _minter The account which would get the minted tokens
* @param _mintAmount The amount of underlying being minted to iToken
* @param _mintedAmount The amount of iToken being minted
*/
function afterMint(
address _iToken,
address _minter,
uint256 _mintAmount,
uint256 _mintedAmount
) external override {
_iToken;
_minter;
_mintAmount;
_mintedAmount;
}
/**
* @notice Hook function before iToken `redeem()`
* Checks if the account should be allowed to redeem the given iToken
* Will `revert()` if any check fails
* @param _iToken The iToken to check the redeem against
* @param _redeemer The account which would redeem iToken
* @param _redeemAmount The amount of iToken to redeem
*/
function beforeRedeem(
address _iToken,
address _redeemer,
uint256 _redeemAmount
) external override {
// _redeemAllowed below will check whether _iToken is listed
require(!markets[_iToken].redeemPaused, "Token redeem has been paused");
_redeemAllowed(_iToken, _redeemer, _redeemAmount);
// Update the Reward Distribution Supply state and distribute reward to suppplier
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
false
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_redeemer,
false
);
}
/**
* @notice Hook function after iToken `redeem()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being redeemed
* @param _redeemer The account which redeemed iToken
* @param _redeemAmount The amount of iToken being redeemed
* @param _redeemedUnderlying The amount of underlying being redeemed
*/
function afterRedeem(
address _iToken,
address _redeemer,
uint256 _redeemAmount,
uint256 _redeemedUnderlying
) external override {
_iToken;
_redeemer;
_redeemAmount;
_redeemedUnderlying;
}
/**
* @notice Hook function before iToken `borrow()`
* Checks if the account should be allowed to borrow the given iToken
* Will `revert()` if any check fails
* @param _iToken The iToken to check the borrow against
* @param _borrower The account which would borrow iToken
* @param _borrowAmount The amount of underlying to borrow
*/
function beforeBorrow(
address _iToken,
address _borrower,
uint256 _borrowAmount
) external override {
_checkiTokenListed(_iToken);
Market storage _market = markets[_iToken];
require(!_market.borrowPaused, "Token borrow has been paused");
if (!hasBorrowed(_borrower, _iToken)) {
// Unlike collaterals, borrowed asset can only be added by iToken,
// rather than enabled by user directly.
require(msg.sender == _iToken, "sender must be iToken");
// Have checked _iToken is listed, just add it
_addToBorrowed(_borrower, _iToken);
}
// Check borrower's equity
(, uint256 _shortfall, , ) =
calcAccountEquityWithEffect(_borrower, _iToken, 0, _borrowAmount);
require(_shortfall == 0, "Account has some shortfall");
// Check the iToken's borrow capacity, -1 means no limit
uint256 _totalBorrows = IiToken(_iToken).totalBorrows();
require(
_totalBorrows.add(_borrowAmount) <= _market.borrowCapacity,
"Token borrow capacity reached"
);
// Update the Reward Distribution Borrow state and distribute reward to borrower
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
true
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_borrower,
true
);
}
/**
* @notice Hook function after iToken `borrow()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being borrewd
* @param _borrower The account which borrowed iToken
* @param _borrowedAmount The amount of underlying being borrowed
*/
function afterBorrow(
address _iToken,
address _borrower,
uint256 _borrowedAmount
) external override {
_iToken;
_borrower;
_borrowedAmount;
}
/**
* @notice Hook function before iToken `repayBorrow()`
* Checks if the account should be allowed to repay the given iToken
* for the borrower. Will `revert()` if any check fails
* @param _iToken The iToken to verify the repay against
* @param _payer The account which would repay iToken
* @param _borrower The account which has borrowed
* @param _repayAmount The amount of underlying to repay
*/
function beforeRepayBorrow(
address _iToken,
address _payer,
address _borrower,
uint256 _repayAmount
) external override {
_checkiTokenListed(_iToken);
// Update the Reward Distribution Borrow state and distribute reward to borrower
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
true
);
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_borrower,
true
);
_payer;
_repayAmount;
}
/**
* @notice Hook function after iToken `repayBorrow()`
* Will `revert()` if any operation fails
* @param _iToken The iToken being repaid
* @param _payer The account which would repay
* @param _borrower The account which has borrowed
* @param _repayAmount The amount of underlying being repaied
*/
function afterRepayBorrow(
address _iToken,
address _payer,
address _borrower,
uint256 _repayAmount
) external override {
_checkiTokenListed(_iToken);
// Remove _iToken from borrowed list if new borrow balance is 0
if (IiToken(_iToken).borrowBalanceStored(_borrower) == 0) {
// Only allow called by iToken as we are going to remove this token from borrower's borrowed list
require(msg.sender == _iToken, "sender must be iToken");
// Have checked _iToken is listed, just remove it
_removeFromBorrowed(_borrower, _iToken);
}
_payer;
_repayAmount;
}
/**
* @notice Hook function before iToken `liquidateBorrow()`
* Checks if the account should be allowed to liquidate the given iToken
* for the borrower. Will `revert()` if any check fails
* @param _iTokenBorrowed The iToken was borrowed
* @param _iTokenCollateral The collateral iToken to be liqudate with
* @param _liquidator The account which would repay the borrowed iToken
* @param _borrower The account which has borrowed
* @param _repayAmount The amount of underlying to repay
*/
function beforeLiquidateBorrow(
address _iTokenBorrowed,
address _iTokenCollateral,
address _liquidator,
address _borrower,
uint256 _repayAmount
) external override {
// Tokens must have been listed
require(
iTokens.contains(_iTokenBorrowed) &&
iTokens.contains(_iTokenCollateral),
"Tokens have not been listed"
);
(, uint256 _shortfall, , ) = calcAccountEquity(_borrower);
require(_shortfall > 0, "Account does not have shortfall");
// Only allowed to repay the borrow balance's close factor
uint256 _borrowBalance =
IiToken(_iTokenBorrowed).borrowBalanceStored(_borrower);
uint256 _maxRepay = _borrowBalance.rmul(closeFactorMantissa);
require(_repayAmount <= _maxRepay, "Repay exceeds max repay allowed");
_liquidator;
}
/**
* @notice Hook function after iToken `liquidateBorrow()`
* Will `revert()` if any operation fails
* @param _iTokenBorrowed The iToken was borrowed
* @param _iTokenCollateral The collateral iToken to be seized
* @param _liquidator The account which would repay and seize
* @param _borrower The account which has borrowed
* @param _repaidAmount The amount of underlying being repaied
* @param _seizedAmount The amount of collateral being seized
*/
function afterLiquidateBorrow(
address _iTokenBorrowed,
address _iTokenCollateral,
address _liquidator,
address _borrower,
uint256 _repaidAmount,
uint256 _seizedAmount
) external override {
_iTokenBorrowed;
_iTokenCollateral;
_liquidator;
_borrower;
_repaidAmount;
_seizedAmount;
// Unlike repayBorrow, liquidateBorrow does not allow to repay all borrow balance
// No need to check whether should remove from borrowed asset list
}
/**
* @notice Hook function before iToken `seize()`
* Checks if the liquidator should be allowed to seize the collateral iToken
* Will `revert()` if any check fails
* @param _iTokenCollateral The collateral iToken to be seize
* @param _iTokenBorrowed The iToken was borrowed
* @param _liquidator The account which has repaid the borrowed iToken
* @param _borrower The account which has borrowed
* @param _seizeAmount The amount of collateral iToken to seize
*/
function beforeSeize(
address _iTokenCollateral,
address _iTokenBorrowed,
address _liquidator,
address _borrower,
uint256 _seizeAmount
) external override {
require(!seizePaused, "Seize has been paused");
// Markets must have been listed
require(
iTokens.contains(_iTokenBorrowed) &&
iTokens.contains(_iTokenCollateral),
"Tokens have not been listed"
);
// Sanity Check the controllers
require(
IiToken(_iTokenBorrowed).controller() ==
IiToken(_iTokenCollateral).controller(),
"Controller mismatch between Borrowed and Collateral"
);
// Update the Reward Distribution Supply state on collateral
IRewardDistributor(rewardDistributor).updateDistributionState(
_iTokenCollateral,
false
);
// Update reward of liquidator and borrower on collateral
IRewardDistributor(rewardDistributor).updateReward(
_iTokenCollateral,
_liquidator,
false
);
IRewardDistributor(rewardDistributor).updateReward(
_iTokenCollateral,
_borrower,
false
);
_seizeAmount;
}
/**
* @notice Hook function after iToken `seize()`
* Will `revert()` if any operation fails
* @param _iTokenCollateral The collateral iToken to be seized
* @param _iTokenBorrowed The iToken was borrowed
* @param _liquidator The account which has repaid and seized
* @param _borrower The account which has borrowed
* @param _seizedAmount The amount of collateral being seized
*/
function afterSeize(
address _iTokenCollateral,
address _iTokenBorrowed,
address _liquidator,
address _borrower,
uint256 _seizedAmount
) external override {
_iTokenBorrowed;
_iTokenCollateral;
_liquidator;
_borrower;
_seizedAmount;
}
/**
* @notice Hook function before iToken `transfer()`
* Checks if the transfer should be allowed
* Will `revert()` if any check fails
* @param _iToken The iToken to be transfered
* @param _from The account to be transfered from
* @param _to The account to be transfered to
* @param _amount The amount to be transfered
*/
function beforeTransfer(
address _iToken,
address _from,
address _to,
uint256 _amount
) external override {
// _redeemAllowed below will check whether _iToken is listed
require(!transferPaused, "Transfer has been paused");
// Check account equity with this amount to decide whether the transfer is allowed
_redeemAllowed(_iToken, _from, _amount);
// Update the Reward Distribution supply state
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
false
);
// Update reward of from and to
IRewardDistributor(rewardDistributor).updateReward(
_iToken,
_from,
false
);
IRewardDistributor(rewardDistributor).updateReward(_iToken, _to, false);
}
/**
* @notice Hook function after iToken `transfer()`
* Will `revert()` if any operation fails
* @param _iToken The iToken was transfered
* @param _from The account was transfer from
* @param _to The account was transfer to
* @param _amount The amount was transfered
*/
function afterTransfer(
address _iToken,
address _from,
address _to,
uint256 _amount
) external override {
_iToken;
_from;
_to;
_amount;
}
/**
* @notice Hook function before iToken `flashloan()`
* Checks if the flashloan should be allowed
* Will `revert()` if any check fails
* @param _iToken The iToken to be flashloaned
* @param _to The account flashloaned transfer to
* @param _amount The amount to be flashloaned
*/
function beforeFlashloan(
address _iToken,
address _to,
uint256 _amount
) external override {
// Flashloan share the same pause state with borrow
require(!markets[_iToken].borrowPaused, "Token borrow has been paused");
_checkiTokenListed(_iToken);
_to;
_amount;
// Update the Reward Distribution Borrow state
IRewardDistributor(rewardDistributor).updateDistributionState(
_iToken,
true
);
}
/**
* @notice Hook function after iToken `flashloan()`
* Will `revert()` if any operation fails
* @param _iToken The iToken was flashloaned
* @param _to The account flashloan transfer to
* @param _amount The amount was flashloaned
*/
function afterFlashloan(
address _iToken,
address _to,
uint256 _amount
) external override {
_iToken;
_to;
_amount;
}
/*********************************/
/***** Internal Functions *******/
/*********************************/
function _redeemAllowed(
address _iToken,
address _redeemer,
uint256 _amount
) private view {
_checkiTokenListed(_iToken);
// No need to check liquidity if _redeemer has not used _iToken as collateral
if (!accountsData[_redeemer].collaterals.contains(_iToken)) {
return;
}
(, uint256 _shortfall, , ) =
calcAccountEquityWithEffect(_redeemer, _iToken, _amount, 0);
require(_shortfall == 0, "Account has some shortfall");
}
/**
* @dev Check if _iToken is listed
*/
function _checkiTokenListed(address _iToken) private view {
require(iTokens.contains(_iToken), "Token has not been listed");
}
/*********************************/
/** Account equity calculation ***/
/*********************************/
/**
* @notice Calculates current account equity
* @param _account The account to query equity of
* @return account equity, shortfall, collateral value, borrowed value.
*/
function calcAccountEquity(address _account)
public
view
override
returns (
uint256,
uint256,
uint256,
uint256
)
{
return calcAccountEquityWithEffect(_account, address(0), 0, 0);
}
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `iTokenBalance` is the number of iTokens the account owns in the collateral,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountEquityLocalVars {
uint256 sumCollateral;
uint256 sumBorrowed;
uint256 iTokenBalance;
uint256 borrowBalance;
uint256 exchangeRateMantissa;
uint256 underlyingPrice;
uint256 collateralValue;
uint256 borrowValue;
}
/**
* @notice Calculates current account equity plus some token and amount to effect
* @param _account The account to query equity of
* @param _tokenToEffect The token address to add some additional redeeem/borrow
* @param _redeemAmount The additional amount to redeem
* @param _borrowAmount The additional amount to borrow
* @return account euqity, shortfall, collateral value, borrowed value plus the effect.
*/
function calcAccountEquityWithEffect(
address _account,
address _tokenToEffect,
uint256 _redeemAmount,
uint256 _borrowAmount
)
internal
view
virtual
returns (
uint256,
uint256,
uint256,
uint256
)
{
AccountEquityLocalVars memory _local;
AccountData storage _accountData = accountsData[_account];
// Calculate value of all collaterals
// collateralValuePerToken = underlyingPrice * exchangeRate * collateralFactor
// collateralValue = balance * collateralValuePerToken
// sumCollateral += collateralValue
uint256 _len = _accountData.collaterals.length();
for (uint256 i = 0; i < _len; i++) {
IiToken _token = IiToken(_accountData.collaterals.at(i));
_local.iTokenBalance = IERC20Upgradeable(address(_token)).balanceOf(
_account
);
_local.exchangeRateMantissa = _token.exchangeRateStored();
if (_tokenToEffect == address(_token) && _redeemAmount > 0) {
_local.iTokenBalance = _local.iTokenBalance.sub(_redeemAmount);
}
_local.underlyingPrice = IPriceOracle(priceOracle)
.getUnderlyingPrice(address(_token));
require(
_local.underlyingPrice != 0,
"Invalid price to calculate account equity"
);
_local.collateralValue = _local
.iTokenBalance
.mul(_local.underlyingPrice)
.rmul(_local.exchangeRateMantissa)
.rmul(markets[address(_token)].collateralFactorMantissa);
_local.sumCollateral = _local.sumCollateral.add(
_local.collateralValue
);
}
// Calculate all borrowed value
// borrowValue = underlyingPrice * underlyingBorrowed / borrowFactor
// sumBorrowed += borrowValue
_len = _accountData.borrowed.length();
for (uint256 i = 0; i < _len; i++) {
IiToken _token = IiToken(_accountData.borrowed.at(i));
_local.borrowBalance = _token.borrowBalanceStored(_account);
if (_tokenToEffect == address(_token) && _borrowAmount > 0) {
_local.borrowBalance = _local.borrowBalance.add(_borrowAmount);
}
_local.underlyingPrice = IPriceOracle(priceOracle)
.getUnderlyingPrice(address(_token));
require(
_local.underlyingPrice != 0,
"Invalid price to calculate account equity"
);
// borrowFactorMantissa can not be set to 0
_local.borrowValue = _local
.borrowBalance
.mul(_local.underlyingPrice)
.rdiv(markets[address(_token)].borrowFactorMantissa);
_local.sumBorrowed = _local.sumBorrowed.add(_local.borrowValue);
}
// Should never underflow
return
_local.sumCollateral > _local.sumBorrowed
? (
_local.sumCollateral - _local.sumBorrowed,
uint256(0),
_local.sumCollateral,
_local.sumBorrowed
)
: (
uint256(0),
_local.sumBorrowed - _local.sumCollateral,
_local.sumCollateral,
_local.sumBorrowed
);
}
/**
* @notice Calculate amount of collateral iToken to seize after repaying an underlying amount
* @dev Used in liquidation
* @param _iTokenBorrowed The iToken was borrowed
* @param _iTokenCollateral The collateral iToken to be seized
* @param _actualRepayAmount The amount of underlying token liquidator has repaied
* @return _seizedTokenCollateral amount of iTokenCollateral tokens to be seized
*/
function liquidateCalculateSeizeTokens(
address _iTokenBorrowed,
address _iTokenCollateral,
uint256 _actualRepayAmount
) external view virtual override returns (uint256 _seizedTokenCollateral) {
/* Read oracle prices for borrowed and collateral assets */
uint256 _priceBorrowed =
IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenBorrowed);
uint256 _priceCollateral =
IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenCollateral);
require(
_priceBorrowed != 0 && _priceCollateral != 0,
"Borrowed or Collateral asset price is invalid"
);
uint256 _valueRepayPlusIncentive =
_actualRepayAmount.mul(_priceBorrowed).rmul(
liquidationIncentiveMantissa
);
// Use stored value here as it is view function
uint256 _exchangeRateMantissa =
IiToken(_iTokenCollateral).exchangeRateStored();
// seizedTokenCollateral = valueRepayPlusIncentive / valuePerTokenCollateral
// valuePerTokenCollateral = exchangeRateMantissa * priceCollateral
_seizedTokenCollateral = _valueRepayPlusIncentive
.rdiv(_exchangeRateMantissa)
.div(_priceCollateral);
}
/*********************************/
/*** Account Markets Operation ***/
/*********************************/
/**
* @notice Returns the markets list the account has entered
* @param _account The address of the account to query
* @return _accountCollaterals The markets list the account has entered
*/
function getEnteredMarkets(address _account)
external
view
override
returns (address[] memory _accountCollaterals)
{
AccountData storage _accountData = accountsData[_account];
uint256 _len = _accountData.collaterals.length();
_accountCollaterals = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_accountCollaterals[i] = _accountData.collaterals.at(i);
}
}
/**
* @notice Add markets to `msg.sender`'s markets list for liquidity calculations
* @param _iTokens The list of addresses of the iToken markets to be entered
* @return _results Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] calldata _iTokens)
external
override
returns (bool[] memory _results)
{
uint256 _len = _iTokens.length;
_results = new bool[](_len);
for (uint256 i = 0; i < _len; i++) {
_results[i] = _enterMarket(_iTokens[i], msg.sender);
}
}
/**
* @notice Add the market to the account's markets list for liquidity calculations
* @param _iToken The market to enter
* @param _account The address of the account to modify
* @return True if entered successfully, false for non-listed market or other errors
*/
function _enterMarket(address _iToken, address _account)
internal
returns (bool)
{
// Market not listed, skip it
if (!iTokens.contains(_iToken)) {
return false;
}
// add() will return false if iToken is in account's market list
if (accountsData[_account].collaterals.add(_iToken)) {
emit MarketEntered(_iToken, _account);
}
return true;
}
/**
* @notice Only expect to be called by iToken contract.
* @dev Add the market to the account's markets list for liquidity calculations
* @param _account The address of the account to modify
*/
function enterMarketFromiToken(address _account)
external
override
{
require(
_enterMarket(msg.sender, _account),
"enterMarketFromiToken: Only can be called by a supported iToken!"
);
}
/**
* @notice Returns whether the given account has entered the market
* @param _account The address of the account to check
* @param _iToken The iToken to check against
* @return True if the account has entered the market, otherwise false.
*/
function hasEnteredMarket(address _account, address _iToken)
external
view
override
returns (bool)
{
return accountsData[_account].collaterals.contains(_iToken);
}
/**
* @notice Remove markets from `msg.sender`'s collaterals for liquidity calculations
* @param _iTokens The list of addresses of the iToken to exit
* @return _results Success indicators for whether each corresponding market was exited
*/
function exitMarkets(address[] calldata _iTokens)
external
override
returns (bool[] memory _results)
{
uint256 _len = _iTokens.length;
_results = new bool[](_len);
for (uint256 i = 0; i < _len; i++) {
_results[i] = _exitMarket(_iTokens[i], msg.sender);
}
}
/**
* @notice Remove the market to the account's markets list for liquidity calculations
* @param _iToken The market to exit
* @param _account The address of the account to modify
* @return True if exit successfully, false for non-listed market or other errors
*/
function _exitMarket(address _iToken, address _account)
internal
returns (bool)
{
// Market not listed, skip it
if (!iTokens.contains(_iToken)) {
return true;
}
// Account has not entered this market, skip it
if (!accountsData[_account].collaterals.contains(_iToken)) {
return true;
}
// Get the iToken balance
uint256 _balance = IERC20Upgradeable(_iToken).balanceOf(_account);
// Check account's equity if all balance are redeemed
// which means iToken can be removed from collaterals
_redeemAllowed(_iToken, _account, _balance);
// Have checked account has entered market before
accountsData[_account].collaterals.remove(_iToken);
emit MarketExited(_iToken, _account);
return true;
}
/**
* @notice Returns the asset list the account has borrowed
* @param _account The address of the account to query
* @return _borrowedAssets The asset list the account has borrowed
*/
function getBorrowedAssets(address _account)
external
view
override
returns (address[] memory _borrowedAssets)
{
AccountData storage _accountData = accountsData[_account];
uint256 _len = _accountData.borrowed.length();
_borrowedAssets = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_borrowedAssets[i] = _accountData.borrowed.at(i);
}
}
/**
* @notice Add the market to the account's borrowed list for equity calculations
* @param _iToken The iToken of underlying to borrow
* @param _account The address of the account to modify
*/
function _addToBorrowed(address _account, address _iToken) internal {
// add() will return false if iToken is in account's market list
if (accountsData[_account].borrowed.add(_iToken)) {
emit BorrowedAdded(_iToken, _account);
}
}
/**
* @notice Returns whether the given account has borrowed the given iToken
* @param _account The address of the account to check
* @param _iToken The iToken to check against
* @return True if the account has borrowed the iToken, otherwise false.
*/
function hasBorrowed(address _account, address _iToken)
public
view
override
returns (bool)
{
return accountsData[_account].borrowed.contains(_iToken);
}
/**
* @notice Remove the iToken from the account's borrowed list
* @param _iToken The iToken to remove
* @param _account The address of the account to modify
*/
function _removeFromBorrowed(address _account, address _iToken) internal {
// remove() will return false if iToken does not exist in account's borrowed list
if (accountsData[_account].borrowed.remove(_iToken)) {
emit BorrowedRemoved(_iToken, _account);
}
}
/*********************************/
/****** General Information ******/
/*********************************/
/**
* @notice Return all of the iTokens
* @return _alliTokens The list of iToken addresses
*/
function getAlliTokens()
public
view
override
returns (address[] memory _alliTokens)
{
EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens;
uint256 _len = _iTokens.length();
_alliTokens = new address[](_len);
for (uint256 i = 0; i < _len; i++) {
_alliTokens[i] = _iTokens.at(i);
}
}
/**
* @notice Check whether a iToken is listed in controller
* @param _iToken The iToken to check for
* @return true if the iToken is listed otherwise false
*/
function hasiToken(address _iToken) public view override returns (bool) {
return iTokens.contains(_iToken);
}
} | /**
* @title dForce's lending controller Contract
* @author dForce
*/ | NatSpecMultiLine | _addMarket | function _addMarket(
address _iToken,
uint256 _collateralFactor,
uint256 _borrowFactor,
uint256 _supplyCapacity,
uint256 _borrowCapacity,
uint256 _distributionFactor
) external override onlyOwner {
require(IiToken(_iToken).isSupported(), "Token is not supported");
// Market must not have been listed, EnumerableSet.add() will return false if it exsits
require(iTokens.add(_iToken), "Token has already been listed");
require(
_collateralFactor <= collateralFactorMaxMantissa,
"Collateral factor invalid"
);
require(
_borrowFactor > 0 && _borrowFactor <= borrowFactorMaxMantissa,
"Borrow factor invalid"
);
// Its value will be taken into account when calculate account equity
// Check if the price is available for the calculation
require(
IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0,
"Underlying price is unavailable"
);
markets[_iToken] = Market({
collateralFactorMantissa: _collateralFactor,
borrowFactorMantissa: _borrowFactor,
borrowCapacity: _borrowCapacity,
supplyCapacity: _supplyCapacity,
mintPaused: false,
redeemPaused: false,
borrowPaused: false
});
IRewardDistributor(rewardDistributor)._addRecipient(
_iToken,
_distributionFactor
);
emit MarketAdded(
_iToken,
_collateralFactor,
_borrowFactor,
_supplyCapacity,
_borrowCapacity,
_distributionFactor
);
}
| /**
* @notice Admin function to add iToken into supported markets
* Checks if the iToken already exsits
* Will `revert()` if any check fails
* @param _iToken The _iToken to add
* @param _collateralFactor The _collateralFactor of _iToken
* @param _borrowFactor The _borrowFactor of _iToken
* @param _supplyCapacity The _supplyCapacity of _iToken
* @param _distributionFactor The _distributionFactor of _iToken
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
5266,
7002
]
} | 13,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.