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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
HumanStandardToken | HumanStandardToken.sol | 0x39514112a90fe523615eeb407af81a880b92a419 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
function _move(address _from, address _to, uint256 _value) returns (bool success) {}
function _balanceOf(address _owner) constant returns (uint256 balance) {}
function _transfer(address _to, uint256 _value) returns (bool success) {}
function _transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function _approve(address _spender, uint256 _value) returns (bool success) {}
function _allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | totalSupply | function totalSupply() constant returns (uint256 supply) {}
| /// @return total amount of tokens | NatSpecSingleLine | v0.4.25+commit.59dbf8f1 | bzzr://b2d8d791f292c59e65ef91dcbe45d0c20e2c0885d6878f15a1f0689365d0031d | {
"func_code_index": [
60,
124
]
} | 1,400 |
|||
HumanStandardToken | HumanStandardToken.sol | 0x39514112a90fe523615eeb407af81a880b92a419 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
function _move(address _from, address _to, uint256 _value) returns (bool success) {}
function _balanceOf(address _owner) constant returns (uint256 balance) {}
function _transfer(address _to, uint256 _value) returns (bool success) {}
function _transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function _approve(address _spender, uint256 _value) returns (bool success) {}
function _allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | balanceOf | function balanceOf(address _owner) constant returns (uint256 balance) {}
| /// @param _owner The address from which the balance will be retrieved
/// @return The balance | NatSpecSingleLine | v0.4.25+commit.59dbf8f1 | bzzr://b2d8d791f292c59e65ef91dcbe45d0c20e2c0885d6878f15a1f0689365d0031d | {
"func_code_index": [
232,
309
]
} | 1,401 |
|||
HumanStandardToken | HumanStandardToken.sol | 0x39514112a90fe523615eeb407af81a880b92a419 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
function _move(address _from, address _to, uint256 _value) returns (bool success) {}
function _balanceOf(address _owner) constant returns (uint256 balance) {}
function _transfer(address _to, uint256 _value) returns (bool success) {}
function _transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function _approve(address _spender, uint256 _value) returns (bool success) {}
function _allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | transfer | function transfer(address _to, uint256 _value) returns (bool success) {}
| /// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not | NatSpecSingleLine | v0.4.25+commit.59dbf8f1 | bzzr://b2d8d791f292c59e65ef91dcbe45d0c20e2c0885d6878f15a1f0689365d0031d | {
"func_code_index": [
546,
623
]
} | 1,402 |
|||
HumanStandardToken | HumanStandardToken.sol | 0x39514112a90fe523615eeb407af81a880b92a419 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
function _move(address _from, address _to, uint256 _value) returns (bool success) {}
function _balanceOf(address _owner) constant returns (uint256 balance) {}
function _transfer(address _to, uint256 _value) returns (bool success) {}
function _transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function _approve(address _spender, uint256 _value) returns (bool success) {}
function _allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | transferFrom | function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
| /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not | NatSpecSingleLine | v0.4.25+commit.59dbf8f1 | bzzr://b2d8d791f292c59e65ef91dcbe45d0c20e2c0885d6878f15a1f0689365d0031d | {
"func_code_index": [
946,
1042
]
} | 1,403 |
|||
HumanStandardToken | HumanStandardToken.sol | 0x39514112a90fe523615eeb407af81a880b92a419 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
function _move(address _from, address _to, uint256 _value) returns (bool success) {}
function _balanceOf(address _owner) constant returns (uint256 balance) {}
function _transfer(address _to, uint256 _value) returns (bool success) {}
function _transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function _approve(address _spender, uint256 _value) returns (bool success) {}
function _allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | approve | function approve(address _spender, uint256 _value) returns (bool success) {}
| /// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not | NatSpecSingleLine | v0.4.25+commit.59dbf8f1 | bzzr://b2d8d791f292c59e65ef91dcbe45d0c20e2c0885d6878f15a1f0689365d0031d | {
"func_code_index": [
1330,
1411
]
} | 1,404 |
|||
HumanStandardToken | HumanStandardToken.sol | 0x39514112a90fe523615eeb407af81a880b92a419 | Solidity | Token | contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
function _move(address _from, address _to, uint256 _value) returns (bool success) {}
function _balanceOf(address _owner) constant returns (uint256 balance) {}
function _transfer(address _to, uint256 _value) returns (bool success) {}
function _transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function _approve(address _spender, uint256 _value) returns (bool success) {}
function _allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | allowance | function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
| /// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent | NatSpecSingleLine | v0.4.25+commit.59dbf8f1 | bzzr://b2d8d791f292c59e65ef91dcbe45d0c20e2c0885d6878f15a1f0689365d0031d | {
"func_code_index": [
1619,
1716
]
} | 1,405 |
|||
HumanStandardToken | HumanStandardToken.sol | 0x39514112a90fe523615eeb407af81a880b92a419 | Solidity | HumanStandardToken | contract HumanStandardToken is StandardToken {
function () {
//if ether is sent to this address, send it back.
throw;
}
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = 'H0.1'; //human 0.1 standard. Just an arbitrary versioning scheme.
function HumanStandardToken(
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol
) {
balances[msg.sender] = _initialAmount; // Give the creator all initial tokens
totalSupply = _initialAmount; // Update total supply
name = _tokenName; // Set the name for display purposes
decimals = _decimalUnits; // Amount of decimals for display purposes
symbol = _tokenSymbol; // Set the symbol for display purposes
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | /*
This Token Contract implements the standard token functionality (https://github.com/ethereum/EIPs/issues/20) as well as the following OPTIONAL extras intended for use by humans.
In other words. This is intended for deployment in something like a Token Factory or Mist wallet, and then used by humans.
Imagine coins, currencies, shares, voting weight, etc.
Machine-based, rapid creation of many tokens would not necessarily need these extra features or will be minted in other manners.
1) Initial Finite Supply (upon creation one specifies how much is minted).
2) In the absence of a token registry: Optional Decimal, Symbol & Name.
3) Optional approveAndCall() functionality to notify a contract if an approval() has occurred.
.*/ | Comment | HumanStandardToken | function HumanStandardToken(
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol
) {
balances[msg.sender] = _initialAmount; // Give the creator all initial tokens
totalSupply = _initialAmount; // Update total supply
name = _tokenName; // Set the name for display purposes
decimals = _decimalUnits; // Amount of decimals for display purposes
symbol = _tokenSymbol; // Set the symbol for display purposes
}
| //human 0.1 standard. Just an arbitrary versioning scheme. | LineComment | v0.4.25+commit.59dbf8f1 | bzzr://b2d8d791f292c59e65ef91dcbe45d0c20e2c0885d6878f15a1f0689365d0031d | {
"func_code_index": [
927,
1591
]
} | 1,406 |
|
HumanStandardToken | HumanStandardToken.sol | 0x39514112a90fe523615eeb407af81a880b92a419 | Solidity | HumanStandardToken | contract HumanStandardToken is StandardToken {
function () {
//if ether is sent to this address, send it back.
throw;
}
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = 'H0.1'; //human 0.1 standard. Just an arbitrary versioning scheme.
function HumanStandardToken(
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol
) {
balances[msg.sender] = _initialAmount; // Give the creator all initial tokens
totalSupply = _initialAmount; // Update total supply
name = _tokenName; // Set the name for display purposes
decimals = _decimalUnits; // Amount of decimals for display purposes
symbol = _tokenSymbol; // Set the symbol for display purposes
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | /*
This Token Contract implements the standard token functionality (https://github.com/ethereum/EIPs/issues/20) as well as the following OPTIONAL extras intended for use by humans.
In other words. This is intended for deployment in something like a Token Factory or Mist wallet, and then used by humans.
Imagine coins, currencies, shares, voting weight, etc.
Machine-based, rapid creation of many tokens would not necessarily need these extra features or will be minted in other manners.
1) Initial Finite Supply (upon creation one specifies how much is minted).
2) In the absence of a token registry: Optional Decimal, Symbol & Name.
3) Optional approveAndCall() functionality to notify a contract if an approval() has occurred.
.*/ | Comment | approveAndCall | function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
| /* Approves and then calls the receiving contract */ | Comment | v0.4.25+commit.59dbf8f1 | bzzr://b2d8d791f292c59e65ef91dcbe45d0c20e2c0885d6878f15a1f0689365d0031d | {
"func_code_index": [
1652,
2457
]
} | 1,407 |
|
ALCXRewarder | contracts/MasterChef.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | IMigratorChef | interface IMigratorChef {
// Perform LP token migration from legacy UniswapV2 to SushiSwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to UniswapV2 LP tokens.
// SushiSwap must mint EXACTLY the same amount of SushiSwap LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrate(IERC20 token) external returns (IERC20);
} | migrate | function migrate(IERC20 token) external returns (IERC20);
| // Perform LP token migration from legacy UniswapV2 to SushiSwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to UniswapV2 LP tokens.
// SushiSwap must mint EXACTLY the same amount of SushiSwap LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful! | LineComment | v0.6.12+commit.27d51765 | {
"func_code_index": [
508,
566
]
} | 1,408 |
||||
ALCXRewarder | contracts/MasterChef.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChef | contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.
uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
}
// The SUSHI TOKEN!
SushiToken public sushi;
// Dev address.
address public devaddr;
// Block number when bonus SUSHI period ends.
uint256 public bonusEndBlock;
// SUSHI tokens created per block.
uint256 public sushiPerBlock;
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSHI mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
SushiToken _sushi,
address _devaddr,
uint256 _sushiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
sushi = _sushi;
devaddr = _devaddr;
sushiPerBlock = _sushiPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })
);
}
// Update the given pool's SUSHI allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(_to.sub(bonusEndBlock));
}
}
// View function to see pending SUSHIs on frontend.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sushi.mint(devaddr, sushiReward.div(10));
sushi.mint(address(this), sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SUSHI allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = sushi.balanceOf(address(this));
if (_amount > sushiBal) {
sushi.transfer(_to, sushiBal);
} else {
sushi.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // MasterChef is the master of Sushi. He can make Sushi and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SUSHI is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | add | function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })
);
}
| // Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. | LineComment | v0.6.12+commit.27d51765 | {
"func_code_index": [
2753,
3174
]
} | 1,409 |
||
ALCXRewarder | contracts/MasterChef.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChef | contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.
uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
}
// The SUSHI TOKEN!
SushiToken public sushi;
// Dev address.
address public devaddr;
// Block number when bonus SUSHI period ends.
uint256 public bonusEndBlock;
// SUSHI tokens created per block.
uint256 public sushiPerBlock;
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSHI mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
SushiToken _sushi,
address _devaddr,
uint256 _sushiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
sushi = _sushi;
devaddr = _devaddr;
sushiPerBlock = _sushiPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })
);
}
// Update the given pool's SUSHI allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(_to.sub(bonusEndBlock));
}
}
// View function to see pending SUSHIs on frontend.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sushi.mint(devaddr, sushiReward.div(10));
sushi.mint(address(this), sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SUSHI allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = sushi.balanceOf(address(this));
if (_amount > sushiBal) {
sushi.transfer(_to, sushiBal);
} else {
sushi.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // MasterChef is the master of Sushi. He can make Sushi and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SUSHI is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | set | function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
| // Update the given pool's SUSHI allocation point. Can only be called by the owner. | LineComment | v0.6.12+commit.27d51765 | {
"func_code_index": [
3261,
3533
]
} | 1,410 |
||
ALCXRewarder | contracts/MasterChef.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChef | contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.
uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
}
// The SUSHI TOKEN!
SushiToken public sushi;
// Dev address.
address public devaddr;
// Block number when bonus SUSHI period ends.
uint256 public bonusEndBlock;
// SUSHI tokens created per block.
uint256 public sushiPerBlock;
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSHI mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
SushiToken _sushi,
address _devaddr,
uint256 _sushiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
sushi = _sushi;
devaddr = _devaddr;
sushiPerBlock = _sushiPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })
);
}
// Update the given pool's SUSHI allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(_to.sub(bonusEndBlock));
}
}
// View function to see pending SUSHIs on frontend.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sushi.mint(devaddr, sushiReward.div(10));
sushi.mint(address(this), sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SUSHI allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = sushi.balanceOf(address(this));
if (_amount > sushiBal) {
sushi.transfer(_to, sushiBal);
} else {
sushi.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // MasterChef is the master of Sushi. He can make Sushi and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SUSHI is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | setMigrator | function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
| // Set the migrator contract. Can only be called by the owner. | LineComment | v0.6.12+commit.27d51765 | {
"func_code_index": [
3599,
3691
]
} | 1,411 |
||
ALCXRewarder | contracts/MasterChef.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChef | contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.
uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
}
// The SUSHI TOKEN!
SushiToken public sushi;
// Dev address.
address public devaddr;
// Block number when bonus SUSHI period ends.
uint256 public bonusEndBlock;
// SUSHI tokens created per block.
uint256 public sushiPerBlock;
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSHI mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
SushiToken _sushi,
address _devaddr,
uint256 _sushiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
sushi = _sushi;
devaddr = _devaddr;
sushiPerBlock = _sushiPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })
);
}
// Update the given pool's SUSHI allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(_to.sub(bonusEndBlock));
}
}
// View function to see pending SUSHIs on frontend.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sushi.mint(devaddr, sushiReward.div(10));
sushi.mint(address(this), sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SUSHI allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = sushi.balanceOf(address(this));
if (_amount > sushiBal) {
sushi.transfer(_to, sushiBal);
} else {
sushi.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // MasterChef is the master of Sushi. He can make Sushi and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SUSHI is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | migrate | function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
| // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. | LineComment | v0.6.12+commit.27d51765 | {
"func_code_index": [
3804,
4236
]
} | 1,412 |
||
ALCXRewarder | contracts/MasterChef.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChef | contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.
uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
}
// The SUSHI TOKEN!
SushiToken public sushi;
// Dev address.
address public devaddr;
// Block number when bonus SUSHI period ends.
uint256 public bonusEndBlock;
// SUSHI tokens created per block.
uint256 public sushiPerBlock;
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSHI mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
SushiToken _sushi,
address _devaddr,
uint256 _sushiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
sushi = _sushi;
devaddr = _devaddr;
sushiPerBlock = _sushiPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })
);
}
// Update the given pool's SUSHI allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(_to.sub(bonusEndBlock));
}
}
// View function to see pending SUSHIs on frontend.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sushi.mint(devaddr, sushiReward.div(10));
sushi.mint(address(this), sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SUSHI allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = sushi.balanceOf(address(this));
if (_amount > sushiBal) {
sushi.transfer(_to, sushiBal);
} else {
sushi.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // MasterChef is the master of Sushi. He can make Sushi and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SUSHI is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | getMultiplier | function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(_to.sub(bonusEndBlock));
}
}
| // Return reward multiplier over the given _from to _to block. | LineComment | v0.6.12+commit.27d51765 | {
"func_code_index": [
4302,
4632
]
} | 1,413 |
||
ALCXRewarder | contracts/MasterChef.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChef | contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.
uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
}
// The SUSHI TOKEN!
SushiToken public sushi;
// Dev address.
address public devaddr;
// Block number when bonus SUSHI period ends.
uint256 public bonusEndBlock;
// SUSHI tokens created per block.
uint256 public sushiPerBlock;
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSHI mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
SushiToken _sushi,
address _devaddr,
uint256 _sushiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
sushi = _sushi;
devaddr = _devaddr;
sushiPerBlock = _sushiPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })
);
}
// Update the given pool's SUSHI allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(_to.sub(bonusEndBlock));
}
}
// View function to see pending SUSHIs on frontend.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sushi.mint(devaddr, sushiReward.div(10));
sushi.mint(address(this), sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SUSHI allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = sushi.balanceOf(address(this));
if (_amount > sushiBal) {
sushi.transfer(_to, sushiBal);
} else {
sushi.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // MasterChef is the master of Sushi. He can make Sushi and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SUSHI is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | pendingSushi | function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
}
| // View function to see pending SUSHIs on frontend. | LineComment | v0.6.12+commit.27d51765 | {
"func_code_index": [
4687,
5373
]
} | 1,414 |
||
ALCXRewarder | contracts/MasterChef.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChef | contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.
uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
}
// The SUSHI TOKEN!
SushiToken public sushi;
// Dev address.
address public devaddr;
// Block number when bonus SUSHI period ends.
uint256 public bonusEndBlock;
// SUSHI tokens created per block.
uint256 public sushiPerBlock;
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSHI mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
SushiToken _sushi,
address _devaddr,
uint256 _sushiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
sushi = _sushi;
devaddr = _devaddr;
sushiPerBlock = _sushiPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })
);
}
// Update the given pool's SUSHI allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(_to.sub(bonusEndBlock));
}
}
// View function to see pending SUSHIs on frontend.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sushi.mint(devaddr, sushiReward.div(10));
sushi.mint(address(this), sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SUSHI allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = sushi.balanceOf(address(this));
if (_amount > sushiBal) {
sushi.transfer(_to, sushiBal);
} else {
sushi.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // MasterChef is the master of Sushi. He can make Sushi and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SUSHI is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | massUpdatePools | function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
| // Update reward vairables for all pools. Be careful of gas spending! | LineComment | v0.6.12+commit.27d51765 | {
"func_code_index": [
5446,
5592
]
} | 1,415 |
||
ALCXRewarder | contracts/MasterChef.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChef | contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.
uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
}
// The SUSHI TOKEN!
SushiToken public sushi;
// Dev address.
address public devaddr;
// Block number when bonus SUSHI period ends.
uint256 public bonusEndBlock;
// SUSHI tokens created per block.
uint256 public sushiPerBlock;
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSHI mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
SushiToken _sushi,
address _devaddr,
uint256 _sushiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
sushi = _sushi;
devaddr = _devaddr;
sushiPerBlock = _sushiPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })
);
}
// Update the given pool's SUSHI allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(_to.sub(bonusEndBlock));
}
}
// View function to see pending SUSHIs on frontend.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sushi.mint(devaddr, sushiReward.div(10));
sushi.mint(address(this), sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SUSHI allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = sushi.balanceOf(address(this));
if (_amount > sushiBal) {
sushi.transfer(_to, sushiBal);
} else {
sushi.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // MasterChef is the master of Sushi. He can make Sushi and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SUSHI is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | updatePool | function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sushi.mint(devaddr, sushiReward.div(10));
sushi.mint(address(this), sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
| // Update reward variables of the given pool to be up-to-date. | LineComment | v0.6.12+commit.27d51765 | {
"func_code_index": [
5658,
6331
]
} | 1,416 |
||
ALCXRewarder | contracts/MasterChef.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChef | contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.
uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
}
// The SUSHI TOKEN!
SushiToken public sushi;
// Dev address.
address public devaddr;
// Block number when bonus SUSHI period ends.
uint256 public bonusEndBlock;
// SUSHI tokens created per block.
uint256 public sushiPerBlock;
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSHI mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
SushiToken _sushi,
address _devaddr,
uint256 _sushiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
sushi = _sushi;
devaddr = _devaddr;
sushiPerBlock = _sushiPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })
);
}
// Update the given pool's SUSHI allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(_to.sub(bonusEndBlock));
}
}
// View function to see pending SUSHIs on frontend.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sushi.mint(devaddr, sushiReward.div(10));
sushi.mint(address(this), sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SUSHI allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = sushi.balanceOf(address(this));
if (_amount > sushiBal) {
sushi.transfer(_to, sushiBal);
} else {
sushi.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // MasterChef is the master of Sushi. He can make Sushi and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SUSHI is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | deposit | function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
| // Deposit LP tokens to MasterChef for SUSHI allocation. | LineComment | v0.6.12+commit.27d51765 | {
"func_code_index": [
6391,
6964
]
} | 1,417 |
||
ALCXRewarder | contracts/MasterChef.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChef | contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.
uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
}
// The SUSHI TOKEN!
SushiToken public sushi;
// Dev address.
address public devaddr;
// Block number when bonus SUSHI period ends.
uint256 public bonusEndBlock;
// SUSHI tokens created per block.
uint256 public sushiPerBlock;
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSHI mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
SushiToken _sushi,
address _devaddr,
uint256 _sushiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
sushi = _sushi;
devaddr = _devaddr;
sushiPerBlock = _sushiPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })
);
}
// Update the given pool's SUSHI allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(_to.sub(bonusEndBlock));
}
}
// View function to see pending SUSHIs on frontend.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sushi.mint(devaddr, sushiReward.div(10));
sushi.mint(address(this), sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SUSHI allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = sushi.balanceOf(address(this));
if (_amount > sushiBal) {
sushi.transfer(_to, sushiBal);
} else {
sushi.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // MasterChef is the master of Sushi. He can make Sushi and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SUSHI is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | withdraw | function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
| // Withdraw LP tokens from MasterChef. | LineComment | v0.6.12+commit.27d51765 | {
"func_code_index": [
7006,
7588
]
} | 1,418 |
||
ALCXRewarder | contracts/MasterChef.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChef | contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.
uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
}
// The SUSHI TOKEN!
SushiToken public sushi;
// Dev address.
address public devaddr;
// Block number when bonus SUSHI period ends.
uint256 public bonusEndBlock;
// SUSHI tokens created per block.
uint256 public sushiPerBlock;
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSHI mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
SushiToken _sushi,
address _devaddr,
uint256 _sushiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
sushi = _sushi;
devaddr = _devaddr;
sushiPerBlock = _sushiPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })
);
}
// Update the given pool's SUSHI allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(_to.sub(bonusEndBlock));
}
}
// View function to see pending SUSHIs on frontend.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sushi.mint(devaddr, sushiReward.div(10));
sushi.mint(address(this), sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SUSHI allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = sushi.balanceOf(address(this));
if (_amount > sushiBal) {
sushi.transfer(_to, sushiBal);
} else {
sushi.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // MasterChef is the master of Sushi. He can make Sushi and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SUSHI is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | emergencyWithdraw | function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
| // Withdraw without caring about rewards. EMERGENCY ONLY. | LineComment | v0.6.12+commit.27d51765 | {
"func_code_index": [
7649,
7960
]
} | 1,419 |
||
ALCXRewarder | contracts/MasterChef.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChef | contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.
uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
}
// The SUSHI TOKEN!
SushiToken public sushi;
// Dev address.
address public devaddr;
// Block number when bonus SUSHI period ends.
uint256 public bonusEndBlock;
// SUSHI tokens created per block.
uint256 public sushiPerBlock;
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSHI mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
SushiToken _sushi,
address _devaddr,
uint256 _sushiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
sushi = _sushi;
devaddr = _devaddr;
sushiPerBlock = _sushiPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })
);
}
// Update the given pool's SUSHI allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(_to.sub(bonusEndBlock));
}
}
// View function to see pending SUSHIs on frontend.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sushi.mint(devaddr, sushiReward.div(10));
sushi.mint(address(this), sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SUSHI allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = sushi.balanceOf(address(this));
if (_amount > sushiBal) {
sushi.transfer(_to, sushiBal);
} else {
sushi.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // MasterChef is the master of Sushi. He can make Sushi and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SUSHI is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | safeSushiTransfer | function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = sushi.balanceOf(address(this));
if (_amount > sushiBal) {
sushi.transfer(_to, sushiBal);
} else {
sushi.transfer(_to, _amount);
}
}
| // Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs. | LineComment | v0.6.12+commit.27d51765 | {
"func_code_index": [
8066,
8300
]
} | 1,420 |
||
ALCXRewarder | contracts/MasterChef.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChef | contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.
uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
}
// The SUSHI TOKEN!
SushiToken public sushi;
// Dev address.
address public devaddr;
// Block number when bonus SUSHI period ends.
uint256 public bonusEndBlock;
// SUSHI tokens created per block.
uint256 public sushiPerBlock;
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSHI mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
SushiToken _sushi,
address _devaddr,
uint256 _sushiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
sushi = _sushi;
devaddr = _devaddr;
sushiPerBlock = _sushiPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })
);
}
// Update the given pool's SUSHI allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(_to.sub(bonusEndBlock));
}
}
// View function to see pending SUSHIs on frontend.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sushi.mint(devaddr, sushiReward.div(10));
sushi.mint(address(this), sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SUSHI allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = sushi.balanceOf(address(this));
if (_amount > sushiBal) {
sushi.transfer(_to, sushiBal);
} else {
sushi.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // MasterChef is the master of Sushi. He can make Sushi and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SUSHI is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | dev | function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
| // Update dev address by the previous dev. | LineComment | v0.6.12+commit.27d51765 | {
"func_code_index": [
8346,
8458
]
} | 1,421 |
||
ExecutionProxy | src/rollup/contracts/MetaProxyFactory.sol | 0x32bbdef16b4e0404191a8b879956280539036dea | Solidity | MetaProxyFactory | contract MetaProxyFactory {
/// @dev Creates a child with metadata from calldata.
/// Copies everything from calldata except the first 4 bytes.
function _metaProxyFromCalldata () internal returns (address addr) {
// the following assembly code (init code + contract code) constructs a metaproxy.
assembly {
// load free memory pointer as per solidity convention
let start := mload(64)
// copy
let ptr := start
// deploy code (11 bytes) + first part of the proxy (21 bytes)
mstore(ptr, 0x600b380380600b3d393df3363d3d373d3d3d3d60368038038091363936013d73)
ptr := add(ptr, 32)
// store the address of the contract to be called
mstore(ptr, shl(96, address()))
// 20 bytes
ptr := add(ptr, 20)
// the remaining proxy code...
mstore(ptr, 0x5af43d3d93803e603457fd5bf300000000000000000000000000000000000000)
// ...13 bytes
ptr := add(ptr, 13)
// now calculdate the size and copy the metadata
// - 4 bytes function signature
let size := sub(calldatasize(), 4)
// copy
calldatacopy(ptr, 4, size)
ptr := add(ptr, size)
// store the size of the metadata at the end of the bytecode
mstore(ptr, size)
ptr := add(ptr, 32)
// The size is deploy code + contract code + calldatasize - 4 + 32.
addr := create(0, start, sub(ptr, start))
}
}
} | // Audit-1: ok | LineComment | _metaProxyFromCalldata | function _metaProxyFromCalldata () internal returns (address addr) {
// the following assembly code (init code + contract code) constructs a metaproxy.
assembly {
// load free memory pointer as per solidity convention
let start := mload(64)
// copy
let ptr := start
// deploy code (11 bytes) + first part of the proxy (21 bytes)
mstore(ptr, 0x600b380380600b3d393df3363d3d373d3d3d3d60368038038091363936013d73)
ptr := add(ptr, 32)
// store the address of the contract to be called
mstore(ptr, shl(96, address()))
// 20 bytes
ptr := add(ptr, 20)
// the remaining proxy code...
mstore(ptr, 0x5af43d3d93803e603457fd5bf300000000000000000000000000000000000000)
// ...13 bytes
ptr := add(ptr, 13)
// now calculdate the size and copy the metadata
// - 4 bytes function signature
let size := sub(calldatasize(), 4)
// copy
calldatacopy(ptr, 4, size)
ptr := add(ptr, size)
// store the size of the metadata at the end of the bytecode
mstore(ptr, size)
ptr := add(ptr, 32)
// The size is deploy code + contract code + calldatasize - 4 + 32.
addr := create(0, start, sub(ptr, start))
}
}
| /// @dev Creates a child with metadata from calldata.
/// Copies everything from calldata except the first 4 bytes. | NatSpecSingleLine | v0.7.6+commit.7338295f | Unlicense | none | {
"func_code_index": [
148,
1398
]
} | 1,422 |
ALCOIN | ALCOIN.sol | 0x327e963ee999184618e33e01b4ae1b9bccf328b4 | Solidity | ALCOIN | contract ALCOIN {
/* Public variables of the token */
string public standard = 'Token 0.1';
string public name;
string public symbol;
uint8 public decimals;
uint256 public initialSupply;
uint256 public totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* Initializes contract with initial supply tokens to the creator of the contract */
function ALCOIN() {
initialSupply = 500000000000;
name = "LATINO AMERICA COIN";
decimals = 3;
symbol = "ALC";
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
}
/* This unnamed function is called whenever someone tries to send ether to it */
function () {
throw; // Prevents accidental sending of ether
}
} | ALCOIN | function ALCOIN() {
initialSupply = 500000000000;
name = "LATINO AMERICA COIN";
decimals = 3;
symbol = "ALC";
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
}
| /* Initializes contract with initial supply tokens to the creator of the contract */ | Comment | v0.4.11+commit.68ef5810 | bzzr://03f3689a7d277d6dfd8339acaf0de3c3bb3a230f0a45a0234b23711bfa7b95a7 | {
"func_code_index": [
525,
916
]
} | 1,423 |
|||
ALCOIN | ALCOIN.sol | 0x327e963ee999184618e33e01b4ae1b9bccf328b4 | Solidity | ALCOIN | contract ALCOIN {
/* Public variables of the token */
string public standard = 'Token 0.1';
string public name;
string public symbol;
uint8 public decimals;
uint256 public initialSupply;
uint256 public totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* Initializes contract with initial supply tokens to the creator of the contract */
function ALCOIN() {
initialSupply = 500000000000;
name = "LATINO AMERICA COIN";
decimals = 3;
symbol = "ALC";
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
}
/* This unnamed function is called whenever someone tries to send ether to it */
function () {
throw; // Prevents accidental sending of ether
}
} | transfer | function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
}
| /* Send coins */ | Comment | v0.4.11+commit.68ef5810 | bzzr://03f3689a7d277d6dfd8339acaf0de3c3bb3a230f0a45a0234b23711bfa7b95a7 | {
"func_code_index": [
941,
1375
]
} | 1,424 |
|||
ALCOIN | ALCOIN.sol | 0x327e963ee999184618e33e01b4ae1b9bccf328b4 | Solidity | ALCOIN | contract ALCOIN {
/* Public variables of the token */
string public standard = 'Token 0.1';
string public name;
string public symbol;
uint8 public decimals;
uint256 public initialSupply;
uint256 public totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* Initializes contract with initial supply tokens to the creator of the contract */
function ALCOIN() {
initialSupply = 500000000000;
name = "LATINO AMERICA COIN";
decimals = 3;
symbol = "ALC";
balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
totalSupply = initialSupply; // Update total supply
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
}
/* This unnamed function is called whenever someone tries to send ether to it */
function () {
throw; // Prevents accidental sending of ether
}
} | function () {
throw; // Prevents accidental sending of ether
}
| /* This unnamed function is called whenever someone tries to send ether to it */ | Comment | v0.4.11+commit.68ef5810 | bzzr://03f3689a7d277d6dfd8339acaf0de3c3bb3a230f0a45a0234b23711bfa7b95a7 | {
"func_code_index": [
1464,
1549
]
} | 1,425 |
||||
ExecutionProxy | src/rollup/contracts/ExecutionProxy.sol | 0x32bbdef16b4e0404191a8b879956280539036dea | Solidity | ExecutionProxy | contract ExecutionProxy is MetaProxyFactory {
/// @notice keeps track of already executed permits
mapping (bytes32 => bool) public executed;
event ProxyCreated(address indexed bridge, address indexed vault, address proxy);
/// @notice Returns the metadata of this (MetaProxy) contract.
/// Only relevant with contracts created via the MetaProxy.
/// @dev This function is aimed to be invoked with- & without a call.
function getMetadata () public pure returns (
address bridge,
address vault
) {
assembly {
// calldata layout:
// [ arbitrary data... ] [ metadata... ] [ size of metadata 32 bytes ]
bridge := calldataload(sub(calldatasize(), 96))
vault := calldataload(sub(calldatasize(), 64))
}
}
/// @notice MetaProxy construction via calldata.
/// @param bridge is the address of the habitat rollup
/// @param vault is the L2 vault used for governance.
function createProxy (address bridge, address vault) external returns (address addr) {
addr = MetaProxyFactory._metaProxyFromCalldata();
emit ProxyCreated(bridge, vault, addr);
}
/// @notice Executes a set of contract calls `actions` if there is a valid
/// permit on the rollup bridge for `proposalId` and `actions`.
function execute (bytes32 proposalId, bytes memory actions) external {
(address bridge, address vault) = getMetadata();
require(executed[proposalId] == false, 'already executed');
require(
IBridge(bridge).executionPermit(vault, proposalId) == keccak256(actions),
'wrong permit'
);
// mark it as executed
executed[proposalId] = true;
// execute
assembly {
// Note: we use `callvalue()` instead of `0`
let ptr := add(actions, 32)
let max := add(ptr, mload(actions))
for { } lt(ptr, max) { } {
let addr := mload(ptr)
ptr := add(ptr, 32)
let size := mload(ptr)
ptr := add(ptr, 32)
let success := call(gas(), addr, callvalue(), ptr, size, callvalue(), callvalue())
if iszero(success) {
// failed, copy the error
returndatacopy(callvalue(), callvalue(), returndatasize())
revert(callvalue(), returndatasize())
}
ptr := add(ptr, size)
}
}
}
} | // Audit-1: ok | LineComment | getMetadata | function getMetadata () public pure returns (
address bridge,
address vault
) {
assembly {
// calldata layout:
// [ arbitrary data... ] [ metadata... ] [ size of metadata 32 bytes ]
bridge := calldataload(sub(calldatasize(), 96))
vault := calldataload(sub(calldatasize(), 64))
}
}
| /// @notice Returns the metadata of this (MetaProxy) contract.
/// Only relevant with contracts created via the MetaProxy.
/// @dev This function is aimed to be invoked with- & without a call. | NatSpecSingleLine | v0.7.6+commit.7338295f | Unlicense | none | {
"func_code_index": [
430,
756
]
} | 1,426 |
ExecutionProxy | src/rollup/contracts/ExecutionProxy.sol | 0x32bbdef16b4e0404191a8b879956280539036dea | Solidity | ExecutionProxy | contract ExecutionProxy is MetaProxyFactory {
/// @notice keeps track of already executed permits
mapping (bytes32 => bool) public executed;
event ProxyCreated(address indexed bridge, address indexed vault, address proxy);
/// @notice Returns the metadata of this (MetaProxy) contract.
/// Only relevant with contracts created via the MetaProxy.
/// @dev This function is aimed to be invoked with- & without a call.
function getMetadata () public pure returns (
address bridge,
address vault
) {
assembly {
// calldata layout:
// [ arbitrary data... ] [ metadata... ] [ size of metadata 32 bytes ]
bridge := calldataload(sub(calldatasize(), 96))
vault := calldataload(sub(calldatasize(), 64))
}
}
/// @notice MetaProxy construction via calldata.
/// @param bridge is the address of the habitat rollup
/// @param vault is the L2 vault used for governance.
function createProxy (address bridge, address vault) external returns (address addr) {
addr = MetaProxyFactory._metaProxyFromCalldata();
emit ProxyCreated(bridge, vault, addr);
}
/// @notice Executes a set of contract calls `actions` if there is a valid
/// permit on the rollup bridge for `proposalId` and `actions`.
function execute (bytes32 proposalId, bytes memory actions) external {
(address bridge, address vault) = getMetadata();
require(executed[proposalId] == false, 'already executed');
require(
IBridge(bridge).executionPermit(vault, proposalId) == keccak256(actions),
'wrong permit'
);
// mark it as executed
executed[proposalId] = true;
// execute
assembly {
// Note: we use `callvalue()` instead of `0`
let ptr := add(actions, 32)
let max := add(ptr, mload(actions))
for { } lt(ptr, max) { } {
let addr := mload(ptr)
ptr := add(ptr, 32)
let size := mload(ptr)
ptr := add(ptr, 32)
let success := call(gas(), addr, callvalue(), ptr, size, callvalue(), callvalue())
if iszero(success) {
// failed, copy the error
returndatacopy(callvalue(), callvalue(), returndatasize())
revert(callvalue(), returndatasize())
}
ptr := add(ptr, size)
}
}
}
} | // Audit-1: ok | LineComment | createProxy | function createProxy (address bridge, address vault) external returns (address addr) {
addr = MetaProxyFactory._metaProxyFromCalldata();
emit ProxyCreated(bridge, vault, addr);
}
| /// @notice MetaProxy construction via calldata.
/// @param bridge is the address of the habitat rollup
/// @param vault is the L2 vault used for governance. | NatSpecSingleLine | v0.7.6+commit.7338295f | Unlicense | none | {
"func_code_index": [
922,
1112
]
} | 1,427 |
ExecutionProxy | src/rollup/contracts/ExecutionProxy.sol | 0x32bbdef16b4e0404191a8b879956280539036dea | Solidity | ExecutionProxy | contract ExecutionProxy is MetaProxyFactory {
/// @notice keeps track of already executed permits
mapping (bytes32 => bool) public executed;
event ProxyCreated(address indexed bridge, address indexed vault, address proxy);
/// @notice Returns the metadata of this (MetaProxy) contract.
/// Only relevant with contracts created via the MetaProxy.
/// @dev This function is aimed to be invoked with- & without a call.
function getMetadata () public pure returns (
address bridge,
address vault
) {
assembly {
// calldata layout:
// [ arbitrary data... ] [ metadata... ] [ size of metadata 32 bytes ]
bridge := calldataload(sub(calldatasize(), 96))
vault := calldataload(sub(calldatasize(), 64))
}
}
/// @notice MetaProxy construction via calldata.
/// @param bridge is the address of the habitat rollup
/// @param vault is the L2 vault used for governance.
function createProxy (address bridge, address vault) external returns (address addr) {
addr = MetaProxyFactory._metaProxyFromCalldata();
emit ProxyCreated(bridge, vault, addr);
}
/// @notice Executes a set of contract calls `actions` if there is a valid
/// permit on the rollup bridge for `proposalId` and `actions`.
function execute (bytes32 proposalId, bytes memory actions) external {
(address bridge, address vault) = getMetadata();
require(executed[proposalId] == false, 'already executed');
require(
IBridge(bridge).executionPermit(vault, proposalId) == keccak256(actions),
'wrong permit'
);
// mark it as executed
executed[proposalId] = true;
// execute
assembly {
// Note: we use `callvalue()` instead of `0`
let ptr := add(actions, 32)
let max := add(ptr, mload(actions))
for { } lt(ptr, max) { } {
let addr := mload(ptr)
ptr := add(ptr, 32)
let size := mload(ptr)
ptr := add(ptr, 32)
let success := call(gas(), addr, callvalue(), ptr, size, callvalue(), callvalue())
if iszero(success) {
// failed, copy the error
returndatacopy(callvalue(), callvalue(), returndatasize())
revert(callvalue(), returndatasize())
}
ptr := add(ptr, size)
}
}
}
} | // Audit-1: ok | LineComment | execute | function execute (bytes32 proposalId, bytes memory actions) external {
(address bridge, address vault) = getMetadata();
require(executed[proposalId] == false, 'already executed');
require(
IBridge(bridge).executionPermit(vault, proposalId) == keccak256(actions),
'wrong permit'
);
// mark it as executed
executed[proposalId] = true;
// execute
assembly {
// Note: we use `callvalue()` instead of `0`
let ptr := add(actions, 32)
let max := add(ptr, mload(actions))
for { } lt(ptr, max) { } {
let addr := mload(ptr)
ptr := add(ptr, 32)
let size := mload(ptr)
ptr := add(ptr, 32)
let success := call(gas(), addr, callvalue(), ptr, size, callvalue(), callvalue())
if iszero(success) {
// failed, copy the error
returndatacopy(callvalue(), callvalue(), returndatasize())
revert(callvalue(), returndatasize())
}
ptr := add(ptr, size)
}
}
}
| /// @notice Executes a set of contract calls `actions` if there is a valid
/// permit on the rollup bridge for `proposalId` and `actions`. | NatSpecSingleLine | v0.7.6+commit.7338295f | Unlicense | none | {
"func_code_index": [
1257,
2270
]
} | 1,428 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | totalSupply | function totalSupply() external view returns (uint256);
| /**
* @dev Returns the amount of tokens in existence.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
95,
155
]
} | 1,429 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address account) external view returns (uint256);
| /**
* @dev Returns the amount of tokens owned by `account`.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
238,
311
]
} | 1,430 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | transfer | function transfer(address recipient, uint256 amount) external returns (bool);
| /**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
535,
617
]
} | 1,431 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | allowance | function allowance(address owner, address spender) external view returns (uint256);
| /**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
896,
984
]
} | 1,432 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | approve | function approve(address spender, uint256 amount) external returns (bool);
| /**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
1648,
1727
]
} | 1,433 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | IERC20 | interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | transferFrom | function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
| /**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
2040,
2142
]
} | 1,434 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | add | function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
| /**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
259,
445
]
} | 1,435 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | sub | function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
| /**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
723,
864
]
} | 1,436 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | sub | function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
| /**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
1162,
1359
]
} | 1,437 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | 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-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
| /**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
1613,
2089
]
} | 1,438 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | div | function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
| /**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
2560,
2697
]
} | 1,439 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | div | function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
| /**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
3188,
3471
]
} | 1,440 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | mod | function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
| /**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
3931,
4066
]
} | 1,441 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | SafeMath | library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} | /**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/ | NatSpecMultiLine | mod | function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
| /**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
4546,
4717
]
} | 1,442 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | isContract | function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
| /**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
606,
1230
]
} | 1,443 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | sendValue | function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
| /**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
2160,
2562
]
} | 1,444 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCall | function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
| /**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
3318,
3496
]
} | 1,445 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCall | function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
3721,
3922
]
} | 1,446 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCallWithValue | function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
4292,
4523
]
} | 1,447 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | Address | library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | /**
* @dev Collection of functions related to the address type
*/ | NatSpecMultiLine | functionCallWithValue | function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
| /**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
4774,
5095
]
} | 1,448 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | Ownable | contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | owner | function owner() public view returns (address) {
return _owner;
}
| /**
* @dev Returns the address of the current owner.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
497,
581
]
} | 1,449 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | Ownable | contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | renounceOwnership | function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
| /**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
1139,
1292
]
} | 1,450 |
BOBO | BOBO.sol | 0xbd84b793bdd6e0127d0f31ca5fb7280f4444e77d | Solidity | Ownable | contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
} | /**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/ | NatSpecMultiLine | transferOwnership | function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| /**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/ | NatSpecMultiLine | v0.6.12+commit.27d51765 | MIT | ipfs://bd890d33a759b4665a17c80681b398963ba35bc465018cc666f43d9d755655a7 | {
"func_code_index": [
1442,
1691
]
} | 1,451 |
MacTama | MacTama.sol | 0x3ef636244d141e50ddc2232d8b70ed68a9088f66 | Solidity | MacTama | contract MacTama is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
uint8 private _decimals = 9;
string private _name = "MacTama";
string private _symbol = "$MCTAMA";
uint256 private _tTotal = 1000 * 10**9 * 10**uint256(_decimals);
// % to holders
uint256 public defaultTaxFee = 0;
uint256 public _taxFee = defaultTaxFee;
uint256 private _previousTaxFee = _taxFee;
// % to swap & send to marketing wallet
uint256 public defaultMarketingFee = 10;
uint256 public _marketingFee = defaultMarketingFee;
uint256 private _previousMarketingFee = _marketingFee;
uint256 public _marketingFee4Sellers = 10;
bool public feesOnSellersAndBuyers = true;
uint256 public _maxTxAmount = _tTotal.div(1).div(66);
uint256 public numTokensToExchangeForMarketing = _tTotal.div(100).div(100);
address payable public marketingWallet = payable(0xd9e18d0d73f33C384453d63D5A4dBEeeACc4829A);
//
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
mapping (address => bool) public _isBlacklisted;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tFeeTotal;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndSend;
bool public SwapAndSendEnabled = true;
event SwapAndSendEnabledUpdated(bool enabled);
modifier lockTheSwap {
inSwapAndSend = true;
_;
inSwapAndSend = false;
}
constructor () {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function excludeFromFee(address account) public onlyOwner() {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner() {
_isExcludedFromFee[account] = false;
}
function removeAllFee() private {
if(_taxFee == 0 && _marketingFee == 0) return;
_previousTaxFee = _taxFee;
_previousMarketingFee = _marketingFee;
_taxFee = 0;
_marketingFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_marketingFee = _previousMarketingFee;
}
//to recieve ETH
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function addToBlackList(address[] calldata addresses) external onlyOwner {
for (uint256 i; i < addresses.length; ++i) {
_isBlacklisted[addresses[i]] = true;
}
}
function removeFromBlackList(address account) external onlyOwner {
_isBlacklisted[account] = false;
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tMarketing, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tMarketing);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tMarketing = calculateMarketingFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tMarketing);
return (tTransferAmount, tFee, tMarketing);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tMarketing, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rMarketing = tMarketing.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rMarketing);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeMarketing(uint256 tMarketing) private {
uint256 currentRate = _getRate();
uint256 rMarketing = tMarketing.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rMarketing);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tMarketing);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**2
);
}
function calculateMarketingFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_marketingFee).div(
10**2
);
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlacklisted[from] && !_isBlacklisted[to], "This address is blacklisted");
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + send lock?
// also, don't get caught in a circular sending event.
// also, don't swap & liquify if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (
overMinTokenBalance &&
!inSwapAndSend &&
from != uniswapV2Pair &&
SwapAndSendEnabled
) {
SwapAndSend(contractTokenBalance);
}
if(feesOnSellersAndBuyers) {
setFees(to);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
_tokenTransfer(from,to,amount,takeFee);
}
function setFees(address recipient) private {
_taxFee = defaultTaxFee;
_marketingFee = defaultMarketingFee;
if (recipient == uniswapV2Pair) { // sell
_marketingFee = _marketingFee4Sellers;
}
}
function SwapAndSend(uint256 contractTokenBalance) private lockTheSwap {
// 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), contractTokenBalance);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
contractTokenBalance,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
marketingWallet.transfer(contractETHBalance);
}
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function setDefaultMarketingFee(uint256 marketingFee) external onlyOwner() {
defaultMarketingFee = marketingFee;
}
function SetFeeOnSells(uint256 marketingFee4Sellers) external onlyOwner() {
_marketingFee4Sellers = marketingFee4Sellers;
}
function setFeesOnSellersAndBuyers(bool _enabled) public onlyOwner() {
feesOnSellersAndBuyers = _enabled;
}
function setSwapAndSendEnabled(bool _enabled) public onlyOwner() {
SwapAndSendEnabled = _enabled;
emit SwapAndSendEnabledUpdated(_enabled);
}
function setnumTokensToExchangeForMarketing(uint256 _numTokensToExchangeForMarketing) public onlyOwner() {
numTokensToExchangeForMarketing = _numTokensToExchangeForMarketing;
}
function _setMarketingWallet(address payable wallet) external onlyOwner() {
marketingWallet = wallet;
}
function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
_maxTxAmount = maxTxAmount;
}
} | //to recieve ETH | LineComment | v0.8.7+commit.e28d00a7 | None | ipfs://7a6b8d4f8b718a58ae7b258c8b2fd62171a9f2f58f811b05f296b950e9378861 | {
"func_code_index": [
7077,
7111
]
} | 1,452 |
||||
MacTama | MacTama.sol | 0x3ef636244d141e50ddc2232d8b70ed68a9088f66 | Solidity | MacTama | contract MacTama is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
uint8 private _decimals = 9;
string private _name = "MacTama";
string private _symbol = "$MCTAMA";
uint256 private _tTotal = 1000 * 10**9 * 10**uint256(_decimals);
// % to holders
uint256 public defaultTaxFee = 0;
uint256 public _taxFee = defaultTaxFee;
uint256 private _previousTaxFee = _taxFee;
// % to swap & send to marketing wallet
uint256 public defaultMarketingFee = 10;
uint256 public _marketingFee = defaultMarketingFee;
uint256 private _previousMarketingFee = _marketingFee;
uint256 public _marketingFee4Sellers = 10;
bool public feesOnSellersAndBuyers = true;
uint256 public _maxTxAmount = _tTotal.div(1).div(66);
uint256 public numTokensToExchangeForMarketing = _tTotal.div(100).div(100);
address payable public marketingWallet = payable(0xd9e18d0d73f33C384453d63D5A4dBEeeACc4829A);
//
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
mapping (address => bool) public _isBlacklisted;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tFeeTotal;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndSend;
bool public SwapAndSendEnabled = true;
event SwapAndSendEnabledUpdated(bool enabled);
modifier lockTheSwap {
inSwapAndSend = true;
_;
inSwapAndSend = false;
}
constructor () {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function excludeFromFee(address account) public onlyOwner() {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner() {
_isExcludedFromFee[account] = false;
}
function removeAllFee() private {
if(_taxFee == 0 && _marketingFee == 0) return;
_previousTaxFee = _taxFee;
_previousMarketingFee = _marketingFee;
_taxFee = 0;
_marketingFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_marketingFee = _previousMarketingFee;
}
//to recieve ETH
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function addToBlackList(address[] calldata addresses) external onlyOwner {
for (uint256 i; i < addresses.length; ++i) {
_isBlacklisted[addresses[i]] = true;
}
}
function removeFromBlackList(address account) external onlyOwner {
_isBlacklisted[account] = false;
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tMarketing, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tMarketing);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tMarketing = calculateMarketingFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tMarketing);
return (tTransferAmount, tFee, tMarketing);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tMarketing, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rMarketing = tMarketing.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rMarketing);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeMarketing(uint256 tMarketing) private {
uint256 currentRate = _getRate();
uint256 rMarketing = tMarketing.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rMarketing);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tMarketing);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**2
);
}
function calculateMarketingFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_marketingFee).div(
10**2
);
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlacklisted[from] && !_isBlacklisted[to], "This address is blacklisted");
if(from != owner() && to != owner())
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + send lock?
// also, don't get caught in a circular sending event.
// also, don't swap & liquify if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= numTokensToExchangeForMarketing;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (
overMinTokenBalance &&
!inSwapAndSend &&
from != uniswapV2Pair &&
SwapAndSendEnabled
) {
SwapAndSend(contractTokenBalance);
}
if(feesOnSellersAndBuyers) {
setFees(to);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
_tokenTransfer(from,to,amount,takeFee);
}
function setFees(address recipient) private {
_taxFee = defaultTaxFee;
_marketingFee = defaultMarketingFee;
if (recipient == uniswapV2Pair) { // sell
_marketingFee = _marketingFee4Sellers;
}
}
function SwapAndSend(uint256 contractTokenBalance) private lockTheSwap {
// 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), contractTokenBalance);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
contractTokenBalance,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
uint256 contractETHBalance = address(this).balance;
if(contractETHBalance > 0) {
marketingWallet.transfer(contractETHBalance);
}
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tMarketing) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function setDefaultMarketingFee(uint256 marketingFee) external onlyOwner() {
defaultMarketingFee = marketingFee;
}
function SetFeeOnSells(uint256 marketingFee4Sellers) external onlyOwner() {
_marketingFee4Sellers = marketingFee4Sellers;
}
function setFeesOnSellersAndBuyers(bool _enabled) public onlyOwner() {
feesOnSellersAndBuyers = _enabled;
}
function setSwapAndSendEnabled(bool _enabled) public onlyOwner() {
SwapAndSendEnabled = _enabled;
emit SwapAndSendEnabledUpdated(_enabled);
}
function setnumTokensToExchangeForMarketing(uint256 _numTokensToExchangeForMarketing) public onlyOwner() {
numTokensToExchangeForMarketing = _numTokensToExchangeForMarketing;
}
function _setMarketingWallet(address payable wallet) external onlyOwner() {
marketingWallet = wallet;
}
function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
_maxTxAmount = maxTxAmount;
}
} | _tokenTransfer | function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
| //this method is responsible for taking all fee, if takeFee is true | LineComment | v0.8.7+commit.e28d00a7 | None | ipfs://7a6b8d4f8b718a58ae7b258c8b2fd62171a9f2f58f811b05f296b950e9378861 | {
"func_code_index": [
13619,
14442
]
} | 1,453 |
||
YUANETHYFIPool | contracts/IRewardDistributionRecipient.sol | 0xe4f6a6d903c62ca9dfc93eba311cc8d01ada8499 | Solidity | YUANETHYFIPool | contract YUANETHYFIPool is LPTokenWrapper, IRewardDistributionRecipient {
IERC20 public yuan = IERC20(0x30bb8D13047204CA2AB8f94D4c96e9Dab85bAc28);
uint256 public constant DURATION = 12 days;
uint256 public starttime = 1604462400; // 2020/11/4 12:0:0 (UTC+8)
uint256 public periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
modifier checkStart() {
require(block.timestamp >= starttime, "not start");
_;
}
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
function lastTimeRewardApplicable() public view returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view returns (uint256) {
if (totalSupply() == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(totalSupply())
);
}
function earned(address account) public view returns (uint256) {
return
balanceOf(account)
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
// stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount) public updateReward(msg.sender) checkStart {
require(amount > 0, "Cannot stake 0");
super.stake(amount);
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount)
public
updateReward(msg.sender)
checkStart
{
require(amount > 0, "Cannot withdraw 0");
super.withdraw(amount);
emit Withdrawn(msg.sender, amount);
}
function exit() external {
withdraw(balanceOf(msg.sender));
getReward();
}
function getReward() public updateReward(msg.sender) checkStart {
uint256 reward = rewards[msg.sender];
if (reward > 0) {
rewards[msg.sender] = 0;
uint256 scalingFactor = YUAN(address(yuan)).yuansScalingFactor();
uint256 trueReward = reward.mul(scalingFactor).div(10**18);
yuan.safeTransfer(msg.sender, trueReward);
emit RewardPaid(msg.sender, reward);
}
}
function notifyRewardAmount(uint256 reward)
external
onlyRewardDistribution
updateReward(address(0))
{
// https://sips.synthetix.io/sips/sip-77
// increased buffer for scaling factor ( supports up to 10**4 * 10**18 scaling factor)
require(reward < uint256(-1) / 10**22, "rewards too large, would lock");
if (block.timestamp > starttime) {
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(DURATION);
} else {
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(DURATION);
}
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(DURATION);
emit RewardAdded(reward);
} else {
rewardRate = reward.div(DURATION);
lastUpdateTime = starttime;
periodFinish = starttime.add(DURATION);
emit RewardAdded(reward);
}
}
} | stake | function stake(uint256 amount) public updateReward(msg.sender) checkStart {
require(amount > 0, "Cannot stake 0");
super.stake(amount);
emit Staked(msg.sender, amount);
}
| // stake visibility is public as overriding LPTokenWrapper's stake() function | LineComment | v0.5.15+commit.6a57276f | GNU LGPLv3 | bzzr://c01228eceaa980caf71ff8af6c6110dd8dffbfe5846555adf8959ac9cf317044 | {
"func_code_index": [
2135,
2342
]
} | 1,454 |
||
xChainFed | xChainFed.sol | 0x4d7928e993125a9cefe7ffa9ab637653654222e2 | Solidity | ERC20 | interface ERC20 {
function approve(address,uint) external returns (bool);
function balanceOf(address) external view returns (uint);
function mint(address,uint) external; // only on src chain
function burn(uint) external; // only on src chain
function Swapout(uint,address) external returns (bool);
function transfer(address,uint) external returns (bool);
} | burn | function burn(uint) external; // only on src chain
| // only on src chain | LineComment | v0.8.9+commit.e5eed63a | None | ipfs://412a7795c50caf1b1195fe78c3837747106f3f7f32721466446da081ef429491 | {
"func_code_index": [
207,
262
]
} | 1,455 |
||
xChainFed | xChainFed.sol | 0x4d7928e993125a9cefe7ffa9ab637653654222e2 | Solidity | ERC20 | interface ERC20 {
function approve(address,uint) external returns (bool);
function balanceOf(address) external view returns (uint);
function mint(address,uint) external; // only on src chain
function burn(uint) external; // only on src chain
function Swapout(uint,address) external returns (bool);
function transfer(address,uint) external returns (bool);
} | Swapout | function Swapout(uint,address) external returns (bool);
| // only on src chain | LineComment | v0.8.9+commit.e5eed63a | None | ipfs://412a7795c50caf1b1195fe78c3837747106f3f7f32721466446da081ef429491 | {
"func_code_index": [
263,
323
]
} | 1,456 |
||
ALCXRewarder | contracts/MasterChefV2.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | IMigratorChef | interface IMigratorChef {
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
function migrate(IERC20 token) external returns (IERC20);
} | migrate | function migrate(IERC20 token) external returns (IERC20);
| // Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token. | LineComment | v0.6.12+commit.27d51765 | {
"func_code_index": [
164,
222
]
} | 1,457 |
||||
ALCXRewarder | contracts/MasterChefV2.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChefV2 | contract MasterChefV2 is BoringOwnable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
using SignedSafeMath for int256;
/// @notice Info of each MCV2 user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of SUSHI entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each MCV2 pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of SUSHI to distribute per block.
struct PoolInfo {
uint128 accSushiPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
/// @notice Address of MCV1 contract.
IMasterChef public immutable MASTER_CHEF;
/// @notice Address of SUSHI contract.
IERC20 public immutable SUSHI;
/// @notice The index of MCV2 master pool in MCV1.
uint256 public immutable MASTER_PID;
// @notice The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
/// @notice Info of each MCV2 pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each MCV2 pool.
IERC20[] public lpToken;
/// @notice Address of each `IRewarder` contract in MCV2.
IRewarder[] public rewarder;
/// @notice Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20;
uint256 private constant ACC_SUSHI_PRECISION = 1e12;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder);
event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare);
event LogInit();
/// @param _MASTER_CHEF The SushiSwap MCV1 contract address.
/// @param _sushi The SUSHI token contract address.
/// @param _MASTER_PID The pool ID of the dummy token on the base MCV1 contract.
constructor(
IMasterChef _MASTER_CHEF,
IERC20 _sushi,
uint256 _MASTER_PID
) public {
MASTER_CHEF = _MASTER_CHEF;
SUSHI = _sushi;
MASTER_PID = _MASTER_PID;
}
/// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUSHI.
/// Any balance of transaction sender in `dummyToken` is transferred.
/// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives.
/// @param dummyToken The address of the ERC-20 token to deposit into MCV1.
function init(IERC20 dummyToken) external {
uint256 balance = dummyToken.balanceOf(msg.sender);
require(balance != 0, "MasterChefV2: Balance must exceed 0");
dummyToken.safeTransferFrom(msg.sender, address(this), balance);
dummyToken.approve(address(MASTER_CHEF), balance);
MASTER_CHEF.deposit(MASTER_PID, balance);
emit LogInit();
}
/// @notice Returns the number of MCV2 pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _lpToken Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate.
function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })
);
emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder);
}
/// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
}
/// @notice Set the `migrator` contract. Can only be called by the owner.
/// @param _migrator The contract address to set.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
/// @notice Migrate LP token to another LP contract through the `migrator` contract.
/// @param _pid The index of the pool. See `poolInfo`.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "MasterChefV2: no migrator set");
IERC20 _lpToken = lpToken[_pid];
uint256 bal = _lpToken.balanceOf(address(this));
_lpToken.approve(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(_lpToken);
require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match");
lpToken[_pid] = newLpToken;
}
/// @notice View function to see pending SUSHI on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending SUSHI reward for a given user.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply);
}
pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256();
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Calculates and returns the `amount` of SUSHI per block.
function sushiPerBlock() public view returns (uint256 amount) {
amount =
uint256(MASTERCHEF_SUSHI_PER_BLOCK).mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) /
MASTER_CHEF.totalAllocPoint();
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
pool.accSushiPerShare = pool.accSushiPerShare.add(
(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare);
}
}
/// @notice Deposit LP tokens to MCV2 for SUSHI allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of SUSHI rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi;
// Interactions
if (_pendingSushi != 0) {
SUSHI.safeTransfer(to, _pendingSushi);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and SUSHI rewards.
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
SUSHI.safeTransfer(to, _pendingSushi);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Harvests SUSHI from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract.
function harvestFromMasterChef() public {
MASTER_CHEF.deposit(MASTER_PID, 0);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
lpToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
} | /// @notice The (older) MasterChef contract gives out a constant number of SUSHI tokens per block.
/// It is the only address with minting rights for SUSHI.
/// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token
/// that is deposited into the MasterChef V1 (MCV1) contract.
/// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives. | NatSpecSingleLine | init | function init(IERC20 dummyToken) external {
uint256 balance = dummyToken.balanceOf(msg.sender);
require(balance != 0, "MasterChefV2: Balance must exceed 0");
dummyToken.safeTransferFrom(msg.sender, address(this), balance);
dummyToken.approve(address(MASTER_CHEF), balance);
MASTER_CHEF.deposit(MASTER_PID, balance);
emit LogInit();
}
| /// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUSHI.
/// Any balance of transaction sender in `dummyToken` is transferred.
/// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives.
/// @param dummyToken The address of the ERC-20 token to deposit into MCV1. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
3122,
3469
]
} | 1,458 |
||
ALCXRewarder | contracts/MasterChefV2.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChefV2 | contract MasterChefV2 is BoringOwnable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
using SignedSafeMath for int256;
/// @notice Info of each MCV2 user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of SUSHI entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each MCV2 pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of SUSHI to distribute per block.
struct PoolInfo {
uint128 accSushiPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
/// @notice Address of MCV1 contract.
IMasterChef public immutable MASTER_CHEF;
/// @notice Address of SUSHI contract.
IERC20 public immutable SUSHI;
/// @notice The index of MCV2 master pool in MCV1.
uint256 public immutable MASTER_PID;
// @notice The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
/// @notice Info of each MCV2 pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each MCV2 pool.
IERC20[] public lpToken;
/// @notice Address of each `IRewarder` contract in MCV2.
IRewarder[] public rewarder;
/// @notice Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20;
uint256 private constant ACC_SUSHI_PRECISION = 1e12;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder);
event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare);
event LogInit();
/// @param _MASTER_CHEF The SushiSwap MCV1 contract address.
/// @param _sushi The SUSHI token contract address.
/// @param _MASTER_PID The pool ID of the dummy token on the base MCV1 contract.
constructor(
IMasterChef _MASTER_CHEF,
IERC20 _sushi,
uint256 _MASTER_PID
) public {
MASTER_CHEF = _MASTER_CHEF;
SUSHI = _sushi;
MASTER_PID = _MASTER_PID;
}
/// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUSHI.
/// Any balance of transaction sender in `dummyToken` is transferred.
/// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives.
/// @param dummyToken The address of the ERC-20 token to deposit into MCV1.
function init(IERC20 dummyToken) external {
uint256 balance = dummyToken.balanceOf(msg.sender);
require(balance != 0, "MasterChefV2: Balance must exceed 0");
dummyToken.safeTransferFrom(msg.sender, address(this), balance);
dummyToken.approve(address(MASTER_CHEF), balance);
MASTER_CHEF.deposit(MASTER_PID, balance);
emit LogInit();
}
/// @notice Returns the number of MCV2 pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _lpToken Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate.
function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })
);
emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder);
}
/// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
}
/// @notice Set the `migrator` contract. Can only be called by the owner.
/// @param _migrator The contract address to set.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
/// @notice Migrate LP token to another LP contract through the `migrator` contract.
/// @param _pid The index of the pool. See `poolInfo`.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "MasterChefV2: no migrator set");
IERC20 _lpToken = lpToken[_pid];
uint256 bal = _lpToken.balanceOf(address(this));
_lpToken.approve(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(_lpToken);
require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match");
lpToken[_pid] = newLpToken;
}
/// @notice View function to see pending SUSHI on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending SUSHI reward for a given user.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply);
}
pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256();
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Calculates and returns the `amount` of SUSHI per block.
function sushiPerBlock() public view returns (uint256 amount) {
amount =
uint256(MASTERCHEF_SUSHI_PER_BLOCK).mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) /
MASTER_CHEF.totalAllocPoint();
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
pool.accSushiPerShare = pool.accSushiPerShare.add(
(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare);
}
}
/// @notice Deposit LP tokens to MCV2 for SUSHI allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of SUSHI rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi;
// Interactions
if (_pendingSushi != 0) {
SUSHI.safeTransfer(to, _pendingSushi);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and SUSHI rewards.
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
SUSHI.safeTransfer(to, _pendingSushi);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Harvests SUSHI from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract.
function harvestFromMasterChef() public {
MASTER_CHEF.deposit(MASTER_PID, 0);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
lpToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
} | /// @notice The (older) MasterChef contract gives out a constant number of SUSHI tokens per block.
/// It is the only address with minting rights for SUSHI.
/// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token
/// that is deposited into the MasterChef V1 (MCV1) contract.
/// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives. | NatSpecSingleLine | poolLength | function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
| /// @notice Returns the number of MCV2 pools. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
3518,
3608
]
} | 1,459 |
||
ALCXRewarder | contracts/MasterChefV2.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChefV2 | contract MasterChefV2 is BoringOwnable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
using SignedSafeMath for int256;
/// @notice Info of each MCV2 user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of SUSHI entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each MCV2 pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of SUSHI to distribute per block.
struct PoolInfo {
uint128 accSushiPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
/// @notice Address of MCV1 contract.
IMasterChef public immutable MASTER_CHEF;
/// @notice Address of SUSHI contract.
IERC20 public immutable SUSHI;
/// @notice The index of MCV2 master pool in MCV1.
uint256 public immutable MASTER_PID;
// @notice The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
/// @notice Info of each MCV2 pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each MCV2 pool.
IERC20[] public lpToken;
/// @notice Address of each `IRewarder` contract in MCV2.
IRewarder[] public rewarder;
/// @notice Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20;
uint256 private constant ACC_SUSHI_PRECISION = 1e12;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder);
event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare);
event LogInit();
/// @param _MASTER_CHEF The SushiSwap MCV1 contract address.
/// @param _sushi The SUSHI token contract address.
/// @param _MASTER_PID The pool ID of the dummy token on the base MCV1 contract.
constructor(
IMasterChef _MASTER_CHEF,
IERC20 _sushi,
uint256 _MASTER_PID
) public {
MASTER_CHEF = _MASTER_CHEF;
SUSHI = _sushi;
MASTER_PID = _MASTER_PID;
}
/// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUSHI.
/// Any balance of transaction sender in `dummyToken` is transferred.
/// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives.
/// @param dummyToken The address of the ERC-20 token to deposit into MCV1.
function init(IERC20 dummyToken) external {
uint256 balance = dummyToken.balanceOf(msg.sender);
require(balance != 0, "MasterChefV2: Balance must exceed 0");
dummyToken.safeTransferFrom(msg.sender, address(this), balance);
dummyToken.approve(address(MASTER_CHEF), balance);
MASTER_CHEF.deposit(MASTER_PID, balance);
emit LogInit();
}
/// @notice Returns the number of MCV2 pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _lpToken Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate.
function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })
);
emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder);
}
/// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
}
/// @notice Set the `migrator` contract. Can only be called by the owner.
/// @param _migrator The contract address to set.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
/// @notice Migrate LP token to another LP contract through the `migrator` contract.
/// @param _pid The index of the pool. See `poolInfo`.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "MasterChefV2: no migrator set");
IERC20 _lpToken = lpToken[_pid];
uint256 bal = _lpToken.balanceOf(address(this));
_lpToken.approve(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(_lpToken);
require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match");
lpToken[_pid] = newLpToken;
}
/// @notice View function to see pending SUSHI on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending SUSHI reward for a given user.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply);
}
pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256();
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Calculates and returns the `amount` of SUSHI per block.
function sushiPerBlock() public view returns (uint256 amount) {
amount =
uint256(MASTERCHEF_SUSHI_PER_BLOCK).mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) /
MASTER_CHEF.totalAllocPoint();
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
pool.accSushiPerShare = pool.accSushiPerShare.add(
(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare);
}
}
/// @notice Deposit LP tokens to MCV2 for SUSHI allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of SUSHI rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi;
// Interactions
if (_pendingSushi != 0) {
SUSHI.safeTransfer(to, _pendingSushi);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and SUSHI rewards.
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
SUSHI.safeTransfer(to, _pendingSushi);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Harvests SUSHI from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract.
function harvestFromMasterChef() public {
MASTER_CHEF.deposit(MASTER_PID, 0);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
lpToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
} | /// @notice The (older) MasterChef contract gives out a constant number of SUSHI tokens per block.
/// It is the only address with minting rights for SUSHI.
/// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token
/// that is deposited into the MasterChef V1 (MCV1) contract.
/// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives. | NatSpecSingleLine | add | function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })
);
emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder);
}
| /// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _lpToken Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
3921,
4384
]
} | 1,460 |
||
ALCXRewarder | contracts/MasterChefV2.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChefV2 | contract MasterChefV2 is BoringOwnable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
using SignedSafeMath for int256;
/// @notice Info of each MCV2 user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of SUSHI entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each MCV2 pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of SUSHI to distribute per block.
struct PoolInfo {
uint128 accSushiPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
/// @notice Address of MCV1 contract.
IMasterChef public immutable MASTER_CHEF;
/// @notice Address of SUSHI contract.
IERC20 public immutable SUSHI;
/// @notice The index of MCV2 master pool in MCV1.
uint256 public immutable MASTER_PID;
// @notice The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
/// @notice Info of each MCV2 pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each MCV2 pool.
IERC20[] public lpToken;
/// @notice Address of each `IRewarder` contract in MCV2.
IRewarder[] public rewarder;
/// @notice Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20;
uint256 private constant ACC_SUSHI_PRECISION = 1e12;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder);
event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare);
event LogInit();
/// @param _MASTER_CHEF The SushiSwap MCV1 contract address.
/// @param _sushi The SUSHI token contract address.
/// @param _MASTER_PID The pool ID of the dummy token on the base MCV1 contract.
constructor(
IMasterChef _MASTER_CHEF,
IERC20 _sushi,
uint256 _MASTER_PID
) public {
MASTER_CHEF = _MASTER_CHEF;
SUSHI = _sushi;
MASTER_PID = _MASTER_PID;
}
/// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUSHI.
/// Any balance of transaction sender in `dummyToken` is transferred.
/// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives.
/// @param dummyToken The address of the ERC-20 token to deposit into MCV1.
function init(IERC20 dummyToken) external {
uint256 balance = dummyToken.balanceOf(msg.sender);
require(balance != 0, "MasterChefV2: Balance must exceed 0");
dummyToken.safeTransferFrom(msg.sender, address(this), balance);
dummyToken.approve(address(MASTER_CHEF), balance);
MASTER_CHEF.deposit(MASTER_PID, balance);
emit LogInit();
}
/// @notice Returns the number of MCV2 pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _lpToken Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate.
function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })
);
emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder);
}
/// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
}
/// @notice Set the `migrator` contract. Can only be called by the owner.
/// @param _migrator The contract address to set.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
/// @notice Migrate LP token to another LP contract through the `migrator` contract.
/// @param _pid The index of the pool. See `poolInfo`.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "MasterChefV2: no migrator set");
IERC20 _lpToken = lpToken[_pid];
uint256 bal = _lpToken.balanceOf(address(this));
_lpToken.approve(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(_lpToken);
require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match");
lpToken[_pid] = newLpToken;
}
/// @notice View function to see pending SUSHI on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending SUSHI reward for a given user.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply);
}
pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256();
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Calculates and returns the `amount` of SUSHI per block.
function sushiPerBlock() public view returns (uint256 amount) {
amount =
uint256(MASTERCHEF_SUSHI_PER_BLOCK).mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) /
MASTER_CHEF.totalAllocPoint();
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
pool.accSushiPerShare = pool.accSushiPerShare.add(
(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare);
}
}
/// @notice Deposit LP tokens to MCV2 for SUSHI allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of SUSHI rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi;
// Interactions
if (_pendingSushi != 0) {
SUSHI.safeTransfer(to, _pendingSushi);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and SUSHI rewards.
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
SUSHI.safeTransfer(to, _pendingSushi);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Harvests SUSHI from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract.
function harvestFromMasterChef() public {
MASTER_CHEF.deposit(MASTER_PID, 0);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
lpToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
} | /// @notice The (older) MasterChef contract gives out a constant number of SUSHI tokens per block.
/// It is the only address with minting rights for SUSHI.
/// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token
/// that is deposited into the MasterChef V1 (MCV1) contract.
/// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives. | NatSpecSingleLine | set | function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
}
| /// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
4752,
5148
]
} | 1,461 |
||
ALCXRewarder | contracts/MasterChefV2.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChefV2 | contract MasterChefV2 is BoringOwnable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
using SignedSafeMath for int256;
/// @notice Info of each MCV2 user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of SUSHI entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each MCV2 pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of SUSHI to distribute per block.
struct PoolInfo {
uint128 accSushiPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
/// @notice Address of MCV1 contract.
IMasterChef public immutable MASTER_CHEF;
/// @notice Address of SUSHI contract.
IERC20 public immutable SUSHI;
/// @notice The index of MCV2 master pool in MCV1.
uint256 public immutable MASTER_PID;
// @notice The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
/// @notice Info of each MCV2 pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each MCV2 pool.
IERC20[] public lpToken;
/// @notice Address of each `IRewarder` contract in MCV2.
IRewarder[] public rewarder;
/// @notice Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20;
uint256 private constant ACC_SUSHI_PRECISION = 1e12;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder);
event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare);
event LogInit();
/// @param _MASTER_CHEF The SushiSwap MCV1 contract address.
/// @param _sushi The SUSHI token contract address.
/// @param _MASTER_PID The pool ID of the dummy token on the base MCV1 contract.
constructor(
IMasterChef _MASTER_CHEF,
IERC20 _sushi,
uint256 _MASTER_PID
) public {
MASTER_CHEF = _MASTER_CHEF;
SUSHI = _sushi;
MASTER_PID = _MASTER_PID;
}
/// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUSHI.
/// Any balance of transaction sender in `dummyToken` is transferred.
/// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives.
/// @param dummyToken The address of the ERC-20 token to deposit into MCV1.
function init(IERC20 dummyToken) external {
uint256 balance = dummyToken.balanceOf(msg.sender);
require(balance != 0, "MasterChefV2: Balance must exceed 0");
dummyToken.safeTransferFrom(msg.sender, address(this), balance);
dummyToken.approve(address(MASTER_CHEF), balance);
MASTER_CHEF.deposit(MASTER_PID, balance);
emit LogInit();
}
/// @notice Returns the number of MCV2 pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _lpToken Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate.
function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })
);
emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder);
}
/// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
}
/// @notice Set the `migrator` contract. Can only be called by the owner.
/// @param _migrator The contract address to set.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
/// @notice Migrate LP token to another LP contract through the `migrator` contract.
/// @param _pid The index of the pool. See `poolInfo`.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "MasterChefV2: no migrator set");
IERC20 _lpToken = lpToken[_pid];
uint256 bal = _lpToken.balanceOf(address(this));
_lpToken.approve(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(_lpToken);
require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match");
lpToken[_pid] = newLpToken;
}
/// @notice View function to see pending SUSHI on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending SUSHI reward for a given user.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply);
}
pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256();
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Calculates and returns the `amount` of SUSHI per block.
function sushiPerBlock() public view returns (uint256 amount) {
amount =
uint256(MASTERCHEF_SUSHI_PER_BLOCK).mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) /
MASTER_CHEF.totalAllocPoint();
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
pool.accSushiPerShare = pool.accSushiPerShare.add(
(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare);
}
}
/// @notice Deposit LP tokens to MCV2 for SUSHI allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of SUSHI rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi;
// Interactions
if (_pendingSushi != 0) {
SUSHI.safeTransfer(to, _pendingSushi);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and SUSHI rewards.
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
SUSHI.safeTransfer(to, _pendingSushi);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Harvests SUSHI from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract.
function harvestFromMasterChef() public {
MASTER_CHEF.deposit(MASTER_PID, 0);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
lpToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
} | /// @notice The (older) MasterChef contract gives out a constant number of SUSHI tokens per block.
/// It is the only address with minting rights for SUSHI.
/// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token
/// that is deposited into the MasterChef V1 (MCV1) contract.
/// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives. | NatSpecSingleLine | setMigrator | function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
| /// @notice Set the `migrator` contract. Can only be called by the owner.
/// @param _migrator The contract address to set. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
5276,
5368
]
} | 1,462 |
||
ALCXRewarder | contracts/MasterChefV2.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChefV2 | contract MasterChefV2 is BoringOwnable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
using SignedSafeMath for int256;
/// @notice Info of each MCV2 user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of SUSHI entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each MCV2 pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of SUSHI to distribute per block.
struct PoolInfo {
uint128 accSushiPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
/// @notice Address of MCV1 contract.
IMasterChef public immutable MASTER_CHEF;
/// @notice Address of SUSHI contract.
IERC20 public immutable SUSHI;
/// @notice The index of MCV2 master pool in MCV1.
uint256 public immutable MASTER_PID;
// @notice The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
/// @notice Info of each MCV2 pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each MCV2 pool.
IERC20[] public lpToken;
/// @notice Address of each `IRewarder` contract in MCV2.
IRewarder[] public rewarder;
/// @notice Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20;
uint256 private constant ACC_SUSHI_PRECISION = 1e12;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder);
event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare);
event LogInit();
/// @param _MASTER_CHEF The SushiSwap MCV1 contract address.
/// @param _sushi The SUSHI token contract address.
/// @param _MASTER_PID The pool ID of the dummy token on the base MCV1 contract.
constructor(
IMasterChef _MASTER_CHEF,
IERC20 _sushi,
uint256 _MASTER_PID
) public {
MASTER_CHEF = _MASTER_CHEF;
SUSHI = _sushi;
MASTER_PID = _MASTER_PID;
}
/// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUSHI.
/// Any balance of transaction sender in `dummyToken` is transferred.
/// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives.
/// @param dummyToken The address of the ERC-20 token to deposit into MCV1.
function init(IERC20 dummyToken) external {
uint256 balance = dummyToken.balanceOf(msg.sender);
require(balance != 0, "MasterChefV2: Balance must exceed 0");
dummyToken.safeTransferFrom(msg.sender, address(this), balance);
dummyToken.approve(address(MASTER_CHEF), balance);
MASTER_CHEF.deposit(MASTER_PID, balance);
emit LogInit();
}
/// @notice Returns the number of MCV2 pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _lpToken Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate.
function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })
);
emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder);
}
/// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
}
/// @notice Set the `migrator` contract. Can only be called by the owner.
/// @param _migrator The contract address to set.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
/// @notice Migrate LP token to another LP contract through the `migrator` contract.
/// @param _pid The index of the pool. See `poolInfo`.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "MasterChefV2: no migrator set");
IERC20 _lpToken = lpToken[_pid];
uint256 bal = _lpToken.balanceOf(address(this));
_lpToken.approve(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(_lpToken);
require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match");
lpToken[_pid] = newLpToken;
}
/// @notice View function to see pending SUSHI on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending SUSHI reward for a given user.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply);
}
pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256();
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Calculates and returns the `amount` of SUSHI per block.
function sushiPerBlock() public view returns (uint256 amount) {
amount =
uint256(MASTERCHEF_SUSHI_PER_BLOCK).mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) /
MASTER_CHEF.totalAllocPoint();
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
pool.accSushiPerShare = pool.accSushiPerShare.add(
(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare);
}
}
/// @notice Deposit LP tokens to MCV2 for SUSHI allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of SUSHI rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi;
// Interactions
if (_pendingSushi != 0) {
SUSHI.safeTransfer(to, _pendingSushi);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and SUSHI rewards.
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
SUSHI.safeTransfer(to, _pendingSushi);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Harvests SUSHI from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract.
function harvestFromMasterChef() public {
MASTER_CHEF.deposit(MASTER_PID, 0);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
lpToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
} | /// @notice The (older) MasterChef contract gives out a constant number of SUSHI tokens per block.
/// It is the only address with minting rights for SUSHI.
/// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token
/// that is deposited into the MasterChef V1 (MCV1) contract.
/// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives. | NatSpecSingleLine | migrate | function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "MasterChefV2: no migrator set");
IERC20 _lpToken = lpToken[_pid];
uint256 bal = _lpToken.balanceOf(address(this));
_lpToken.approve(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(_lpToken);
require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match");
lpToken[_pid] = newLpToken;
}
| /// @notice Migrate LP token to another LP contract through the `migrator` contract.
/// @param _pid The index of the pool. See `poolInfo`. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
5512,
5942
]
} | 1,463 |
||
ALCXRewarder | contracts/MasterChefV2.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChefV2 | contract MasterChefV2 is BoringOwnable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
using SignedSafeMath for int256;
/// @notice Info of each MCV2 user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of SUSHI entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each MCV2 pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of SUSHI to distribute per block.
struct PoolInfo {
uint128 accSushiPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
/// @notice Address of MCV1 contract.
IMasterChef public immutable MASTER_CHEF;
/// @notice Address of SUSHI contract.
IERC20 public immutable SUSHI;
/// @notice The index of MCV2 master pool in MCV1.
uint256 public immutable MASTER_PID;
// @notice The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
/// @notice Info of each MCV2 pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each MCV2 pool.
IERC20[] public lpToken;
/// @notice Address of each `IRewarder` contract in MCV2.
IRewarder[] public rewarder;
/// @notice Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20;
uint256 private constant ACC_SUSHI_PRECISION = 1e12;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder);
event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare);
event LogInit();
/// @param _MASTER_CHEF The SushiSwap MCV1 contract address.
/// @param _sushi The SUSHI token contract address.
/// @param _MASTER_PID The pool ID of the dummy token on the base MCV1 contract.
constructor(
IMasterChef _MASTER_CHEF,
IERC20 _sushi,
uint256 _MASTER_PID
) public {
MASTER_CHEF = _MASTER_CHEF;
SUSHI = _sushi;
MASTER_PID = _MASTER_PID;
}
/// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUSHI.
/// Any balance of transaction sender in `dummyToken` is transferred.
/// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives.
/// @param dummyToken The address of the ERC-20 token to deposit into MCV1.
function init(IERC20 dummyToken) external {
uint256 balance = dummyToken.balanceOf(msg.sender);
require(balance != 0, "MasterChefV2: Balance must exceed 0");
dummyToken.safeTransferFrom(msg.sender, address(this), balance);
dummyToken.approve(address(MASTER_CHEF), balance);
MASTER_CHEF.deposit(MASTER_PID, balance);
emit LogInit();
}
/// @notice Returns the number of MCV2 pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _lpToken Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate.
function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })
);
emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder);
}
/// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
}
/// @notice Set the `migrator` contract. Can only be called by the owner.
/// @param _migrator The contract address to set.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
/// @notice Migrate LP token to another LP contract through the `migrator` contract.
/// @param _pid The index of the pool. See `poolInfo`.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "MasterChefV2: no migrator set");
IERC20 _lpToken = lpToken[_pid];
uint256 bal = _lpToken.balanceOf(address(this));
_lpToken.approve(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(_lpToken);
require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match");
lpToken[_pid] = newLpToken;
}
/// @notice View function to see pending SUSHI on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending SUSHI reward for a given user.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply);
}
pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256();
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Calculates and returns the `amount` of SUSHI per block.
function sushiPerBlock() public view returns (uint256 amount) {
amount =
uint256(MASTERCHEF_SUSHI_PER_BLOCK).mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) /
MASTER_CHEF.totalAllocPoint();
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
pool.accSushiPerShare = pool.accSushiPerShare.add(
(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare);
}
}
/// @notice Deposit LP tokens to MCV2 for SUSHI allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of SUSHI rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi;
// Interactions
if (_pendingSushi != 0) {
SUSHI.safeTransfer(to, _pendingSushi);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and SUSHI rewards.
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
SUSHI.safeTransfer(to, _pendingSushi);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Harvests SUSHI from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract.
function harvestFromMasterChef() public {
MASTER_CHEF.deposit(MASTER_PID, 0);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
lpToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
} | /// @notice The (older) MasterChef contract gives out a constant number of SUSHI tokens per block.
/// It is the only address with minting rights for SUSHI.
/// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token
/// that is deposited into the MasterChef V1 (MCV1) contract.
/// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives. | NatSpecSingleLine | pendingSushi | function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply);
}
pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256();
}
| /// @notice View function to see pending SUSHI on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending SUSHI reward for a given user. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
6148,
6869
]
} | 1,464 |
||
ALCXRewarder | contracts/MasterChefV2.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChefV2 | contract MasterChefV2 is BoringOwnable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
using SignedSafeMath for int256;
/// @notice Info of each MCV2 user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of SUSHI entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each MCV2 pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of SUSHI to distribute per block.
struct PoolInfo {
uint128 accSushiPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
/// @notice Address of MCV1 contract.
IMasterChef public immutable MASTER_CHEF;
/// @notice Address of SUSHI contract.
IERC20 public immutable SUSHI;
/// @notice The index of MCV2 master pool in MCV1.
uint256 public immutable MASTER_PID;
// @notice The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
/// @notice Info of each MCV2 pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each MCV2 pool.
IERC20[] public lpToken;
/// @notice Address of each `IRewarder` contract in MCV2.
IRewarder[] public rewarder;
/// @notice Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20;
uint256 private constant ACC_SUSHI_PRECISION = 1e12;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder);
event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare);
event LogInit();
/// @param _MASTER_CHEF The SushiSwap MCV1 contract address.
/// @param _sushi The SUSHI token contract address.
/// @param _MASTER_PID The pool ID of the dummy token on the base MCV1 contract.
constructor(
IMasterChef _MASTER_CHEF,
IERC20 _sushi,
uint256 _MASTER_PID
) public {
MASTER_CHEF = _MASTER_CHEF;
SUSHI = _sushi;
MASTER_PID = _MASTER_PID;
}
/// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUSHI.
/// Any balance of transaction sender in `dummyToken` is transferred.
/// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives.
/// @param dummyToken The address of the ERC-20 token to deposit into MCV1.
function init(IERC20 dummyToken) external {
uint256 balance = dummyToken.balanceOf(msg.sender);
require(balance != 0, "MasterChefV2: Balance must exceed 0");
dummyToken.safeTransferFrom(msg.sender, address(this), balance);
dummyToken.approve(address(MASTER_CHEF), balance);
MASTER_CHEF.deposit(MASTER_PID, balance);
emit LogInit();
}
/// @notice Returns the number of MCV2 pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _lpToken Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate.
function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })
);
emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder);
}
/// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
}
/// @notice Set the `migrator` contract. Can only be called by the owner.
/// @param _migrator The contract address to set.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
/// @notice Migrate LP token to another LP contract through the `migrator` contract.
/// @param _pid The index of the pool. See `poolInfo`.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "MasterChefV2: no migrator set");
IERC20 _lpToken = lpToken[_pid];
uint256 bal = _lpToken.balanceOf(address(this));
_lpToken.approve(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(_lpToken);
require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match");
lpToken[_pid] = newLpToken;
}
/// @notice View function to see pending SUSHI on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending SUSHI reward for a given user.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply);
}
pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256();
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Calculates and returns the `amount` of SUSHI per block.
function sushiPerBlock() public view returns (uint256 amount) {
amount =
uint256(MASTERCHEF_SUSHI_PER_BLOCK).mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) /
MASTER_CHEF.totalAllocPoint();
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
pool.accSushiPerShare = pool.accSushiPerShare.add(
(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare);
}
}
/// @notice Deposit LP tokens to MCV2 for SUSHI allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of SUSHI rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi;
// Interactions
if (_pendingSushi != 0) {
SUSHI.safeTransfer(to, _pendingSushi);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and SUSHI rewards.
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
SUSHI.safeTransfer(to, _pendingSushi);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Harvests SUSHI from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract.
function harvestFromMasterChef() public {
MASTER_CHEF.deposit(MASTER_PID, 0);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
lpToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
} | /// @notice The (older) MasterChef contract gives out a constant number of SUSHI tokens per block.
/// It is the only address with minting rights for SUSHI.
/// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token
/// that is deposited into the MasterChef V1 (MCV1) contract.
/// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives. | NatSpecSingleLine | massUpdatePools | function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
| /// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
7037,
7196
]
} | 1,465 |
||
ALCXRewarder | contracts/MasterChefV2.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChefV2 | contract MasterChefV2 is BoringOwnable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
using SignedSafeMath for int256;
/// @notice Info of each MCV2 user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of SUSHI entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each MCV2 pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of SUSHI to distribute per block.
struct PoolInfo {
uint128 accSushiPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
/// @notice Address of MCV1 contract.
IMasterChef public immutable MASTER_CHEF;
/// @notice Address of SUSHI contract.
IERC20 public immutable SUSHI;
/// @notice The index of MCV2 master pool in MCV1.
uint256 public immutable MASTER_PID;
// @notice The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
/// @notice Info of each MCV2 pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each MCV2 pool.
IERC20[] public lpToken;
/// @notice Address of each `IRewarder` contract in MCV2.
IRewarder[] public rewarder;
/// @notice Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20;
uint256 private constant ACC_SUSHI_PRECISION = 1e12;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder);
event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare);
event LogInit();
/// @param _MASTER_CHEF The SushiSwap MCV1 contract address.
/// @param _sushi The SUSHI token contract address.
/// @param _MASTER_PID The pool ID of the dummy token on the base MCV1 contract.
constructor(
IMasterChef _MASTER_CHEF,
IERC20 _sushi,
uint256 _MASTER_PID
) public {
MASTER_CHEF = _MASTER_CHEF;
SUSHI = _sushi;
MASTER_PID = _MASTER_PID;
}
/// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUSHI.
/// Any balance of transaction sender in `dummyToken` is transferred.
/// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives.
/// @param dummyToken The address of the ERC-20 token to deposit into MCV1.
function init(IERC20 dummyToken) external {
uint256 balance = dummyToken.balanceOf(msg.sender);
require(balance != 0, "MasterChefV2: Balance must exceed 0");
dummyToken.safeTransferFrom(msg.sender, address(this), balance);
dummyToken.approve(address(MASTER_CHEF), balance);
MASTER_CHEF.deposit(MASTER_PID, balance);
emit LogInit();
}
/// @notice Returns the number of MCV2 pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _lpToken Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate.
function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })
);
emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder);
}
/// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
}
/// @notice Set the `migrator` contract. Can only be called by the owner.
/// @param _migrator The contract address to set.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
/// @notice Migrate LP token to another LP contract through the `migrator` contract.
/// @param _pid The index of the pool. See `poolInfo`.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "MasterChefV2: no migrator set");
IERC20 _lpToken = lpToken[_pid];
uint256 bal = _lpToken.balanceOf(address(this));
_lpToken.approve(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(_lpToken);
require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match");
lpToken[_pid] = newLpToken;
}
/// @notice View function to see pending SUSHI on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending SUSHI reward for a given user.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply);
}
pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256();
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Calculates and returns the `amount` of SUSHI per block.
function sushiPerBlock() public view returns (uint256 amount) {
amount =
uint256(MASTERCHEF_SUSHI_PER_BLOCK).mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) /
MASTER_CHEF.totalAllocPoint();
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
pool.accSushiPerShare = pool.accSushiPerShare.add(
(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare);
}
}
/// @notice Deposit LP tokens to MCV2 for SUSHI allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of SUSHI rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi;
// Interactions
if (_pendingSushi != 0) {
SUSHI.safeTransfer(to, _pendingSushi);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and SUSHI rewards.
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
SUSHI.safeTransfer(to, _pendingSushi);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Harvests SUSHI from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract.
function harvestFromMasterChef() public {
MASTER_CHEF.deposit(MASTER_PID, 0);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
lpToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
} | /// @notice The (older) MasterChef contract gives out a constant number of SUSHI tokens per block.
/// It is the only address with minting rights for SUSHI.
/// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token
/// that is deposited into the MasterChef V1 (MCV1) contract.
/// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives. | NatSpecSingleLine | sushiPerBlock | function sushiPerBlock() public view returns (uint256 amount) {
amount =
uint256(MASTERCHEF_SUSHI_PER_BLOCK).mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) /
MASTER_CHEF.totalAllocPoint();
}
| /// @notice Calculates and returns the `amount` of SUSHI per block. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
7267,
7469
]
} | 1,466 |
||
ALCXRewarder | contracts/MasterChefV2.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChefV2 | contract MasterChefV2 is BoringOwnable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
using SignedSafeMath for int256;
/// @notice Info of each MCV2 user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of SUSHI entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each MCV2 pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of SUSHI to distribute per block.
struct PoolInfo {
uint128 accSushiPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
/// @notice Address of MCV1 contract.
IMasterChef public immutable MASTER_CHEF;
/// @notice Address of SUSHI contract.
IERC20 public immutable SUSHI;
/// @notice The index of MCV2 master pool in MCV1.
uint256 public immutable MASTER_PID;
// @notice The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
/// @notice Info of each MCV2 pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each MCV2 pool.
IERC20[] public lpToken;
/// @notice Address of each `IRewarder` contract in MCV2.
IRewarder[] public rewarder;
/// @notice Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20;
uint256 private constant ACC_SUSHI_PRECISION = 1e12;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder);
event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare);
event LogInit();
/// @param _MASTER_CHEF The SushiSwap MCV1 contract address.
/// @param _sushi The SUSHI token contract address.
/// @param _MASTER_PID The pool ID of the dummy token on the base MCV1 contract.
constructor(
IMasterChef _MASTER_CHEF,
IERC20 _sushi,
uint256 _MASTER_PID
) public {
MASTER_CHEF = _MASTER_CHEF;
SUSHI = _sushi;
MASTER_PID = _MASTER_PID;
}
/// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUSHI.
/// Any balance of transaction sender in `dummyToken` is transferred.
/// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives.
/// @param dummyToken The address of the ERC-20 token to deposit into MCV1.
function init(IERC20 dummyToken) external {
uint256 balance = dummyToken.balanceOf(msg.sender);
require(balance != 0, "MasterChefV2: Balance must exceed 0");
dummyToken.safeTransferFrom(msg.sender, address(this), balance);
dummyToken.approve(address(MASTER_CHEF), balance);
MASTER_CHEF.deposit(MASTER_PID, balance);
emit LogInit();
}
/// @notice Returns the number of MCV2 pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _lpToken Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate.
function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })
);
emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder);
}
/// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
}
/// @notice Set the `migrator` contract. Can only be called by the owner.
/// @param _migrator The contract address to set.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
/// @notice Migrate LP token to another LP contract through the `migrator` contract.
/// @param _pid The index of the pool. See `poolInfo`.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "MasterChefV2: no migrator set");
IERC20 _lpToken = lpToken[_pid];
uint256 bal = _lpToken.balanceOf(address(this));
_lpToken.approve(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(_lpToken);
require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match");
lpToken[_pid] = newLpToken;
}
/// @notice View function to see pending SUSHI on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending SUSHI reward for a given user.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply);
}
pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256();
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Calculates and returns the `amount` of SUSHI per block.
function sushiPerBlock() public view returns (uint256 amount) {
amount =
uint256(MASTERCHEF_SUSHI_PER_BLOCK).mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) /
MASTER_CHEF.totalAllocPoint();
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
pool.accSushiPerShare = pool.accSushiPerShare.add(
(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare);
}
}
/// @notice Deposit LP tokens to MCV2 for SUSHI allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of SUSHI rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi;
// Interactions
if (_pendingSushi != 0) {
SUSHI.safeTransfer(to, _pendingSushi);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and SUSHI rewards.
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
SUSHI.safeTransfer(to, _pendingSushi);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Harvests SUSHI from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract.
function harvestFromMasterChef() public {
MASTER_CHEF.deposit(MASTER_PID, 0);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
lpToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
} | /// @notice The (older) MasterChef contract gives out a constant number of SUSHI tokens per block.
/// It is the only address with minting rights for SUSHI.
/// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token
/// that is deposited into the MasterChef V1 (MCV1) contract.
/// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives. | NatSpecSingleLine | updatePool | function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
pool.accSushiPerShare = pool.accSushiPerShare.add(
(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare);
}
}
| /// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
7635,
8308
]
} | 1,467 |
||
ALCXRewarder | contracts/MasterChefV2.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChefV2 | contract MasterChefV2 is BoringOwnable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
using SignedSafeMath for int256;
/// @notice Info of each MCV2 user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of SUSHI entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each MCV2 pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of SUSHI to distribute per block.
struct PoolInfo {
uint128 accSushiPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
/// @notice Address of MCV1 contract.
IMasterChef public immutable MASTER_CHEF;
/// @notice Address of SUSHI contract.
IERC20 public immutable SUSHI;
/// @notice The index of MCV2 master pool in MCV1.
uint256 public immutable MASTER_PID;
// @notice The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
/// @notice Info of each MCV2 pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each MCV2 pool.
IERC20[] public lpToken;
/// @notice Address of each `IRewarder` contract in MCV2.
IRewarder[] public rewarder;
/// @notice Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20;
uint256 private constant ACC_SUSHI_PRECISION = 1e12;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder);
event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare);
event LogInit();
/// @param _MASTER_CHEF The SushiSwap MCV1 contract address.
/// @param _sushi The SUSHI token contract address.
/// @param _MASTER_PID The pool ID of the dummy token on the base MCV1 contract.
constructor(
IMasterChef _MASTER_CHEF,
IERC20 _sushi,
uint256 _MASTER_PID
) public {
MASTER_CHEF = _MASTER_CHEF;
SUSHI = _sushi;
MASTER_PID = _MASTER_PID;
}
/// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUSHI.
/// Any balance of transaction sender in `dummyToken` is transferred.
/// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives.
/// @param dummyToken The address of the ERC-20 token to deposit into MCV1.
function init(IERC20 dummyToken) external {
uint256 balance = dummyToken.balanceOf(msg.sender);
require(balance != 0, "MasterChefV2: Balance must exceed 0");
dummyToken.safeTransferFrom(msg.sender, address(this), balance);
dummyToken.approve(address(MASTER_CHEF), balance);
MASTER_CHEF.deposit(MASTER_PID, balance);
emit LogInit();
}
/// @notice Returns the number of MCV2 pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _lpToken Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate.
function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })
);
emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder);
}
/// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
}
/// @notice Set the `migrator` contract. Can only be called by the owner.
/// @param _migrator The contract address to set.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
/// @notice Migrate LP token to another LP contract through the `migrator` contract.
/// @param _pid The index of the pool. See `poolInfo`.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "MasterChefV2: no migrator set");
IERC20 _lpToken = lpToken[_pid];
uint256 bal = _lpToken.balanceOf(address(this));
_lpToken.approve(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(_lpToken);
require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match");
lpToken[_pid] = newLpToken;
}
/// @notice View function to see pending SUSHI on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending SUSHI reward for a given user.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply);
}
pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256();
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Calculates and returns the `amount` of SUSHI per block.
function sushiPerBlock() public view returns (uint256 amount) {
amount =
uint256(MASTERCHEF_SUSHI_PER_BLOCK).mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) /
MASTER_CHEF.totalAllocPoint();
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
pool.accSushiPerShare = pool.accSushiPerShare.add(
(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare);
}
}
/// @notice Deposit LP tokens to MCV2 for SUSHI allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of SUSHI rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi;
// Interactions
if (_pendingSushi != 0) {
SUSHI.safeTransfer(to, _pendingSushi);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and SUSHI rewards.
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
SUSHI.safeTransfer(to, _pendingSushi);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Harvests SUSHI from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract.
function harvestFromMasterChef() public {
MASTER_CHEF.deposit(MASTER_PID, 0);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
lpToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
} | /// @notice The (older) MasterChef contract gives out a constant number of SUSHI tokens per block.
/// It is the only address with minting rights for SUSHI.
/// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token
/// that is deposited into the MasterChef V1 (MCV1) contract.
/// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives. | NatSpecSingleLine | deposit | function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
| /// @notice Deposit LP tokens to MCV2 for SUSHI allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
8530,
9133
]
} | 1,468 |
||
ALCXRewarder | contracts/MasterChefV2.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChefV2 | contract MasterChefV2 is BoringOwnable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
using SignedSafeMath for int256;
/// @notice Info of each MCV2 user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of SUSHI entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each MCV2 pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of SUSHI to distribute per block.
struct PoolInfo {
uint128 accSushiPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
/// @notice Address of MCV1 contract.
IMasterChef public immutable MASTER_CHEF;
/// @notice Address of SUSHI contract.
IERC20 public immutable SUSHI;
/// @notice The index of MCV2 master pool in MCV1.
uint256 public immutable MASTER_PID;
// @notice The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
/// @notice Info of each MCV2 pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each MCV2 pool.
IERC20[] public lpToken;
/// @notice Address of each `IRewarder` contract in MCV2.
IRewarder[] public rewarder;
/// @notice Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20;
uint256 private constant ACC_SUSHI_PRECISION = 1e12;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder);
event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare);
event LogInit();
/// @param _MASTER_CHEF The SushiSwap MCV1 contract address.
/// @param _sushi The SUSHI token contract address.
/// @param _MASTER_PID The pool ID of the dummy token on the base MCV1 contract.
constructor(
IMasterChef _MASTER_CHEF,
IERC20 _sushi,
uint256 _MASTER_PID
) public {
MASTER_CHEF = _MASTER_CHEF;
SUSHI = _sushi;
MASTER_PID = _MASTER_PID;
}
/// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUSHI.
/// Any balance of transaction sender in `dummyToken` is transferred.
/// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives.
/// @param dummyToken The address of the ERC-20 token to deposit into MCV1.
function init(IERC20 dummyToken) external {
uint256 balance = dummyToken.balanceOf(msg.sender);
require(balance != 0, "MasterChefV2: Balance must exceed 0");
dummyToken.safeTransferFrom(msg.sender, address(this), balance);
dummyToken.approve(address(MASTER_CHEF), balance);
MASTER_CHEF.deposit(MASTER_PID, balance);
emit LogInit();
}
/// @notice Returns the number of MCV2 pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _lpToken Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate.
function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })
);
emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder);
}
/// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
}
/// @notice Set the `migrator` contract. Can only be called by the owner.
/// @param _migrator The contract address to set.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
/// @notice Migrate LP token to another LP contract through the `migrator` contract.
/// @param _pid The index of the pool. See `poolInfo`.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "MasterChefV2: no migrator set");
IERC20 _lpToken = lpToken[_pid];
uint256 bal = _lpToken.balanceOf(address(this));
_lpToken.approve(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(_lpToken);
require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match");
lpToken[_pid] = newLpToken;
}
/// @notice View function to see pending SUSHI on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending SUSHI reward for a given user.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply);
}
pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256();
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Calculates and returns the `amount` of SUSHI per block.
function sushiPerBlock() public view returns (uint256 amount) {
amount =
uint256(MASTERCHEF_SUSHI_PER_BLOCK).mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) /
MASTER_CHEF.totalAllocPoint();
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
pool.accSushiPerShare = pool.accSushiPerShare.add(
(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare);
}
}
/// @notice Deposit LP tokens to MCV2 for SUSHI allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of SUSHI rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi;
// Interactions
if (_pendingSushi != 0) {
SUSHI.safeTransfer(to, _pendingSushi);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and SUSHI rewards.
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
SUSHI.safeTransfer(to, _pendingSushi);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Harvests SUSHI from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract.
function harvestFromMasterChef() public {
MASTER_CHEF.deposit(MASTER_PID, 0);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
lpToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
} | /// @notice The (older) MasterChef contract gives out a constant number of SUSHI tokens per block.
/// It is the only address with minting rights for SUSHI.
/// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token
/// that is deposited into the MasterChef V1 (MCV1) contract.
/// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives. | NatSpecSingleLine | withdraw | function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
| /// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
9323,
9917
]
} | 1,469 |
||
ALCXRewarder | contracts/MasterChefV2.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChefV2 | contract MasterChefV2 is BoringOwnable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
using SignedSafeMath for int256;
/// @notice Info of each MCV2 user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of SUSHI entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each MCV2 pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of SUSHI to distribute per block.
struct PoolInfo {
uint128 accSushiPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
/// @notice Address of MCV1 contract.
IMasterChef public immutable MASTER_CHEF;
/// @notice Address of SUSHI contract.
IERC20 public immutable SUSHI;
/// @notice The index of MCV2 master pool in MCV1.
uint256 public immutable MASTER_PID;
// @notice The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
/// @notice Info of each MCV2 pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each MCV2 pool.
IERC20[] public lpToken;
/// @notice Address of each `IRewarder` contract in MCV2.
IRewarder[] public rewarder;
/// @notice Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20;
uint256 private constant ACC_SUSHI_PRECISION = 1e12;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder);
event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare);
event LogInit();
/// @param _MASTER_CHEF The SushiSwap MCV1 contract address.
/// @param _sushi The SUSHI token contract address.
/// @param _MASTER_PID The pool ID of the dummy token on the base MCV1 contract.
constructor(
IMasterChef _MASTER_CHEF,
IERC20 _sushi,
uint256 _MASTER_PID
) public {
MASTER_CHEF = _MASTER_CHEF;
SUSHI = _sushi;
MASTER_PID = _MASTER_PID;
}
/// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUSHI.
/// Any balance of transaction sender in `dummyToken` is transferred.
/// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives.
/// @param dummyToken The address of the ERC-20 token to deposit into MCV1.
function init(IERC20 dummyToken) external {
uint256 balance = dummyToken.balanceOf(msg.sender);
require(balance != 0, "MasterChefV2: Balance must exceed 0");
dummyToken.safeTransferFrom(msg.sender, address(this), balance);
dummyToken.approve(address(MASTER_CHEF), balance);
MASTER_CHEF.deposit(MASTER_PID, balance);
emit LogInit();
}
/// @notice Returns the number of MCV2 pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _lpToken Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate.
function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })
);
emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder);
}
/// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
}
/// @notice Set the `migrator` contract. Can only be called by the owner.
/// @param _migrator The contract address to set.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
/// @notice Migrate LP token to another LP contract through the `migrator` contract.
/// @param _pid The index of the pool. See `poolInfo`.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "MasterChefV2: no migrator set");
IERC20 _lpToken = lpToken[_pid];
uint256 bal = _lpToken.balanceOf(address(this));
_lpToken.approve(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(_lpToken);
require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match");
lpToken[_pid] = newLpToken;
}
/// @notice View function to see pending SUSHI on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending SUSHI reward for a given user.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply);
}
pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256();
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Calculates and returns the `amount` of SUSHI per block.
function sushiPerBlock() public view returns (uint256 amount) {
amount =
uint256(MASTERCHEF_SUSHI_PER_BLOCK).mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) /
MASTER_CHEF.totalAllocPoint();
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
pool.accSushiPerShare = pool.accSushiPerShare.add(
(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare);
}
}
/// @notice Deposit LP tokens to MCV2 for SUSHI allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of SUSHI rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi;
// Interactions
if (_pendingSushi != 0) {
SUSHI.safeTransfer(to, _pendingSushi);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and SUSHI rewards.
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
SUSHI.safeTransfer(to, _pendingSushi);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Harvests SUSHI from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract.
function harvestFromMasterChef() public {
MASTER_CHEF.deposit(MASTER_PID, 0);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
lpToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
} | /// @notice The (older) MasterChef contract gives out a constant number of SUSHI tokens per block.
/// It is the only address with minting rights for SUSHI.
/// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token
/// that is deposited into the MasterChef V1 (MCV1) contract.
/// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives. | NatSpecSingleLine | harvest | function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi;
// Interactions
if (_pendingSushi != 0) {
SUSHI.safeTransfer(to, _pendingSushi);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
emit Harvest(msg.sender, pid, _pendingSushi);
}
| /// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of SUSHI rewards. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
10078,
10759
]
} | 1,470 |
||
ALCXRewarder | contracts/MasterChefV2.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChefV2 | contract MasterChefV2 is BoringOwnable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
using SignedSafeMath for int256;
/// @notice Info of each MCV2 user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of SUSHI entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each MCV2 pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of SUSHI to distribute per block.
struct PoolInfo {
uint128 accSushiPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
/// @notice Address of MCV1 contract.
IMasterChef public immutable MASTER_CHEF;
/// @notice Address of SUSHI contract.
IERC20 public immutable SUSHI;
/// @notice The index of MCV2 master pool in MCV1.
uint256 public immutable MASTER_PID;
// @notice The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
/// @notice Info of each MCV2 pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each MCV2 pool.
IERC20[] public lpToken;
/// @notice Address of each `IRewarder` contract in MCV2.
IRewarder[] public rewarder;
/// @notice Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20;
uint256 private constant ACC_SUSHI_PRECISION = 1e12;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder);
event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare);
event LogInit();
/// @param _MASTER_CHEF The SushiSwap MCV1 contract address.
/// @param _sushi The SUSHI token contract address.
/// @param _MASTER_PID The pool ID of the dummy token on the base MCV1 contract.
constructor(
IMasterChef _MASTER_CHEF,
IERC20 _sushi,
uint256 _MASTER_PID
) public {
MASTER_CHEF = _MASTER_CHEF;
SUSHI = _sushi;
MASTER_PID = _MASTER_PID;
}
/// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUSHI.
/// Any balance of transaction sender in `dummyToken` is transferred.
/// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives.
/// @param dummyToken The address of the ERC-20 token to deposit into MCV1.
function init(IERC20 dummyToken) external {
uint256 balance = dummyToken.balanceOf(msg.sender);
require(balance != 0, "MasterChefV2: Balance must exceed 0");
dummyToken.safeTransferFrom(msg.sender, address(this), balance);
dummyToken.approve(address(MASTER_CHEF), balance);
MASTER_CHEF.deposit(MASTER_PID, balance);
emit LogInit();
}
/// @notice Returns the number of MCV2 pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _lpToken Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate.
function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })
);
emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder);
}
/// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
}
/// @notice Set the `migrator` contract. Can only be called by the owner.
/// @param _migrator The contract address to set.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
/// @notice Migrate LP token to another LP contract through the `migrator` contract.
/// @param _pid The index of the pool. See `poolInfo`.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "MasterChefV2: no migrator set");
IERC20 _lpToken = lpToken[_pid];
uint256 bal = _lpToken.balanceOf(address(this));
_lpToken.approve(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(_lpToken);
require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match");
lpToken[_pid] = newLpToken;
}
/// @notice View function to see pending SUSHI on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending SUSHI reward for a given user.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply);
}
pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256();
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Calculates and returns the `amount` of SUSHI per block.
function sushiPerBlock() public view returns (uint256 amount) {
amount =
uint256(MASTERCHEF_SUSHI_PER_BLOCK).mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) /
MASTER_CHEF.totalAllocPoint();
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
pool.accSushiPerShare = pool.accSushiPerShare.add(
(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare);
}
}
/// @notice Deposit LP tokens to MCV2 for SUSHI allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of SUSHI rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi;
// Interactions
if (_pendingSushi != 0) {
SUSHI.safeTransfer(to, _pendingSushi);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and SUSHI rewards.
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
SUSHI.safeTransfer(to, _pendingSushi);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Harvests SUSHI from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract.
function harvestFromMasterChef() public {
MASTER_CHEF.deposit(MASTER_PID, 0);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
lpToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
} | /// @notice The (older) MasterChef contract gives out a constant number of SUSHI tokens per block.
/// It is the only address with minting rights for SUSHI.
/// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token
/// that is deposited into the MasterChef V1 (MCV1) contract.
/// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives. | NatSpecSingleLine | withdrawAndHarvest | function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
SUSHI.safeTransfer(to, _pendingSushi);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSushi);
}
| /// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and SUSHI rewards. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
11019,
11901
]
} | 1,471 |
||
ALCXRewarder | contracts/MasterChefV2.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChefV2 | contract MasterChefV2 is BoringOwnable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
using SignedSafeMath for int256;
/// @notice Info of each MCV2 user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of SUSHI entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each MCV2 pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of SUSHI to distribute per block.
struct PoolInfo {
uint128 accSushiPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
/// @notice Address of MCV1 contract.
IMasterChef public immutable MASTER_CHEF;
/// @notice Address of SUSHI contract.
IERC20 public immutable SUSHI;
/// @notice The index of MCV2 master pool in MCV1.
uint256 public immutable MASTER_PID;
// @notice The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
/// @notice Info of each MCV2 pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each MCV2 pool.
IERC20[] public lpToken;
/// @notice Address of each `IRewarder` contract in MCV2.
IRewarder[] public rewarder;
/// @notice Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20;
uint256 private constant ACC_SUSHI_PRECISION = 1e12;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder);
event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare);
event LogInit();
/// @param _MASTER_CHEF The SushiSwap MCV1 contract address.
/// @param _sushi The SUSHI token contract address.
/// @param _MASTER_PID The pool ID of the dummy token on the base MCV1 contract.
constructor(
IMasterChef _MASTER_CHEF,
IERC20 _sushi,
uint256 _MASTER_PID
) public {
MASTER_CHEF = _MASTER_CHEF;
SUSHI = _sushi;
MASTER_PID = _MASTER_PID;
}
/// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUSHI.
/// Any balance of transaction sender in `dummyToken` is transferred.
/// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives.
/// @param dummyToken The address of the ERC-20 token to deposit into MCV1.
function init(IERC20 dummyToken) external {
uint256 balance = dummyToken.balanceOf(msg.sender);
require(balance != 0, "MasterChefV2: Balance must exceed 0");
dummyToken.safeTransferFrom(msg.sender, address(this), balance);
dummyToken.approve(address(MASTER_CHEF), balance);
MASTER_CHEF.deposit(MASTER_PID, balance);
emit LogInit();
}
/// @notice Returns the number of MCV2 pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _lpToken Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate.
function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })
);
emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder);
}
/// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
}
/// @notice Set the `migrator` contract. Can only be called by the owner.
/// @param _migrator The contract address to set.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
/// @notice Migrate LP token to another LP contract through the `migrator` contract.
/// @param _pid The index of the pool. See `poolInfo`.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "MasterChefV2: no migrator set");
IERC20 _lpToken = lpToken[_pid];
uint256 bal = _lpToken.balanceOf(address(this));
_lpToken.approve(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(_lpToken);
require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match");
lpToken[_pid] = newLpToken;
}
/// @notice View function to see pending SUSHI on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending SUSHI reward for a given user.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply);
}
pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256();
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Calculates and returns the `amount` of SUSHI per block.
function sushiPerBlock() public view returns (uint256 amount) {
amount =
uint256(MASTERCHEF_SUSHI_PER_BLOCK).mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) /
MASTER_CHEF.totalAllocPoint();
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
pool.accSushiPerShare = pool.accSushiPerShare.add(
(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare);
}
}
/// @notice Deposit LP tokens to MCV2 for SUSHI allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of SUSHI rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi;
// Interactions
if (_pendingSushi != 0) {
SUSHI.safeTransfer(to, _pendingSushi);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and SUSHI rewards.
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
SUSHI.safeTransfer(to, _pendingSushi);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Harvests SUSHI from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract.
function harvestFromMasterChef() public {
MASTER_CHEF.deposit(MASTER_PID, 0);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
lpToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
} | /// @notice The (older) MasterChef contract gives out a constant number of SUSHI tokens per block.
/// It is the only address with minting rights for SUSHI.
/// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token
/// that is deposited into the MasterChef V1 (MCV1) contract.
/// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives. | NatSpecSingleLine | harvestFromMasterChef | function harvestFromMasterChef() public {
MASTER_CHEF.deposit(MASTER_PID, 0);
}
| /// @notice Harvests SUSHI from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
12000,
12083
]
} | 1,472 |
||
ALCXRewarder | contracts/MasterChefV2.sol | 0xd101479ce045b903ae14ec6afa7a11171afb5dfa | Solidity | MasterChefV2 | contract MasterChefV2 is BoringOwnable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
using SignedSafeMath for int256;
/// @notice Info of each MCV2 user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of SUSHI entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each MCV2 pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of SUSHI to distribute per block.
struct PoolInfo {
uint128 accSushiPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
/// @notice Address of MCV1 contract.
IMasterChef public immutable MASTER_CHEF;
/// @notice Address of SUSHI contract.
IERC20 public immutable SUSHI;
/// @notice The index of MCV2 master pool in MCV1.
uint256 public immutable MASTER_PID;
// @notice The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
/// @notice Info of each MCV2 pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each MCV2 pool.
IERC20[] public lpToken;
/// @notice Address of each `IRewarder` contract in MCV2.
IRewarder[] public rewarder;
/// @notice Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20;
uint256 private constant ACC_SUSHI_PRECISION = 1e12;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder);
event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare);
event LogInit();
/// @param _MASTER_CHEF The SushiSwap MCV1 contract address.
/// @param _sushi The SUSHI token contract address.
/// @param _MASTER_PID The pool ID of the dummy token on the base MCV1 contract.
constructor(
IMasterChef _MASTER_CHEF,
IERC20 _sushi,
uint256 _MASTER_PID
) public {
MASTER_CHEF = _MASTER_CHEF;
SUSHI = _sushi;
MASTER_PID = _MASTER_PID;
}
/// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUSHI.
/// Any balance of transaction sender in `dummyToken` is transferred.
/// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives.
/// @param dummyToken The address of the ERC-20 token to deposit into MCV1.
function init(IERC20 dummyToken) external {
uint256 balance = dummyToken.balanceOf(msg.sender);
require(balance != 0, "MasterChefV2: Balance must exceed 0");
dummyToken.safeTransferFrom(msg.sender, address(this), balance);
dummyToken.approve(address(MASTER_CHEF), balance);
MASTER_CHEF.deposit(MASTER_PID, balance);
emit LogInit();
}
/// @notice Returns the number of MCV2 pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _lpToken Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate.
function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })
);
emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder);
}
/// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
}
/// @notice Set the `migrator` contract. Can only be called by the owner.
/// @param _migrator The contract address to set.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
/// @notice Migrate LP token to another LP contract through the `migrator` contract.
/// @param _pid The index of the pool. See `poolInfo`.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "MasterChefV2: no migrator set");
IERC20 _lpToken = lpToken[_pid];
uint256 bal = _lpToken.balanceOf(address(this));
_lpToken.approve(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(_lpToken);
require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match");
lpToken[_pid] = newLpToken;
}
/// @notice View function to see pending SUSHI on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending SUSHI reward for a given user.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply);
}
pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256();
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Calculates and returns the `amount` of SUSHI per block.
function sushiPerBlock() public view returns (uint256 amount) {
amount =
uint256(MASTERCHEF_SUSHI_PER_BLOCK).mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) /
MASTER_CHEF.totalAllocPoint();
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
pool.accSushiPerShare = pool.accSushiPerShare.add(
(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare);
}
}
/// @notice Deposit LP tokens to MCV2 for SUSHI allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of SUSHI rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi;
// Interactions
if (_pendingSushi != 0) {
SUSHI.safeTransfer(to, _pendingSushi);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and SUSHI rewards.
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
SUSHI.safeTransfer(to, _pendingSushi);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Harvests SUSHI from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract.
function harvestFromMasterChef() public {
MASTER_CHEF.deposit(MASTER_PID, 0);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
lpToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
} | /// @notice The (older) MasterChef contract gives out a constant number of SUSHI tokens per block.
/// It is the only address with minting rights for SUSHI.
/// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token
/// that is deposited into the MasterChef V1 (MCV1) contract.
/// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives. | NatSpecSingleLine | emergencyWithdraw | function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
lpToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
| /// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens. | NatSpecSingleLine | v0.6.12+commit.27d51765 | {
"func_code_index": [
12250,
12740
]
} | 1,473 |
||
StreamingFeeModule | contracts/protocol/modules/StreamingFeeModule.sol | 0xa840939edafa7641cfc7ac1e337e322190ac95ff | Solidity | StreamingFeeModule | contract StreamingFeeModule is ModuleBase, ReentrancyGuard {
using SafeMath for uint256;
using PreciseUnitMath for uint256;
using SafeCast for uint256;
using SignedSafeMath for int256;
using PreciseUnitMath for int256;
using SafeCast for int256;
/* ============ Structs ============ */
struct FeeState {
address feeRecipient; // Address to accrue fees to
uint256 maxStreamingFeePercentage; // Max streaming fee maanager commits to using (1% = 1e16, 100% = 1e18)
uint256 streamingFeePercentage; // Percent of Set accruing to manager annually (1% = 1e16, 100% = 1e18)
uint256 lastStreamingFeeTimestamp; // Timestamp last streaming fee was accrued
}
/* ============ Events ============ */
event FeeActualized(address indexed _setToken, uint256 _managerFee, uint256 _protocolFee);
event StreamingFeeUpdated(address indexed _setToken, uint256 _newStreamingFee);
event FeeRecipientUpdated(address indexed _setToken, address _newFeeRecipient);
/* ============ Constants ============ */
uint256 private constant ONE_YEAR_IN_SECONDS = 365.25 days;
uint256 private constant PROTOCOL_STREAMING_FEE_INDEX = 0;
/* ============ State Variables ============ */
mapping(ISetToken => FeeState) public feeStates;
/* ============ Constructor ============ */
// solhint-disable-next-line no-empty-blocks
constructor(IController _controller) ModuleBase(_controller) {}
/* ============ External Functions ============ */
/*
* Calculates total inflation percentage then mints new Sets to the fee recipient. Position units are
* then adjusted down (in magnitude) in order to ensure full collateralization. Callable by anyone.
*
* @param _setToken Address of SetToken
*/
function accrueFee(ISetToken _setToken)
public
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
uint256 managerFee;
uint256 protocolFee;
if (_streamingFeePercentage(_setToken) > 0) {
uint256 inflationFeePercentage = _calculateStreamingFee(_setToken);
// Calculate incentiveFee inflation
uint256 feeQuantity = _calculateStreamingFeeInflation(_setToken, inflationFeePercentage);
// Mint new Sets to manager and protocol
(managerFee, protocolFee) = _mintManagerAndProtocolFee(_setToken, feeQuantity);
_editPositionMultiplier(_setToken, inflationFeePercentage);
}
// solhint-disable-next-line not-rely-on-time
feeStates[_setToken].lastStreamingFeeTimestamp = block.timestamp;
emit FeeActualized(address(_setToken), managerFee, protocolFee);
}
/**
* SET MANAGER ONLY. Initialize module with SetToken and set the fee state for the SetToken. Passed
* _settings will have lastStreamingFeeTimestamp over-written.
*
* @param _setToken Address of SetToken
* @param _settings FeeState struct defining fee parameters
*/
function initialize(ISetToken _setToken, FeeState memory _settings)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
require(_settings.feeRecipient != address(0), "Fee Recipient must be non-zero address.");
require(
_settings.maxStreamingFeePercentage < PreciseUnitMath.preciseUnit(),
"Max fee must be < 100%."
);
require(
_settings.streamingFeePercentage <= _settings.maxStreamingFeePercentage,
"Fee must be <= max."
);
// solhint-disable-next-line not-rely-on-time
_settings.lastStreamingFeeTimestamp = block.timestamp;
feeStates[_setToken] = _settings;
_setToken.initializeModule();
}
/**
* Removes this module from the SetToken, via call by the SetToken. Manager's feeState is deleted. Fees
* are not accrued in case reason for removing module is related to fee accrual.
*/
function removeModule() external override {
delete feeStates[ISetToken(msg.sender)];
}
/*
* Set new streaming fee. Fees accrue at current rate then new rate is set.
* Fees are accrued to prevent the manager from unfairly accruing a larger percentage.
*
* @param _setToken Address of SetToken
* @param _newFee New streaming fee 18 decimal precision
*/
function updateStreamingFee(ISetToken _setToken, uint256 _newFee)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFee < _maxStreamingFeePercentage(_setToken), "Fee must be less than max");
accrueFee(_setToken);
feeStates[_setToken].streamingFeePercentage = _newFee;
emit StreamingFeeUpdated(address(_setToken), _newFee);
}
/*
* Set new fee recipient.
*
* @param _setToken Address of SetToken
* @param _newFeeRecipient New fee recipient
*/
function updateFeeRecipient(ISetToken _setToken, address _newFeeRecipient)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFeeRecipient != address(0), "Fee Recipient must be non-zero address.");
feeStates[_setToken].feeRecipient = _newFeeRecipient;
emit FeeRecipientUpdated(address(_setToken), _newFeeRecipient);
}
/*
* Calculates total inflation percentage in order to accrue fees to manager.
*
* @param _setToken Address of SetToken
* @return uint256 Percent inflation of supply
*/
function getFee(ISetToken _setToken) external view returns (uint256) {
return _calculateStreamingFee(_setToken);
}
/* ============ Internal Functions ============ */
/**
* Calculates streaming fee by multiplying streamingFeePercentage by the elapsed amount of time since the last fee
* was collected divided by one year in seconds, since the fee is a yearly fee.
*
* @param _setToken Address of Set to have feeState updated
* @return uint256 Streaming fee denominated in percentage of totalSupply
*/
function _calculateStreamingFee(ISetToken _setToken) internal view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
uint256 timeSinceLastFee = block.timestamp.sub(_lastStreamingFeeTimestamp(_setToken));
// Streaming fee is streaming fee times years since last fee
return timeSinceLastFee.mul(_streamingFeePercentage(_setToken)).div(ONE_YEAR_IN_SECONDS);
}
/**
* Returns the new incentive fee denominated in the number of SetTokens to mint. The calculation for the fee involves
* implying mint quantity so that the feeRecipient owns the fee percentage of the entire supply of the Set.
*
* The formula to solve for fee is:
* (feeQuantity / feeQuantity) + totalSupply = fee / scaleFactor
*
* The simplified formula utilized below is:
* feeQuantity = fee * totalSupply / (scaleFactor - fee)
*
* @param _setToken SetToken instance
* @param _feePercentage Fee levied to feeRecipient
* @return uint256 New RebalancingSet issue quantity
*/
function _calculateStreamingFeeInflation(ISetToken _setToken, uint256 _feePercentage)
internal
view
returns (uint256)
{
uint256 totalSupply = _setToken.totalSupply();
// fee * totalSupply
uint256 a = _feePercentage.mul(totalSupply);
// ScaleFactor (10e18) - fee
uint256 b = PreciseUnitMath.preciseUnit().sub(_feePercentage);
return a.div(b);
}
/**
* Mints sets to both the manager and the protocol. Protocol takes a percentage fee of the total amount of Sets
* minted to manager.
*
* @param _setToken SetToken instance
* @param _feeQuantity Amount of Sets to be minted as fees
* @return uint256 Amount of Sets accrued to manager as fee
* @return uint256 Amount of Sets accrued to protocol as fee
*/
function _mintManagerAndProtocolFee(ISetToken _setToken, uint256 _feeQuantity)
internal
returns (uint256, uint256)
{
address protocolFeeRecipient = controller.feeRecipient();
uint256 protocolFee = controller.getModuleFee(address(this), PROTOCOL_STREAMING_FEE_INDEX);
uint256 protocolFeeAmount = _feeQuantity.preciseMul(protocolFee);
uint256 managerFeeAmount = _feeQuantity.sub(protocolFeeAmount);
_setToken.mint(_feeRecipient(_setToken), managerFeeAmount);
if (protocolFeeAmount > 0) {
_setToken.mint(protocolFeeRecipient, protocolFeeAmount);
}
return (managerFeeAmount, protocolFeeAmount);
}
/**
* Calculates new position multiplier according to following formula:
*
* newMultiplier = oldMultiplier * (1-inflationFee)
*
* This reduces position sizes to offset increase in supply due to fee collection.
*
* @param _setToken SetToken instance
* @param _inflationFee Fee inflation rate
*/
function _editPositionMultiplier(ISetToken _setToken, uint256 _inflationFee) internal {
int256 currentMultipler = _setToken.positionMultiplier();
int256 newMultiplier = currentMultipler.preciseMul(
PreciseUnitMath.preciseUnit().sub(_inflationFee).toInt256()
);
_setToken.editPositionMultiplier(newMultiplier);
}
function _feeRecipient(ISetToken _set) internal view returns (address) {
return feeStates[_set].feeRecipient;
}
function _lastStreamingFeeTimestamp(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].lastStreamingFeeTimestamp;
}
function _maxStreamingFeePercentage(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].maxStreamingFeePercentage;
}
function _streamingFeePercentage(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].streamingFeePercentage;
}
} | /**
* @title StreamingFeeModule
* @author Set Protocol
*
* Smart contract that accrues streaming fees for Set managers. Streaming fees are denominated as percent
* per year and realized as Set inflation rewarded to the manager.
*/ | NatSpecMultiLine | accrueFee | function accrueFee(ISetToken _setToken)
public
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
uint256 managerFee;
uint256 protocolFee;
if (_streamingFeePercentage(_setToken) > 0) {
uint256 inflationFeePercentage = _calculateStreamingFee(_setToken);
// Calculate incentiveFee inflation
uint256 feeQuantity = _calculateStreamingFeeInflation(_setToken, inflationFeePercentage);
// Mint new Sets to manager and protocol
(managerFee, protocolFee) = _mintManagerAndProtocolFee(_setToken, feeQuantity);
_editPositionMultiplier(_setToken, inflationFeePercentage);
}
// solhint-disable-next-line not-rely-on-time
feeStates[_setToken].lastStreamingFeeTimestamp = block.timestamp;
emit FeeActualized(address(_setToken), managerFee, protocolFee);
}
| /*
* Calculates total inflation percentage then mints new Sets to the fee recipient. Position units are
* then adjusted down (in magnitude) in order to ensure full collateralization. Callable by anyone.
*
* @param _setToken Address of SetToken
*/ | Comment | v0.7.6+commit.7338295f | None | {
"func_code_index": [
1742,
2572
]
} | 1,474 |
|
StreamingFeeModule | contracts/protocol/modules/StreamingFeeModule.sol | 0xa840939edafa7641cfc7ac1e337e322190ac95ff | Solidity | StreamingFeeModule | contract StreamingFeeModule is ModuleBase, ReentrancyGuard {
using SafeMath for uint256;
using PreciseUnitMath for uint256;
using SafeCast for uint256;
using SignedSafeMath for int256;
using PreciseUnitMath for int256;
using SafeCast for int256;
/* ============ Structs ============ */
struct FeeState {
address feeRecipient; // Address to accrue fees to
uint256 maxStreamingFeePercentage; // Max streaming fee maanager commits to using (1% = 1e16, 100% = 1e18)
uint256 streamingFeePercentage; // Percent of Set accruing to manager annually (1% = 1e16, 100% = 1e18)
uint256 lastStreamingFeeTimestamp; // Timestamp last streaming fee was accrued
}
/* ============ Events ============ */
event FeeActualized(address indexed _setToken, uint256 _managerFee, uint256 _protocolFee);
event StreamingFeeUpdated(address indexed _setToken, uint256 _newStreamingFee);
event FeeRecipientUpdated(address indexed _setToken, address _newFeeRecipient);
/* ============ Constants ============ */
uint256 private constant ONE_YEAR_IN_SECONDS = 365.25 days;
uint256 private constant PROTOCOL_STREAMING_FEE_INDEX = 0;
/* ============ State Variables ============ */
mapping(ISetToken => FeeState) public feeStates;
/* ============ Constructor ============ */
// solhint-disable-next-line no-empty-blocks
constructor(IController _controller) ModuleBase(_controller) {}
/* ============ External Functions ============ */
/*
* Calculates total inflation percentage then mints new Sets to the fee recipient. Position units are
* then adjusted down (in magnitude) in order to ensure full collateralization. Callable by anyone.
*
* @param _setToken Address of SetToken
*/
function accrueFee(ISetToken _setToken)
public
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
uint256 managerFee;
uint256 protocolFee;
if (_streamingFeePercentage(_setToken) > 0) {
uint256 inflationFeePercentage = _calculateStreamingFee(_setToken);
// Calculate incentiveFee inflation
uint256 feeQuantity = _calculateStreamingFeeInflation(_setToken, inflationFeePercentage);
// Mint new Sets to manager and protocol
(managerFee, protocolFee) = _mintManagerAndProtocolFee(_setToken, feeQuantity);
_editPositionMultiplier(_setToken, inflationFeePercentage);
}
// solhint-disable-next-line not-rely-on-time
feeStates[_setToken].lastStreamingFeeTimestamp = block.timestamp;
emit FeeActualized(address(_setToken), managerFee, protocolFee);
}
/**
* SET MANAGER ONLY. Initialize module with SetToken and set the fee state for the SetToken. Passed
* _settings will have lastStreamingFeeTimestamp over-written.
*
* @param _setToken Address of SetToken
* @param _settings FeeState struct defining fee parameters
*/
function initialize(ISetToken _setToken, FeeState memory _settings)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
require(_settings.feeRecipient != address(0), "Fee Recipient must be non-zero address.");
require(
_settings.maxStreamingFeePercentage < PreciseUnitMath.preciseUnit(),
"Max fee must be < 100%."
);
require(
_settings.streamingFeePercentage <= _settings.maxStreamingFeePercentage,
"Fee must be <= max."
);
// solhint-disable-next-line not-rely-on-time
_settings.lastStreamingFeeTimestamp = block.timestamp;
feeStates[_setToken] = _settings;
_setToken.initializeModule();
}
/**
* Removes this module from the SetToken, via call by the SetToken. Manager's feeState is deleted. Fees
* are not accrued in case reason for removing module is related to fee accrual.
*/
function removeModule() external override {
delete feeStates[ISetToken(msg.sender)];
}
/*
* Set new streaming fee. Fees accrue at current rate then new rate is set.
* Fees are accrued to prevent the manager from unfairly accruing a larger percentage.
*
* @param _setToken Address of SetToken
* @param _newFee New streaming fee 18 decimal precision
*/
function updateStreamingFee(ISetToken _setToken, uint256 _newFee)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFee < _maxStreamingFeePercentage(_setToken), "Fee must be less than max");
accrueFee(_setToken);
feeStates[_setToken].streamingFeePercentage = _newFee;
emit StreamingFeeUpdated(address(_setToken), _newFee);
}
/*
* Set new fee recipient.
*
* @param _setToken Address of SetToken
* @param _newFeeRecipient New fee recipient
*/
function updateFeeRecipient(ISetToken _setToken, address _newFeeRecipient)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFeeRecipient != address(0), "Fee Recipient must be non-zero address.");
feeStates[_setToken].feeRecipient = _newFeeRecipient;
emit FeeRecipientUpdated(address(_setToken), _newFeeRecipient);
}
/*
* Calculates total inflation percentage in order to accrue fees to manager.
*
* @param _setToken Address of SetToken
* @return uint256 Percent inflation of supply
*/
function getFee(ISetToken _setToken) external view returns (uint256) {
return _calculateStreamingFee(_setToken);
}
/* ============ Internal Functions ============ */
/**
* Calculates streaming fee by multiplying streamingFeePercentage by the elapsed amount of time since the last fee
* was collected divided by one year in seconds, since the fee is a yearly fee.
*
* @param _setToken Address of Set to have feeState updated
* @return uint256 Streaming fee denominated in percentage of totalSupply
*/
function _calculateStreamingFee(ISetToken _setToken) internal view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
uint256 timeSinceLastFee = block.timestamp.sub(_lastStreamingFeeTimestamp(_setToken));
// Streaming fee is streaming fee times years since last fee
return timeSinceLastFee.mul(_streamingFeePercentage(_setToken)).div(ONE_YEAR_IN_SECONDS);
}
/**
* Returns the new incentive fee denominated in the number of SetTokens to mint. The calculation for the fee involves
* implying mint quantity so that the feeRecipient owns the fee percentage of the entire supply of the Set.
*
* The formula to solve for fee is:
* (feeQuantity / feeQuantity) + totalSupply = fee / scaleFactor
*
* The simplified formula utilized below is:
* feeQuantity = fee * totalSupply / (scaleFactor - fee)
*
* @param _setToken SetToken instance
* @param _feePercentage Fee levied to feeRecipient
* @return uint256 New RebalancingSet issue quantity
*/
function _calculateStreamingFeeInflation(ISetToken _setToken, uint256 _feePercentage)
internal
view
returns (uint256)
{
uint256 totalSupply = _setToken.totalSupply();
// fee * totalSupply
uint256 a = _feePercentage.mul(totalSupply);
// ScaleFactor (10e18) - fee
uint256 b = PreciseUnitMath.preciseUnit().sub(_feePercentage);
return a.div(b);
}
/**
* Mints sets to both the manager and the protocol. Protocol takes a percentage fee of the total amount of Sets
* minted to manager.
*
* @param _setToken SetToken instance
* @param _feeQuantity Amount of Sets to be minted as fees
* @return uint256 Amount of Sets accrued to manager as fee
* @return uint256 Amount of Sets accrued to protocol as fee
*/
function _mintManagerAndProtocolFee(ISetToken _setToken, uint256 _feeQuantity)
internal
returns (uint256, uint256)
{
address protocolFeeRecipient = controller.feeRecipient();
uint256 protocolFee = controller.getModuleFee(address(this), PROTOCOL_STREAMING_FEE_INDEX);
uint256 protocolFeeAmount = _feeQuantity.preciseMul(protocolFee);
uint256 managerFeeAmount = _feeQuantity.sub(protocolFeeAmount);
_setToken.mint(_feeRecipient(_setToken), managerFeeAmount);
if (protocolFeeAmount > 0) {
_setToken.mint(protocolFeeRecipient, protocolFeeAmount);
}
return (managerFeeAmount, protocolFeeAmount);
}
/**
* Calculates new position multiplier according to following formula:
*
* newMultiplier = oldMultiplier * (1-inflationFee)
*
* This reduces position sizes to offset increase in supply due to fee collection.
*
* @param _setToken SetToken instance
* @param _inflationFee Fee inflation rate
*/
function _editPositionMultiplier(ISetToken _setToken, uint256 _inflationFee) internal {
int256 currentMultipler = _setToken.positionMultiplier();
int256 newMultiplier = currentMultipler.preciseMul(
PreciseUnitMath.preciseUnit().sub(_inflationFee).toInt256()
);
_setToken.editPositionMultiplier(newMultiplier);
}
function _feeRecipient(ISetToken _set) internal view returns (address) {
return feeStates[_set].feeRecipient;
}
function _lastStreamingFeeTimestamp(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].lastStreamingFeeTimestamp;
}
function _maxStreamingFeePercentage(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].maxStreamingFeePercentage;
}
function _streamingFeePercentage(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].streamingFeePercentage;
}
} | /**
* @title StreamingFeeModule
* @author Set Protocol
*
* Smart contract that accrues streaming fees for Set managers. Streaming fees are denominated as percent
* per year and realized as Set inflation rewarded to the manager.
*/ | NatSpecMultiLine | initialize | function initialize(ISetToken _setToken, FeeState memory _settings)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
require(_settings.feeRecipient != address(0), "Fee Recipient must be non-zero address.");
require(
_settings.maxStreamingFeePercentage < PreciseUnitMath.preciseUnit(),
"Max fee must be < 100%."
);
require(
_settings.streamingFeePercentage <= _settings.maxStreamingFeePercentage,
"Fee must be <= max."
);
// solhint-disable-next-line not-rely-on-time
_settings.lastStreamingFeeTimestamp = block.timestamp;
feeStates[_setToken] = _settings;
_setToken.initializeModule();
}
| /**
* SET MANAGER ONLY. Initialize module with SetToken and set the fee state for the SetToken. Passed
* _settings will have lastStreamingFeeTimestamp over-written.
*
* @param _setToken Address of SetToken
* @param _settings FeeState struct defining fee parameters
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | None | {
"func_code_index": [
2894,
3595
]
} | 1,475 |
|
StreamingFeeModule | contracts/protocol/modules/StreamingFeeModule.sol | 0xa840939edafa7641cfc7ac1e337e322190ac95ff | Solidity | StreamingFeeModule | contract StreamingFeeModule is ModuleBase, ReentrancyGuard {
using SafeMath for uint256;
using PreciseUnitMath for uint256;
using SafeCast for uint256;
using SignedSafeMath for int256;
using PreciseUnitMath for int256;
using SafeCast for int256;
/* ============ Structs ============ */
struct FeeState {
address feeRecipient; // Address to accrue fees to
uint256 maxStreamingFeePercentage; // Max streaming fee maanager commits to using (1% = 1e16, 100% = 1e18)
uint256 streamingFeePercentage; // Percent of Set accruing to manager annually (1% = 1e16, 100% = 1e18)
uint256 lastStreamingFeeTimestamp; // Timestamp last streaming fee was accrued
}
/* ============ Events ============ */
event FeeActualized(address indexed _setToken, uint256 _managerFee, uint256 _protocolFee);
event StreamingFeeUpdated(address indexed _setToken, uint256 _newStreamingFee);
event FeeRecipientUpdated(address indexed _setToken, address _newFeeRecipient);
/* ============ Constants ============ */
uint256 private constant ONE_YEAR_IN_SECONDS = 365.25 days;
uint256 private constant PROTOCOL_STREAMING_FEE_INDEX = 0;
/* ============ State Variables ============ */
mapping(ISetToken => FeeState) public feeStates;
/* ============ Constructor ============ */
// solhint-disable-next-line no-empty-blocks
constructor(IController _controller) ModuleBase(_controller) {}
/* ============ External Functions ============ */
/*
* Calculates total inflation percentage then mints new Sets to the fee recipient. Position units are
* then adjusted down (in magnitude) in order to ensure full collateralization. Callable by anyone.
*
* @param _setToken Address of SetToken
*/
function accrueFee(ISetToken _setToken)
public
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
uint256 managerFee;
uint256 protocolFee;
if (_streamingFeePercentage(_setToken) > 0) {
uint256 inflationFeePercentage = _calculateStreamingFee(_setToken);
// Calculate incentiveFee inflation
uint256 feeQuantity = _calculateStreamingFeeInflation(_setToken, inflationFeePercentage);
// Mint new Sets to manager and protocol
(managerFee, protocolFee) = _mintManagerAndProtocolFee(_setToken, feeQuantity);
_editPositionMultiplier(_setToken, inflationFeePercentage);
}
// solhint-disable-next-line not-rely-on-time
feeStates[_setToken].lastStreamingFeeTimestamp = block.timestamp;
emit FeeActualized(address(_setToken), managerFee, protocolFee);
}
/**
* SET MANAGER ONLY. Initialize module with SetToken and set the fee state for the SetToken. Passed
* _settings will have lastStreamingFeeTimestamp over-written.
*
* @param _setToken Address of SetToken
* @param _settings FeeState struct defining fee parameters
*/
function initialize(ISetToken _setToken, FeeState memory _settings)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
require(_settings.feeRecipient != address(0), "Fee Recipient must be non-zero address.");
require(
_settings.maxStreamingFeePercentage < PreciseUnitMath.preciseUnit(),
"Max fee must be < 100%."
);
require(
_settings.streamingFeePercentage <= _settings.maxStreamingFeePercentage,
"Fee must be <= max."
);
// solhint-disable-next-line not-rely-on-time
_settings.lastStreamingFeeTimestamp = block.timestamp;
feeStates[_setToken] = _settings;
_setToken.initializeModule();
}
/**
* Removes this module from the SetToken, via call by the SetToken. Manager's feeState is deleted. Fees
* are not accrued in case reason for removing module is related to fee accrual.
*/
function removeModule() external override {
delete feeStates[ISetToken(msg.sender)];
}
/*
* Set new streaming fee. Fees accrue at current rate then new rate is set.
* Fees are accrued to prevent the manager from unfairly accruing a larger percentage.
*
* @param _setToken Address of SetToken
* @param _newFee New streaming fee 18 decimal precision
*/
function updateStreamingFee(ISetToken _setToken, uint256 _newFee)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFee < _maxStreamingFeePercentage(_setToken), "Fee must be less than max");
accrueFee(_setToken);
feeStates[_setToken].streamingFeePercentage = _newFee;
emit StreamingFeeUpdated(address(_setToken), _newFee);
}
/*
* Set new fee recipient.
*
* @param _setToken Address of SetToken
* @param _newFeeRecipient New fee recipient
*/
function updateFeeRecipient(ISetToken _setToken, address _newFeeRecipient)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFeeRecipient != address(0), "Fee Recipient must be non-zero address.");
feeStates[_setToken].feeRecipient = _newFeeRecipient;
emit FeeRecipientUpdated(address(_setToken), _newFeeRecipient);
}
/*
* Calculates total inflation percentage in order to accrue fees to manager.
*
* @param _setToken Address of SetToken
* @return uint256 Percent inflation of supply
*/
function getFee(ISetToken _setToken) external view returns (uint256) {
return _calculateStreamingFee(_setToken);
}
/* ============ Internal Functions ============ */
/**
* Calculates streaming fee by multiplying streamingFeePercentage by the elapsed amount of time since the last fee
* was collected divided by one year in seconds, since the fee is a yearly fee.
*
* @param _setToken Address of Set to have feeState updated
* @return uint256 Streaming fee denominated in percentage of totalSupply
*/
function _calculateStreamingFee(ISetToken _setToken) internal view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
uint256 timeSinceLastFee = block.timestamp.sub(_lastStreamingFeeTimestamp(_setToken));
// Streaming fee is streaming fee times years since last fee
return timeSinceLastFee.mul(_streamingFeePercentage(_setToken)).div(ONE_YEAR_IN_SECONDS);
}
/**
* Returns the new incentive fee denominated in the number of SetTokens to mint. The calculation for the fee involves
* implying mint quantity so that the feeRecipient owns the fee percentage of the entire supply of the Set.
*
* The formula to solve for fee is:
* (feeQuantity / feeQuantity) + totalSupply = fee / scaleFactor
*
* The simplified formula utilized below is:
* feeQuantity = fee * totalSupply / (scaleFactor - fee)
*
* @param _setToken SetToken instance
* @param _feePercentage Fee levied to feeRecipient
* @return uint256 New RebalancingSet issue quantity
*/
function _calculateStreamingFeeInflation(ISetToken _setToken, uint256 _feePercentage)
internal
view
returns (uint256)
{
uint256 totalSupply = _setToken.totalSupply();
// fee * totalSupply
uint256 a = _feePercentage.mul(totalSupply);
// ScaleFactor (10e18) - fee
uint256 b = PreciseUnitMath.preciseUnit().sub(_feePercentage);
return a.div(b);
}
/**
* Mints sets to both the manager and the protocol. Protocol takes a percentage fee of the total amount of Sets
* minted to manager.
*
* @param _setToken SetToken instance
* @param _feeQuantity Amount of Sets to be minted as fees
* @return uint256 Amount of Sets accrued to manager as fee
* @return uint256 Amount of Sets accrued to protocol as fee
*/
function _mintManagerAndProtocolFee(ISetToken _setToken, uint256 _feeQuantity)
internal
returns (uint256, uint256)
{
address protocolFeeRecipient = controller.feeRecipient();
uint256 protocolFee = controller.getModuleFee(address(this), PROTOCOL_STREAMING_FEE_INDEX);
uint256 protocolFeeAmount = _feeQuantity.preciseMul(protocolFee);
uint256 managerFeeAmount = _feeQuantity.sub(protocolFeeAmount);
_setToken.mint(_feeRecipient(_setToken), managerFeeAmount);
if (protocolFeeAmount > 0) {
_setToken.mint(protocolFeeRecipient, protocolFeeAmount);
}
return (managerFeeAmount, protocolFeeAmount);
}
/**
* Calculates new position multiplier according to following formula:
*
* newMultiplier = oldMultiplier * (1-inflationFee)
*
* This reduces position sizes to offset increase in supply due to fee collection.
*
* @param _setToken SetToken instance
* @param _inflationFee Fee inflation rate
*/
function _editPositionMultiplier(ISetToken _setToken, uint256 _inflationFee) internal {
int256 currentMultipler = _setToken.positionMultiplier();
int256 newMultiplier = currentMultipler.preciseMul(
PreciseUnitMath.preciseUnit().sub(_inflationFee).toInt256()
);
_setToken.editPositionMultiplier(newMultiplier);
}
function _feeRecipient(ISetToken _set) internal view returns (address) {
return feeStates[_set].feeRecipient;
}
function _lastStreamingFeeTimestamp(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].lastStreamingFeeTimestamp;
}
function _maxStreamingFeePercentage(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].maxStreamingFeePercentage;
}
function _streamingFeePercentage(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].streamingFeePercentage;
}
} | /**
* @title StreamingFeeModule
* @author Set Protocol
*
* Smart contract that accrues streaming fees for Set managers. Streaming fees are denominated as percent
* per year and realized as Set inflation rewarded to the manager.
*/ | NatSpecMultiLine | removeModule | function removeModule() external override {
delete feeStates[ISetToken(msg.sender)];
}
| /**
* Removes this module from the SetToken, via call by the SetToken. Manager's feeState is deleted. Fees
* are not accrued in case reason for removing module is related to fee accrual.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | None | {
"func_code_index": [
3798,
3892
]
} | 1,476 |
|
StreamingFeeModule | contracts/protocol/modules/StreamingFeeModule.sol | 0xa840939edafa7641cfc7ac1e337e322190ac95ff | Solidity | StreamingFeeModule | contract StreamingFeeModule is ModuleBase, ReentrancyGuard {
using SafeMath for uint256;
using PreciseUnitMath for uint256;
using SafeCast for uint256;
using SignedSafeMath for int256;
using PreciseUnitMath for int256;
using SafeCast for int256;
/* ============ Structs ============ */
struct FeeState {
address feeRecipient; // Address to accrue fees to
uint256 maxStreamingFeePercentage; // Max streaming fee maanager commits to using (1% = 1e16, 100% = 1e18)
uint256 streamingFeePercentage; // Percent of Set accruing to manager annually (1% = 1e16, 100% = 1e18)
uint256 lastStreamingFeeTimestamp; // Timestamp last streaming fee was accrued
}
/* ============ Events ============ */
event FeeActualized(address indexed _setToken, uint256 _managerFee, uint256 _protocolFee);
event StreamingFeeUpdated(address indexed _setToken, uint256 _newStreamingFee);
event FeeRecipientUpdated(address indexed _setToken, address _newFeeRecipient);
/* ============ Constants ============ */
uint256 private constant ONE_YEAR_IN_SECONDS = 365.25 days;
uint256 private constant PROTOCOL_STREAMING_FEE_INDEX = 0;
/* ============ State Variables ============ */
mapping(ISetToken => FeeState) public feeStates;
/* ============ Constructor ============ */
// solhint-disable-next-line no-empty-blocks
constructor(IController _controller) ModuleBase(_controller) {}
/* ============ External Functions ============ */
/*
* Calculates total inflation percentage then mints new Sets to the fee recipient. Position units are
* then adjusted down (in magnitude) in order to ensure full collateralization. Callable by anyone.
*
* @param _setToken Address of SetToken
*/
function accrueFee(ISetToken _setToken)
public
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
uint256 managerFee;
uint256 protocolFee;
if (_streamingFeePercentage(_setToken) > 0) {
uint256 inflationFeePercentage = _calculateStreamingFee(_setToken);
// Calculate incentiveFee inflation
uint256 feeQuantity = _calculateStreamingFeeInflation(_setToken, inflationFeePercentage);
// Mint new Sets to manager and protocol
(managerFee, protocolFee) = _mintManagerAndProtocolFee(_setToken, feeQuantity);
_editPositionMultiplier(_setToken, inflationFeePercentage);
}
// solhint-disable-next-line not-rely-on-time
feeStates[_setToken].lastStreamingFeeTimestamp = block.timestamp;
emit FeeActualized(address(_setToken), managerFee, protocolFee);
}
/**
* SET MANAGER ONLY. Initialize module with SetToken and set the fee state for the SetToken. Passed
* _settings will have lastStreamingFeeTimestamp over-written.
*
* @param _setToken Address of SetToken
* @param _settings FeeState struct defining fee parameters
*/
function initialize(ISetToken _setToken, FeeState memory _settings)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
require(_settings.feeRecipient != address(0), "Fee Recipient must be non-zero address.");
require(
_settings.maxStreamingFeePercentage < PreciseUnitMath.preciseUnit(),
"Max fee must be < 100%."
);
require(
_settings.streamingFeePercentage <= _settings.maxStreamingFeePercentage,
"Fee must be <= max."
);
// solhint-disable-next-line not-rely-on-time
_settings.lastStreamingFeeTimestamp = block.timestamp;
feeStates[_setToken] = _settings;
_setToken.initializeModule();
}
/**
* Removes this module from the SetToken, via call by the SetToken. Manager's feeState is deleted. Fees
* are not accrued in case reason for removing module is related to fee accrual.
*/
function removeModule() external override {
delete feeStates[ISetToken(msg.sender)];
}
/*
* Set new streaming fee. Fees accrue at current rate then new rate is set.
* Fees are accrued to prevent the manager from unfairly accruing a larger percentage.
*
* @param _setToken Address of SetToken
* @param _newFee New streaming fee 18 decimal precision
*/
function updateStreamingFee(ISetToken _setToken, uint256 _newFee)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFee < _maxStreamingFeePercentage(_setToken), "Fee must be less than max");
accrueFee(_setToken);
feeStates[_setToken].streamingFeePercentage = _newFee;
emit StreamingFeeUpdated(address(_setToken), _newFee);
}
/*
* Set new fee recipient.
*
* @param _setToken Address of SetToken
* @param _newFeeRecipient New fee recipient
*/
function updateFeeRecipient(ISetToken _setToken, address _newFeeRecipient)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFeeRecipient != address(0), "Fee Recipient must be non-zero address.");
feeStates[_setToken].feeRecipient = _newFeeRecipient;
emit FeeRecipientUpdated(address(_setToken), _newFeeRecipient);
}
/*
* Calculates total inflation percentage in order to accrue fees to manager.
*
* @param _setToken Address of SetToken
* @return uint256 Percent inflation of supply
*/
function getFee(ISetToken _setToken) external view returns (uint256) {
return _calculateStreamingFee(_setToken);
}
/* ============ Internal Functions ============ */
/**
* Calculates streaming fee by multiplying streamingFeePercentage by the elapsed amount of time since the last fee
* was collected divided by one year in seconds, since the fee is a yearly fee.
*
* @param _setToken Address of Set to have feeState updated
* @return uint256 Streaming fee denominated in percentage of totalSupply
*/
function _calculateStreamingFee(ISetToken _setToken) internal view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
uint256 timeSinceLastFee = block.timestamp.sub(_lastStreamingFeeTimestamp(_setToken));
// Streaming fee is streaming fee times years since last fee
return timeSinceLastFee.mul(_streamingFeePercentage(_setToken)).div(ONE_YEAR_IN_SECONDS);
}
/**
* Returns the new incentive fee denominated in the number of SetTokens to mint. The calculation for the fee involves
* implying mint quantity so that the feeRecipient owns the fee percentage of the entire supply of the Set.
*
* The formula to solve for fee is:
* (feeQuantity / feeQuantity) + totalSupply = fee / scaleFactor
*
* The simplified formula utilized below is:
* feeQuantity = fee * totalSupply / (scaleFactor - fee)
*
* @param _setToken SetToken instance
* @param _feePercentage Fee levied to feeRecipient
* @return uint256 New RebalancingSet issue quantity
*/
function _calculateStreamingFeeInflation(ISetToken _setToken, uint256 _feePercentage)
internal
view
returns (uint256)
{
uint256 totalSupply = _setToken.totalSupply();
// fee * totalSupply
uint256 a = _feePercentage.mul(totalSupply);
// ScaleFactor (10e18) - fee
uint256 b = PreciseUnitMath.preciseUnit().sub(_feePercentage);
return a.div(b);
}
/**
* Mints sets to both the manager and the protocol. Protocol takes a percentage fee of the total amount of Sets
* minted to manager.
*
* @param _setToken SetToken instance
* @param _feeQuantity Amount of Sets to be minted as fees
* @return uint256 Amount of Sets accrued to manager as fee
* @return uint256 Amount of Sets accrued to protocol as fee
*/
function _mintManagerAndProtocolFee(ISetToken _setToken, uint256 _feeQuantity)
internal
returns (uint256, uint256)
{
address protocolFeeRecipient = controller.feeRecipient();
uint256 protocolFee = controller.getModuleFee(address(this), PROTOCOL_STREAMING_FEE_INDEX);
uint256 protocolFeeAmount = _feeQuantity.preciseMul(protocolFee);
uint256 managerFeeAmount = _feeQuantity.sub(protocolFeeAmount);
_setToken.mint(_feeRecipient(_setToken), managerFeeAmount);
if (protocolFeeAmount > 0) {
_setToken.mint(protocolFeeRecipient, protocolFeeAmount);
}
return (managerFeeAmount, protocolFeeAmount);
}
/**
* Calculates new position multiplier according to following formula:
*
* newMultiplier = oldMultiplier * (1-inflationFee)
*
* This reduces position sizes to offset increase in supply due to fee collection.
*
* @param _setToken SetToken instance
* @param _inflationFee Fee inflation rate
*/
function _editPositionMultiplier(ISetToken _setToken, uint256 _inflationFee) internal {
int256 currentMultipler = _setToken.positionMultiplier();
int256 newMultiplier = currentMultipler.preciseMul(
PreciseUnitMath.preciseUnit().sub(_inflationFee).toInt256()
);
_setToken.editPositionMultiplier(newMultiplier);
}
function _feeRecipient(ISetToken _set) internal view returns (address) {
return feeStates[_set].feeRecipient;
}
function _lastStreamingFeeTimestamp(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].lastStreamingFeeTimestamp;
}
function _maxStreamingFeePercentage(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].maxStreamingFeePercentage;
}
function _streamingFeePercentage(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].streamingFeePercentage;
}
} | /**
* @title StreamingFeeModule
* @author Set Protocol
*
* Smart contract that accrues streaming fees for Set managers. Streaming fees are denominated as percent
* per year and realized as Set inflation rewarded to the manager.
*/ | NatSpecMultiLine | updateStreamingFee | function updateStreamingFee(ISetToken _setToken, uint256 _newFee)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFee < _maxStreamingFeePercentage(_setToken), "Fee must be less than max");
accrueFee(_setToken);
feeStates[_setToken].streamingFeePercentage = _newFee;
emit StreamingFeeUpdated(address(_setToken), _newFee);
}
| /*
* Set new streaming fee. Fees accrue at current rate then new rate is set.
* Fees are accrued to prevent the manager from unfairly accruing a larger percentage.
*
* @param _setToken Address of SetToken
* @param _newFee New streaming fee 18 decimal precision
*/ | Comment | v0.7.6+commit.7338295f | None | {
"func_code_index": [
4192,
4601
]
} | 1,477 |
|
StreamingFeeModule | contracts/protocol/modules/StreamingFeeModule.sol | 0xa840939edafa7641cfc7ac1e337e322190ac95ff | Solidity | StreamingFeeModule | contract StreamingFeeModule is ModuleBase, ReentrancyGuard {
using SafeMath for uint256;
using PreciseUnitMath for uint256;
using SafeCast for uint256;
using SignedSafeMath for int256;
using PreciseUnitMath for int256;
using SafeCast for int256;
/* ============ Structs ============ */
struct FeeState {
address feeRecipient; // Address to accrue fees to
uint256 maxStreamingFeePercentage; // Max streaming fee maanager commits to using (1% = 1e16, 100% = 1e18)
uint256 streamingFeePercentage; // Percent of Set accruing to manager annually (1% = 1e16, 100% = 1e18)
uint256 lastStreamingFeeTimestamp; // Timestamp last streaming fee was accrued
}
/* ============ Events ============ */
event FeeActualized(address indexed _setToken, uint256 _managerFee, uint256 _protocolFee);
event StreamingFeeUpdated(address indexed _setToken, uint256 _newStreamingFee);
event FeeRecipientUpdated(address indexed _setToken, address _newFeeRecipient);
/* ============ Constants ============ */
uint256 private constant ONE_YEAR_IN_SECONDS = 365.25 days;
uint256 private constant PROTOCOL_STREAMING_FEE_INDEX = 0;
/* ============ State Variables ============ */
mapping(ISetToken => FeeState) public feeStates;
/* ============ Constructor ============ */
// solhint-disable-next-line no-empty-blocks
constructor(IController _controller) ModuleBase(_controller) {}
/* ============ External Functions ============ */
/*
* Calculates total inflation percentage then mints new Sets to the fee recipient. Position units are
* then adjusted down (in magnitude) in order to ensure full collateralization. Callable by anyone.
*
* @param _setToken Address of SetToken
*/
function accrueFee(ISetToken _setToken)
public
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
uint256 managerFee;
uint256 protocolFee;
if (_streamingFeePercentage(_setToken) > 0) {
uint256 inflationFeePercentage = _calculateStreamingFee(_setToken);
// Calculate incentiveFee inflation
uint256 feeQuantity = _calculateStreamingFeeInflation(_setToken, inflationFeePercentage);
// Mint new Sets to manager and protocol
(managerFee, protocolFee) = _mintManagerAndProtocolFee(_setToken, feeQuantity);
_editPositionMultiplier(_setToken, inflationFeePercentage);
}
// solhint-disable-next-line not-rely-on-time
feeStates[_setToken].lastStreamingFeeTimestamp = block.timestamp;
emit FeeActualized(address(_setToken), managerFee, protocolFee);
}
/**
* SET MANAGER ONLY. Initialize module with SetToken and set the fee state for the SetToken. Passed
* _settings will have lastStreamingFeeTimestamp over-written.
*
* @param _setToken Address of SetToken
* @param _settings FeeState struct defining fee parameters
*/
function initialize(ISetToken _setToken, FeeState memory _settings)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
require(_settings.feeRecipient != address(0), "Fee Recipient must be non-zero address.");
require(
_settings.maxStreamingFeePercentage < PreciseUnitMath.preciseUnit(),
"Max fee must be < 100%."
);
require(
_settings.streamingFeePercentage <= _settings.maxStreamingFeePercentage,
"Fee must be <= max."
);
// solhint-disable-next-line not-rely-on-time
_settings.lastStreamingFeeTimestamp = block.timestamp;
feeStates[_setToken] = _settings;
_setToken.initializeModule();
}
/**
* Removes this module from the SetToken, via call by the SetToken. Manager's feeState is deleted. Fees
* are not accrued in case reason for removing module is related to fee accrual.
*/
function removeModule() external override {
delete feeStates[ISetToken(msg.sender)];
}
/*
* Set new streaming fee. Fees accrue at current rate then new rate is set.
* Fees are accrued to prevent the manager from unfairly accruing a larger percentage.
*
* @param _setToken Address of SetToken
* @param _newFee New streaming fee 18 decimal precision
*/
function updateStreamingFee(ISetToken _setToken, uint256 _newFee)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFee < _maxStreamingFeePercentage(_setToken), "Fee must be less than max");
accrueFee(_setToken);
feeStates[_setToken].streamingFeePercentage = _newFee;
emit StreamingFeeUpdated(address(_setToken), _newFee);
}
/*
* Set new fee recipient.
*
* @param _setToken Address of SetToken
* @param _newFeeRecipient New fee recipient
*/
function updateFeeRecipient(ISetToken _setToken, address _newFeeRecipient)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFeeRecipient != address(0), "Fee Recipient must be non-zero address.");
feeStates[_setToken].feeRecipient = _newFeeRecipient;
emit FeeRecipientUpdated(address(_setToken), _newFeeRecipient);
}
/*
* Calculates total inflation percentage in order to accrue fees to manager.
*
* @param _setToken Address of SetToken
* @return uint256 Percent inflation of supply
*/
function getFee(ISetToken _setToken) external view returns (uint256) {
return _calculateStreamingFee(_setToken);
}
/* ============ Internal Functions ============ */
/**
* Calculates streaming fee by multiplying streamingFeePercentage by the elapsed amount of time since the last fee
* was collected divided by one year in seconds, since the fee is a yearly fee.
*
* @param _setToken Address of Set to have feeState updated
* @return uint256 Streaming fee denominated in percentage of totalSupply
*/
function _calculateStreamingFee(ISetToken _setToken) internal view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
uint256 timeSinceLastFee = block.timestamp.sub(_lastStreamingFeeTimestamp(_setToken));
// Streaming fee is streaming fee times years since last fee
return timeSinceLastFee.mul(_streamingFeePercentage(_setToken)).div(ONE_YEAR_IN_SECONDS);
}
/**
* Returns the new incentive fee denominated in the number of SetTokens to mint. The calculation for the fee involves
* implying mint quantity so that the feeRecipient owns the fee percentage of the entire supply of the Set.
*
* The formula to solve for fee is:
* (feeQuantity / feeQuantity) + totalSupply = fee / scaleFactor
*
* The simplified formula utilized below is:
* feeQuantity = fee * totalSupply / (scaleFactor - fee)
*
* @param _setToken SetToken instance
* @param _feePercentage Fee levied to feeRecipient
* @return uint256 New RebalancingSet issue quantity
*/
function _calculateStreamingFeeInflation(ISetToken _setToken, uint256 _feePercentage)
internal
view
returns (uint256)
{
uint256 totalSupply = _setToken.totalSupply();
// fee * totalSupply
uint256 a = _feePercentage.mul(totalSupply);
// ScaleFactor (10e18) - fee
uint256 b = PreciseUnitMath.preciseUnit().sub(_feePercentage);
return a.div(b);
}
/**
* Mints sets to both the manager and the protocol. Protocol takes a percentage fee of the total amount of Sets
* minted to manager.
*
* @param _setToken SetToken instance
* @param _feeQuantity Amount of Sets to be minted as fees
* @return uint256 Amount of Sets accrued to manager as fee
* @return uint256 Amount of Sets accrued to protocol as fee
*/
function _mintManagerAndProtocolFee(ISetToken _setToken, uint256 _feeQuantity)
internal
returns (uint256, uint256)
{
address protocolFeeRecipient = controller.feeRecipient();
uint256 protocolFee = controller.getModuleFee(address(this), PROTOCOL_STREAMING_FEE_INDEX);
uint256 protocolFeeAmount = _feeQuantity.preciseMul(protocolFee);
uint256 managerFeeAmount = _feeQuantity.sub(protocolFeeAmount);
_setToken.mint(_feeRecipient(_setToken), managerFeeAmount);
if (protocolFeeAmount > 0) {
_setToken.mint(protocolFeeRecipient, protocolFeeAmount);
}
return (managerFeeAmount, protocolFeeAmount);
}
/**
* Calculates new position multiplier according to following formula:
*
* newMultiplier = oldMultiplier * (1-inflationFee)
*
* This reduces position sizes to offset increase in supply due to fee collection.
*
* @param _setToken SetToken instance
* @param _inflationFee Fee inflation rate
*/
function _editPositionMultiplier(ISetToken _setToken, uint256 _inflationFee) internal {
int256 currentMultipler = _setToken.positionMultiplier();
int256 newMultiplier = currentMultipler.preciseMul(
PreciseUnitMath.preciseUnit().sub(_inflationFee).toInt256()
);
_setToken.editPositionMultiplier(newMultiplier);
}
function _feeRecipient(ISetToken _set) internal view returns (address) {
return feeStates[_set].feeRecipient;
}
function _lastStreamingFeeTimestamp(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].lastStreamingFeeTimestamp;
}
function _maxStreamingFeePercentage(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].maxStreamingFeePercentage;
}
function _streamingFeePercentage(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].streamingFeePercentage;
}
} | /**
* @title StreamingFeeModule
* @author Set Protocol
*
* Smart contract that accrues streaming fees for Set managers. Streaming fees are denominated as percent
* per year and realized as Set inflation rewarded to the manager.
*/ | NatSpecMultiLine | updateFeeRecipient | function updateFeeRecipient(ISetToken _setToken, address _newFeeRecipient)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFeeRecipient != address(0), "Fee Recipient must be non-zero address.");
feeStates[_setToken].feeRecipient = _newFeeRecipient;
emit FeeRecipientUpdated(address(_setToken), _newFeeRecipient);
}
| /*
* Set new fee recipient.
*
* @param _setToken Address of SetToken
* @param _newFeeRecipient New fee recipient
*/ | Comment | v0.7.6+commit.7338295f | None | {
"func_code_index": [
4753,
5150
]
} | 1,478 |
|
StreamingFeeModule | contracts/protocol/modules/StreamingFeeModule.sol | 0xa840939edafa7641cfc7ac1e337e322190ac95ff | Solidity | StreamingFeeModule | contract StreamingFeeModule is ModuleBase, ReentrancyGuard {
using SafeMath for uint256;
using PreciseUnitMath for uint256;
using SafeCast for uint256;
using SignedSafeMath for int256;
using PreciseUnitMath for int256;
using SafeCast for int256;
/* ============ Structs ============ */
struct FeeState {
address feeRecipient; // Address to accrue fees to
uint256 maxStreamingFeePercentage; // Max streaming fee maanager commits to using (1% = 1e16, 100% = 1e18)
uint256 streamingFeePercentage; // Percent of Set accruing to manager annually (1% = 1e16, 100% = 1e18)
uint256 lastStreamingFeeTimestamp; // Timestamp last streaming fee was accrued
}
/* ============ Events ============ */
event FeeActualized(address indexed _setToken, uint256 _managerFee, uint256 _protocolFee);
event StreamingFeeUpdated(address indexed _setToken, uint256 _newStreamingFee);
event FeeRecipientUpdated(address indexed _setToken, address _newFeeRecipient);
/* ============ Constants ============ */
uint256 private constant ONE_YEAR_IN_SECONDS = 365.25 days;
uint256 private constant PROTOCOL_STREAMING_FEE_INDEX = 0;
/* ============ State Variables ============ */
mapping(ISetToken => FeeState) public feeStates;
/* ============ Constructor ============ */
// solhint-disable-next-line no-empty-blocks
constructor(IController _controller) ModuleBase(_controller) {}
/* ============ External Functions ============ */
/*
* Calculates total inflation percentage then mints new Sets to the fee recipient. Position units are
* then adjusted down (in magnitude) in order to ensure full collateralization. Callable by anyone.
*
* @param _setToken Address of SetToken
*/
function accrueFee(ISetToken _setToken)
public
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
uint256 managerFee;
uint256 protocolFee;
if (_streamingFeePercentage(_setToken) > 0) {
uint256 inflationFeePercentage = _calculateStreamingFee(_setToken);
// Calculate incentiveFee inflation
uint256 feeQuantity = _calculateStreamingFeeInflation(_setToken, inflationFeePercentage);
// Mint new Sets to manager and protocol
(managerFee, protocolFee) = _mintManagerAndProtocolFee(_setToken, feeQuantity);
_editPositionMultiplier(_setToken, inflationFeePercentage);
}
// solhint-disable-next-line not-rely-on-time
feeStates[_setToken].lastStreamingFeeTimestamp = block.timestamp;
emit FeeActualized(address(_setToken), managerFee, protocolFee);
}
/**
* SET MANAGER ONLY. Initialize module with SetToken and set the fee state for the SetToken. Passed
* _settings will have lastStreamingFeeTimestamp over-written.
*
* @param _setToken Address of SetToken
* @param _settings FeeState struct defining fee parameters
*/
function initialize(ISetToken _setToken, FeeState memory _settings)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
require(_settings.feeRecipient != address(0), "Fee Recipient must be non-zero address.");
require(
_settings.maxStreamingFeePercentage < PreciseUnitMath.preciseUnit(),
"Max fee must be < 100%."
);
require(
_settings.streamingFeePercentage <= _settings.maxStreamingFeePercentage,
"Fee must be <= max."
);
// solhint-disable-next-line not-rely-on-time
_settings.lastStreamingFeeTimestamp = block.timestamp;
feeStates[_setToken] = _settings;
_setToken.initializeModule();
}
/**
* Removes this module from the SetToken, via call by the SetToken. Manager's feeState is deleted. Fees
* are not accrued in case reason for removing module is related to fee accrual.
*/
function removeModule() external override {
delete feeStates[ISetToken(msg.sender)];
}
/*
* Set new streaming fee. Fees accrue at current rate then new rate is set.
* Fees are accrued to prevent the manager from unfairly accruing a larger percentage.
*
* @param _setToken Address of SetToken
* @param _newFee New streaming fee 18 decimal precision
*/
function updateStreamingFee(ISetToken _setToken, uint256 _newFee)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFee < _maxStreamingFeePercentage(_setToken), "Fee must be less than max");
accrueFee(_setToken);
feeStates[_setToken].streamingFeePercentage = _newFee;
emit StreamingFeeUpdated(address(_setToken), _newFee);
}
/*
* Set new fee recipient.
*
* @param _setToken Address of SetToken
* @param _newFeeRecipient New fee recipient
*/
function updateFeeRecipient(ISetToken _setToken, address _newFeeRecipient)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFeeRecipient != address(0), "Fee Recipient must be non-zero address.");
feeStates[_setToken].feeRecipient = _newFeeRecipient;
emit FeeRecipientUpdated(address(_setToken), _newFeeRecipient);
}
/*
* Calculates total inflation percentage in order to accrue fees to manager.
*
* @param _setToken Address of SetToken
* @return uint256 Percent inflation of supply
*/
function getFee(ISetToken _setToken) external view returns (uint256) {
return _calculateStreamingFee(_setToken);
}
/* ============ Internal Functions ============ */
/**
* Calculates streaming fee by multiplying streamingFeePercentage by the elapsed amount of time since the last fee
* was collected divided by one year in seconds, since the fee is a yearly fee.
*
* @param _setToken Address of Set to have feeState updated
* @return uint256 Streaming fee denominated in percentage of totalSupply
*/
function _calculateStreamingFee(ISetToken _setToken) internal view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
uint256 timeSinceLastFee = block.timestamp.sub(_lastStreamingFeeTimestamp(_setToken));
// Streaming fee is streaming fee times years since last fee
return timeSinceLastFee.mul(_streamingFeePercentage(_setToken)).div(ONE_YEAR_IN_SECONDS);
}
/**
* Returns the new incentive fee denominated in the number of SetTokens to mint. The calculation for the fee involves
* implying mint quantity so that the feeRecipient owns the fee percentage of the entire supply of the Set.
*
* The formula to solve for fee is:
* (feeQuantity / feeQuantity) + totalSupply = fee / scaleFactor
*
* The simplified formula utilized below is:
* feeQuantity = fee * totalSupply / (scaleFactor - fee)
*
* @param _setToken SetToken instance
* @param _feePercentage Fee levied to feeRecipient
* @return uint256 New RebalancingSet issue quantity
*/
function _calculateStreamingFeeInflation(ISetToken _setToken, uint256 _feePercentage)
internal
view
returns (uint256)
{
uint256 totalSupply = _setToken.totalSupply();
// fee * totalSupply
uint256 a = _feePercentage.mul(totalSupply);
// ScaleFactor (10e18) - fee
uint256 b = PreciseUnitMath.preciseUnit().sub(_feePercentage);
return a.div(b);
}
/**
* Mints sets to both the manager and the protocol. Protocol takes a percentage fee of the total amount of Sets
* minted to manager.
*
* @param _setToken SetToken instance
* @param _feeQuantity Amount of Sets to be minted as fees
* @return uint256 Amount of Sets accrued to manager as fee
* @return uint256 Amount of Sets accrued to protocol as fee
*/
function _mintManagerAndProtocolFee(ISetToken _setToken, uint256 _feeQuantity)
internal
returns (uint256, uint256)
{
address protocolFeeRecipient = controller.feeRecipient();
uint256 protocolFee = controller.getModuleFee(address(this), PROTOCOL_STREAMING_FEE_INDEX);
uint256 protocolFeeAmount = _feeQuantity.preciseMul(protocolFee);
uint256 managerFeeAmount = _feeQuantity.sub(protocolFeeAmount);
_setToken.mint(_feeRecipient(_setToken), managerFeeAmount);
if (protocolFeeAmount > 0) {
_setToken.mint(protocolFeeRecipient, protocolFeeAmount);
}
return (managerFeeAmount, protocolFeeAmount);
}
/**
* Calculates new position multiplier according to following formula:
*
* newMultiplier = oldMultiplier * (1-inflationFee)
*
* This reduces position sizes to offset increase in supply due to fee collection.
*
* @param _setToken SetToken instance
* @param _inflationFee Fee inflation rate
*/
function _editPositionMultiplier(ISetToken _setToken, uint256 _inflationFee) internal {
int256 currentMultipler = _setToken.positionMultiplier();
int256 newMultiplier = currentMultipler.preciseMul(
PreciseUnitMath.preciseUnit().sub(_inflationFee).toInt256()
);
_setToken.editPositionMultiplier(newMultiplier);
}
function _feeRecipient(ISetToken _set) internal view returns (address) {
return feeStates[_set].feeRecipient;
}
function _lastStreamingFeeTimestamp(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].lastStreamingFeeTimestamp;
}
function _maxStreamingFeePercentage(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].maxStreamingFeePercentage;
}
function _streamingFeePercentage(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].streamingFeePercentage;
}
} | /**
* @title StreamingFeeModule
* @author Set Protocol
*
* Smart contract that accrues streaming fees for Set managers. Streaming fees are denominated as percent
* per year and realized as Set inflation rewarded to the manager.
*/ | NatSpecMultiLine | getFee | function getFee(ISetToken _setToken) external view returns (uint256) {
return _calculateStreamingFee(_setToken);
}
| /*
* Calculates total inflation percentage in order to accrue fees to manager.
*
* @param _setToken Address of SetToken
* @return uint256 Percent inflation of supply
*/ | Comment | v0.7.6+commit.7338295f | None | {
"func_code_index": [
5351,
5473
]
} | 1,479 |
|
StreamingFeeModule | contracts/protocol/modules/StreamingFeeModule.sol | 0xa840939edafa7641cfc7ac1e337e322190ac95ff | Solidity | StreamingFeeModule | contract StreamingFeeModule is ModuleBase, ReentrancyGuard {
using SafeMath for uint256;
using PreciseUnitMath for uint256;
using SafeCast for uint256;
using SignedSafeMath for int256;
using PreciseUnitMath for int256;
using SafeCast for int256;
/* ============ Structs ============ */
struct FeeState {
address feeRecipient; // Address to accrue fees to
uint256 maxStreamingFeePercentage; // Max streaming fee maanager commits to using (1% = 1e16, 100% = 1e18)
uint256 streamingFeePercentage; // Percent of Set accruing to manager annually (1% = 1e16, 100% = 1e18)
uint256 lastStreamingFeeTimestamp; // Timestamp last streaming fee was accrued
}
/* ============ Events ============ */
event FeeActualized(address indexed _setToken, uint256 _managerFee, uint256 _protocolFee);
event StreamingFeeUpdated(address indexed _setToken, uint256 _newStreamingFee);
event FeeRecipientUpdated(address indexed _setToken, address _newFeeRecipient);
/* ============ Constants ============ */
uint256 private constant ONE_YEAR_IN_SECONDS = 365.25 days;
uint256 private constant PROTOCOL_STREAMING_FEE_INDEX = 0;
/* ============ State Variables ============ */
mapping(ISetToken => FeeState) public feeStates;
/* ============ Constructor ============ */
// solhint-disable-next-line no-empty-blocks
constructor(IController _controller) ModuleBase(_controller) {}
/* ============ External Functions ============ */
/*
* Calculates total inflation percentage then mints new Sets to the fee recipient. Position units are
* then adjusted down (in magnitude) in order to ensure full collateralization. Callable by anyone.
*
* @param _setToken Address of SetToken
*/
function accrueFee(ISetToken _setToken)
public
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
uint256 managerFee;
uint256 protocolFee;
if (_streamingFeePercentage(_setToken) > 0) {
uint256 inflationFeePercentage = _calculateStreamingFee(_setToken);
// Calculate incentiveFee inflation
uint256 feeQuantity = _calculateStreamingFeeInflation(_setToken, inflationFeePercentage);
// Mint new Sets to manager and protocol
(managerFee, protocolFee) = _mintManagerAndProtocolFee(_setToken, feeQuantity);
_editPositionMultiplier(_setToken, inflationFeePercentage);
}
// solhint-disable-next-line not-rely-on-time
feeStates[_setToken].lastStreamingFeeTimestamp = block.timestamp;
emit FeeActualized(address(_setToken), managerFee, protocolFee);
}
/**
* SET MANAGER ONLY. Initialize module with SetToken and set the fee state for the SetToken. Passed
* _settings will have lastStreamingFeeTimestamp over-written.
*
* @param _setToken Address of SetToken
* @param _settings FeeState struct defining fee parameters
*/
function initialize(ISetToken _setToken, FeeState memory _settings)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
require(_settings.feeRecipient != address(0), "Fee Recipient must be non-zero address.");
require(
_settings.maxStreamingFeePercentage < PreciseUnitMath.preciseUnit(),
"Max fee must be < 100%."
);
require(
_settings.streamingFeePercentage <= _settings.maxStreamingFeePercentage,
"Fee must be <= max."
);
// solhint-disable-next-line not-rely-on-time
_settings.lastStreamingFeeTimestamp = block.timestamp;
feeStates[_setToken] = _settings;
_setToken.initializeModule();
}
/**
* Removes this module from the SetToken, via call by the SetToken. Manager's feeState is deleted. Fees
* are not accrued in case reason for removing module is related to fee accrual.
*/
function removeModule() external override {
delete feeStates[ISetToken(msg.sender)];
}
/*
* Set new streaming fee. Fees accrue at current rate then new rate is set.
* Fees are accrued to prevent the manager from unfairly accruing a larger percentage.
*
* @param _setToken Address of SetToken
* @param _newFee New streaming fee 18 decimal precision
*/
function updateStreamingFee(ISetToken _setToken, uint256 _newFee)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFee < _maxStreamingFeePercentage(_setToken), "Fee must be less than max");
accrueFee(_setToken);
feeStates[_setToken].streamingFeePercentage = _newFee;
emit StreamingFeeUpdated(address(_setToken), _newFee);
}
/*
* Set new fee recipient.
*
* @param _setToken Address of SetToken
* @param _newFeeRecipient New fee recipient
*/
function updateFeeRecipient(ISetToken _setToken, address _newFeeRecipient)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFeeRecipient != address(0), "Fee Recipient must be non-zero address.");
feeStates[_setToken].feeRecipient = _newFeeRecipient;
emit FeeRecipientUpdated(address(_setToken), _newFeeRecipient);
}
/*
* Calculates total inflation percentage in order to accrue fees to manager.
*
* @param _setToken Address of SetToken
* @return uint256 Percent inflation of supply
*/
function getFee(ISetToken _setToken) external view returns (uint256) {
return _calculateStreamingFee(_setToken);
}
/* ============ Internal Functions ============ */
/**
* Calculates streaming fee by multiplying streamingFeePercentage by the elapsed amount of time since the last fee
* was collected divided by one year in seconds, since the fee is a yearly fee.
*
* @param _setToken Address of Set to have feeState updated
* @return uint256 Streaming fee denominated in percentage of totalSupply
*/
function _calculateStreamingFee(ISetToken _setToken) internal view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
uint256 timeSinceLastFee = block.timestamp.sub(_lastStreamingFeeTimestamp(_setToken));
// Streaming fee is streaming fee times years since last fee
return timeSinceLastFee.mul(_streamingFeePercentage(_setToken)).div(ONE_YEAR_IN_SECONDS);
}
/**
* Returns the new incentive fee denominated in the number of SetTokens to mint. The calculation for the fee involves
* implying mint quantity so that the feeRecipient owns the fee percentage of the entire supply of the Set.
*
* The formula to solve for fee is:
* (feeQuantity / feeQuantity) + totalSupply = fee / scaleFactor
*
* The simplified formula utilized below is:
* feeQuantity = fee * totalSupply / (scaleFactor - fee)
*
* @param _setToken SetToken instance
* @param _feePercentage Fee levied to feeRecipient
* @return uint256 New RebalancingSet issue quantity
*/
function _calculateStreamingFeeInflation(ISetToken _setToken, uint256 _feePercentage)
internal
view
returns (uint256)
{
uint256 totalSupply = _setToken.totalSupply();
// fee * totalSupply
uint256 a = _feePercentage.mul(totalSupply);
// ScaleFactor (10e18) - fee
uint256 b = PreciseUnitMath.preciseUnit().sub(_feePercentage);
return a.div(b);
}
/**
* Mints sets to both the manager and the protocol. Protocol takes a percentage fee of the total amount of Sets
* minted to manager.
*
* @param _setToken SetToken instance
* @param _feeQuantity Amount of Sets to be minted as fees
* @return uint256 Amount of Sets accrued to manager as fee
* @return uint256 Amount of Sets accrued to protocol as fee
*/
function _mintManagerAndProtocolFee(ISetToken _setToken, uint256 _feeQuantity)
internal
returns (uint256, uint256)
{
address protocolFeeRecipient = controller.feeRecipient();
uint256 protocolFee = controller.getModuleFee(address(this), PROTOCOL_STREAMING_FEE_INDEX);
uint256 protocolFeeAmount = _feeQuantity.preciseMul(protocolFee);
uint256 managerFeeAmount = _feeQuantity.sub(protocolFeeAmount);
_setToken.mint(_feeRecipient(_setToken), managerFeeAmount);
if (protocolFeeAmount > 0) {
_setToken.mint(protocolFeeRecipient, protocolFeeAmount);
}
return (managerFeeAmount, protocolFeeAmount);
}
/**
* Calculates new position multiplier according to following formula:
*
* newMultiplier = oldMultiplier * (1-inflationFee)
*
* This reduces position sizes to offset increase in supply due to fee collection.
*
* @param _setToken SetToken instance
* @param _inflationFee Fee inflation rate
*/
function _editPositionMultiplier(ISetToken _setToken, uint256 _inflationFee) internal {
int256 currentMultipler = _setToken.positionMultiplier();
int256 newMultiplier = currentMultipler.preciseMul(
PreciseUnitMath.preciseUnit().sub(_inflationFee).toInt256()
);
_setToken.editPositionMultiplier(newMultiplier);
}
function _feeRecipient(ISetToken _set) internal view returns (address) {
return feeStates[_set].feeRecipient;
}
function _lastStreamingFeeTimestamp(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].lastStreamingFeeTimestamp;
}
function _maxStreamingFeePercentage(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].maxStreamingFeePercentage;
}
function _streamingFeePercentage(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].streamingFeePercentage;
}
} | /**
* @title StreamingFeeModule
* @author Set Protocol
*
* Smart contract that accrues streaming fees for Set managers. Streaming fees are denominated as percent
* per year and realized as Set inflation rewarded to the manager.
*/ | NatSpecMultiLine | _calculateStreamingFee | function _calculateStreamingFee(ISetToken _setToken) internal view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
uint256 timeSinceLastFee = block.timestamp.sub(_lastStreamingFeeTimestamp(_setToken));
// Streaming fee is streaming fee times years since last fee
return timeSinceLastFee.mul(_streamingFeePercentage(_setToken)).div(ONE_YEAR_IN_SECONDS);
}
| /**
* Calculates streaming fee by multiplying streamingFeePercentage by the elapsed amount of time since the last fee
* was collected divided by one year in seconds, since the fee is a yearly fee.
*
* @param _setToken Address of Set to have feeState updated
* @return uint256 Streaming fee denominated in percentage of totalSupply
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | None | {
"func_code_index": [
5904,
6297
]
} | 1,480 |
|
StreamingFeeModule | contracts/protocol/modules/StreamingFeeModule.sol | 0xa840939edafa7641cfc7ac1e337e322190ac95ff | Solidity | StreamingFeeModule | contract StreamingFeeModule is ModuleBase, ReentrancyGuard {
using SafeMath for uint256;
using PreciseUnitMath for uint256;
using SafeCast for uint256;
using SignedSafeMath for int256;
using PreciseUnitMath for int256;
using SafeCast for int256;
/* ============ Structs ============ */
struct FeeState {
address feeRecipient; // Address to accrue fees to
uint256 maxStreamingFeePercentage; // Max streaming fee maanager commits to using (1% = 1e16, 100% = 1e18)
uint256 streamingFeePercentage; // Percent of Set accruing to manager annually (1% = 1e16, 100% = 1e18)
uint256 lastStreamingFeeTimestamp; // Timestamp last streaming fee was accrued
}
/* ============ Events ============ */
event FeeActualized(address indexed _setToken, uint256 _managerFee, uint256 _protocolFee);
event StreamingFeeUpdated(address indexed _setToken, uint256 _newStreamingFee);
event FeeRecipientUpdated(address indexed _setToken, address _newFeeRecipient);
/* ============ Constants ============ */
uint256 private constant ONE_YEAR_IN_SECONDS = 365.25 days;
uint256 private constant PROTOCOL_STREAMING_FEE_INDEX = 0;
/* ============ State Variables ============ */
mapping(ISetToken => FeeState) public feeStates;
/* ============ Constructor ============ */
// solhint-disable-next-line no-empty-blocks
constructor(IController _controller) ModuleBase(_controller) {}
/* ============ External Functions ============ */
/*
* Calculates total inflation percentage then mints new Sets to the fee recipient. Position units are
* then adjusted down (in magnitude) in order to ensure full collateralization. Callable by anyone.
*
* @param _setToken Address of SetToken
*/
function accrueFee(ISetToken _setToken)
public
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
uint256 managerFee;
uint256 protocolFee;
if (_streamingFeePercentage(_setToken) > 0) {
uint256 inflationFeePercentage = _calculateStreamingFee(_setToken);
// Calculate incentiveFee inflation
uint256 feeQuantity = _calculateStreamingFeeInflation(_setToken, inflationFeePercentage);
// Mint new Sets to manager and protocol
(managerFee, protocolFee) = _mintManagerAndProtocolFee(_setToken, feeQuantity);
_editPositionMultiplier(_setToken, inflationFeePercentage);
}
// solhint-disable-next-line not-rely-on-time
feeStates[_setToken].lastStreamingFeeTimestamp = block.timestamp;
emit FeeActualized(address(_setToken), managerFee, protocolFee);
}
/**
* SET MANAGER ONLY. Initialize module with SetToken and set the fee state for the SetToken. Passed
* _settings will have lastStreamingFeeTimestamp over-written.
*
* @param _setToken Address of SetToken
* @param _settings FeeState struct defining fee parameters
*/
function initialize(ISetToken _setToken, FeeState memory _settings)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
require(_settings.feeRecipient != address(0), "Fee Recipient must be non-zero address.");
require(
_settings.maxStreamingFeePercentage < PreciseUnitMath.preciseUnit(),
"Max fee must be < 100%."
);
require(
_settings.streamingFeePercentage <= _settings.maxStreamingFeePercentage,
"Fee must be <= max."
);
// solhint-disable-next-line not-rely-on-time
_settings.lastStreamingFeeTimestamp = block.timestamp;
feeStates[_setToken] = _settings;
_setToken.initializeModule();
}
/**
* Removes this module from the SetToken, via call by the SetToken. Manager's feeState is deleted. Fees
* are not accrued in case reason for removing module is related to fee accrual.
*/
function removeModule() external override {
delete feeStates[ISetToken(msg.sender)];
}
/*
* Set new streaming fee. Fees accrue at current rate then new rate is set.
* Fees are accrued to prevent the manager from unfairly accruing a larger percentage.
*
* @param _setToken Address of SetToken
* @param _newFee New streaming fee 18 decimal precision
*/
function updateStreamingFee(ISetToken _setToken, uint256 _newFee)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFee < _maxStreamingFeePercentage(_setToken), "Fee must be less than max");
accrueFee(_setToken);
feeStates[_setToken].streamingFeePercentage = _newFee;
emit StreamingFeeUpdated(address(_setToken), _newFee);
}
/*
* Set new fee recipient.
*
* @param _setToken Address of SetToken
* @param _newFeeRecipient New fee recipient
*/
function updateFeeRecipient(ISetToken _setToken, address _newFeeRecipient)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFeeRecipient != address(0), "Fee Recipient must be non-zero address.");
feeStates[_setToken].feeRecipient = _newFeeRecipient;
emit FeeRecipientUpdated(address(_setToken), _newFeeRecipient);
}
/*
* Calculates total inflation percentage in order to accrue fees to manager.
*
* @param _setToken Address of SetToken
* @return uint256 Percent inflation of supply
*/
function getFee(ISetToken _setToken) external view returns (uint256) {
return _calculateStreamingFee(_setToken);
}
/* ============ Internal Functions ============ */
/**
* Calculates streaming fee by multiplying streamingFeePercentage by the elapsed amount of time since the last fee
* was collected divided by one year in seconds, since the fee is a yearly fee.
*
* @param _setToken Address of Set to have feeState updated
* @return uint256 Streaming fee denominated in percentage of totalSupply
*/
function _calculateStreamingFee(ISetToken _setToken) internal view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
uint256 timeSinceLastFee = block.timestamp.sub(_lastStreamingFeeTimestamp(_setToken));
// Streaming fee is streaming fee times years since last fee
return timeSinceLastFee.mul(_streamingFeePercentage(_setToken)).div(ONE_YEAR_IN_SECONDS);
}
/**
* Returns the new incentive fee denominated in the number of SetTokens to mint. The calculation for the fee involves
* implying mint quantity so that the feeRecipient owns the fee percentage of the entire supply of the Set.
*
* The formula to solve for fee is:
* (feeQuantity / feeQuantity) + totalSupply = fee / scaleFactor
*
* The simplified formula utilized below is:
* feeQuantity = fee * totalSupply / (scaleFactor - fee)
*
* @param _setToken SetToken instance
* @param _feePercentage Fee levied to feeRecipient
* @return uint256 New RebalancingSet issue quantity
*/
function _calculateStreamingFeeInflation(ISetToken _setToken, uint256 _feePercentage)
internal
view
returns (uint256)
{
uint256 totalSupply = _setToken.totalSupply();
// fee * totalSupply
uint256 a = _feePercentage.mul(totalSupply);
// ScaleFactor (10e18) - fee
uint256 b = PreciseUnitMath.preciseUnit().sub(_feePercentage);
return a.div(b);
}
/**
* Mints sets to both the manager and the protocol. Protocol takes a percentage fee of the total amount of Sets
* minted to manager.
*
* @param _setToken SetToken instance
* @param _feeQuantity Amount of Sets to be minted as fees
* @return uint256 Amount of Sets accrued to manager as fee
* @return uint256 Amount of Sets accrued to protocol as fee
*/
function _mintManagerAndProtocolFee(ISetToken _setToken, uint256 _feeQuantity)
internal
returns (uint256, uint256)
{
address protocolFeeRecipient = controller.feeRecipient();
uint256 protocolFee = controller.getModuleFee(address(this), PROTOCOL_STREAMING_FEE_INDEX);
uint256 protocolFeeAmount = _feeQuantity.preciseMul(protocolFee);
uint256 managerFeeAmount = _feeQuantity.sub(protocolFeeAmount);
_setToken.mint(_feeRecipient(_setToken), managerFeeAmount);
if (protocolFeeAmount > 0) {
_setToken.mint(protocolFeeRecipient, protocolFeeAmount);
}
return (managerFeeAmount, protocolFeeAmount);
}
/**
* Calculates new position multiplier according to following formula:
*
* newMultiplier = oldMultiplier * (1-inflationFee)
*
* This reduces position sizes to offset increase in supply due to fee collection.
*
* @param _setToken SetToken instance
* @param _inflationFee Fee inflation rate
*/
function _editPositionMultiplier(ISetToken _setToken, uint256 _inflationFee) internal {
int256 currentMultipler = _setToken.positionMultiplier();
int256 newMultiplier = currentMultipler.preciseMul(
PreciseUnitMath.preciseUnit().sub(_inflationFee).toInt256()
);
_setToken.editPositionMultiplier(newMultiplier);
}
function _feeRecipient(ISetToken _set) internal view returns (address) {
return feeStates[_set].feeRecipient;
}
function _lastStreamingFeeTimestamp(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].lastStreamingFeeTimestamp;
}
function _maxStreamingFeePercentage(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].maxStreamingFeePercentage;
}
function _streamingFeePercentage(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].streamingFeePercentage;
}
} | /**
* @title StreamingFeeModule
* @author Set Protocol
*
* Smart contract that accrues streaming fees for Set managers. Streaming fees are denominated as percent
* per year and realized as Set inflation rewarded to the manager.
*/ | NatSpecMultiLine | _calculateStreamingFeeInflation | function _calculateStreamingFeeInflation(ISetToken _setToken, uint256 _feePercentage)
internal
view
returns (uint256)
{
uint256 totalSupply = _setToken.totalSupply();
// fee * totalSupply
uint256 a = _feePercentage.mul(totalSupply);
// ScaleFactor (10e18) - fee
uint256 b = PreciseUnitMath.preciseUnit().sub(_feePercentage);
return a.div(b);
}
| /**
* Returns the new incentive fee denominated in the number of SetTokens to mint. The calculation for the fee involves
* implying mint quantity so that the feeRecipient owns the fee percentage of the entire supply of the Set.
*
* The formula to solve for fee is:
* (feeQuantity / feeQuantity) + totalSupply = fee / scaleFactor
*
* The simplified formula utilized below is:
* feeQuantity = fee * totalSupply / (scaleFactor - fee)
*
* @param _setToken SetToken instance
* @param _feePercentage Fee levied to feeRecipient
* @return uint256 New RebalancingSet issue quantity
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | None | {
"func_code_index": [
6960,
7348
]
} | 1,481 |
|
StreamingFeeModule | contracts/protocol/modules/StreamingFeeModule.sol | 0xa840939edafa7641cfc7ac1e337e322190ac95ff | Solidity | StreamingFeeModule | contract StreamingFeeModule is ModuleBase, ReentrancyGuard {
using SafeMath for uint256;
using PreciseUnitMath for uint256;
using SafeCast for uint256;
using SignedSafeMath for int256;
using PreciseUnitMath for int256;
using SafeCast for int256;
/* ============ Structs ============ */
struct FeeState {
address feeRecipient; // Address to accrue fees to
uint256 maxStreamingFeePercentage; // Max streaming fee maanager commits to using (1% = 1e16, 100% = 1e18)
uint256 streamingFeePercentage; // Percent of Set accruing to manager annually (1% = 1e16, 100% = 1e18)
uint256 lastStreamingFeeTimestamp; // Timestamp last streaming fee was accrued
}
/* ============ Events ============ */
event FeeActualized(address indexed _setToken, uint256 _managerFee, uint256 _protocolFee);
event StreamingFeeUpdated(address indexed _setToken, uint256 _newStreamingFee);
event FeeRecipientUpdated(address indexed _setToken, address _newFeeRecipient);
/* ============ Constants ============ */
uint256 private constant ONE_YEAR_IN_SECONDS = 365.25 days;
uint256 private constant PROTOCOL_STREAMING_FEE_INDEX = 0;
/* ============ State Variables ============ */
mapping(ISetToken => FeeState) public feeStates;
/* ============ Constructor ============ */
// solhint-disable-next-line no-empty-blocks
constructor(IController _controller) ModuleBase(_controller) {}
/* ============ External Functions ============ */
/*
* Calculates total inflation percentage then mints new Sets to the fee recipient. Position units are
* then adjusted down (in magnitude) in order to ensure full collateralization. Callable by anyone.
*
* @param _setToken Address of SetToken
*/
function accrueFee(ISetToken _setToken)
public
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
uint256 managerFee;
uint256 protocolFee;
if (_streamingFeePercentage(_setToken) > 0) {
uint256 inflationFeePercentage = _calculateStreamingFee(_setToken);
// Calculate incentiveFee inflation
uint256 feeQuantity = _calculateStreamingFeeInflation(_setToken, inflationFeePercentage);
// Mint new Sets to manager and protocol
(managerFee, protocolFee) = _mintManagerAndProtocolFee(_setToken, feeQuantity);
_editPositionMultiplier(_setToken, inflationFeePercentage);
}
// solhint-disable-next-line not-rely-on-time
feeStates[_setToken].lastStreamingFeeTimestamp = block.timestamp;
emit FeeActualized(address(_setToken), managerFee, protocolFee);
}
/**
* SET MANAGER ONLY. Initialize module with SetToken and set the fee state for the SetToken. Passed
* _settings will have lastStreamingFeeTimestamp over-written.
*
* @param _setToken Address of SetToken
* @param _settings FeeState struct defining fee parameters
*/
function initialize(ISetToken _setToken, FeeState memory _settings)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
require(_settings.feeRecipient != address(0), "Fee Recipient must be non-zero address.");
require(
_settings.maxStreamingFeePercentage < PreciseUnitMath.preciseUnit(),
"Max fee must be < 100%."
);
require(
_settings.streamingFeePercentage <= _settings.maxStreamingFeePercentage,
"Fee must be <= max."
);
// solhint-disable-next-line not-rely-on-time
_settings.lastStreamingFeeTimestamp = block.timestamp;
feeStates[_setToken] = _settings;
_setToken.initializeModule();
}
/**
* Removes this module from the SetToken, via call by the SetToken. Manager's feeState is deleted. Fees
* are not accrued in case reason for removing module is related to fee accrual.
*/
function removeModule() external override {
delete feeStates[ISetToken(msg.sender)];
}
/*
* Set new streaming fee. Fees accrue at current rate then new rate is set.
* Fees are accrued to prevent the manager from unfairly accruing a larger percentage.
*
* @param _setToken Address of SetToken
* @param _newFee New streaming fee 18 decimal precision
*/
function updateStreamingFee(ISetToken _setToken, uint256 _newFee)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFee < _maxStreamingFeePercentage(_setToken), "Fee must be less than max");
accrueFee(_setToken);
feeStates[_setToken].streamingFeePercentage = _newFee;
emit StreamingFeeUpdated(address(_setToken), _newFee);
}
/*
* Set new fee recipient.
*
* @param _setToken Address of SetToken
* @param _newFeeRecipient New fee recipient
*/
function updateFeeRecipient(ISetToken _setToken, address _newFeeRecipient)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFeeRecipient != address(0), "Fee Recipient must be non-zero address.");
feeStates[_setToken].feeRecipient = _newFeeRecipient;
emit FeeRecipientUpdated(address(_setToken), _newFeeRecipient);
}
/*
* Calculates total inflation percentage in order to accrue fees to manager.
*
* @param _setToken Address of SetToken
* @return uint256 Percent inflation of supply
*/
function getFee(ISetToken _setToken) external view returns (uint256) {
return _calculateStreamingFee(_setToken);
}
/* ============ Internal Functions ============ */
/**
* Calculates streaming fee by multiplying streamingFeePercentage by the elapsed amount of time since the last fee
* was collected divided by one year in seconds, since the fee is a yearly fee.
*
* @param _setToken Address of Set to have feeState updated
* @return uint256 Streaming fee denominated in percentage of totalSupply
*/
function _calculateStreamingFee(ISetToken _setToken) internal view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
uint256 timeSinceLastFee = block.timestamp.sub(_lastStreamingFeeTimestamp(_setToken));
// Streaming fee is streaming fee times years since last fee
return timeSinceLastFee.mul(_streamingFeePercentage(_setToken)).div(ONE_YEAR_IN_SECONDS);
}
/**
* Returns the new incentive fee denominated in the number of SetTokens to mint. The calculation for the fee involves
* implying mint quantity so that the feeRecipient owns the fee percentage of the entire supply of the Set.
*
* The formula to solve for fee is:
* (feeQuantity / feeQuantity) + totalSupply = fee / scaleFactor
*
* The simplified formula utilized below is:
* feeQuantity = fee * totalSupply / (scaleFactor - fee)
*
* @param _setToken SetToken instance
* @param _feePercentage Fee levied to feeRecipient
* @return uint256 New RebalancingSet issue quantity
*/
function _calculateStreamingFeeInflation(ISetToken _setToken, uint256 _feePercentage)
internal
view
returns (uint256)
{
uint256 totalSupply = _setToken.totalSupply();
// fee * totalSupply
uint256 a = _feePercentage.mul(totalSupply);
// ScaleFactor (10e18) - fee
uint256 b = PreciseUnitMath.preciseUnit().sub(_feePercentage);
return a.div(b);
}
/**
* Mints sets to both the manager and the protocol. Protocol takes a percentage fee of the total amount of Sets
* minted to manager.
*
* @param _setToken SetToken instance
* @param _feeQuantity Amount of Sets to be minted as fees
* @return uint256 Amount of Sets accrued to manager as fee
* @return uint256 Amount of Sets accrued to protocol as fee
*/
function _mintManagerAndProtocolFee(ISetToken _setToken, uint256 _feeQuantity)
internal
returns (uint256, uint256)
{
address protocolFeeRecipient = controller.feeRecipient();
uint256 protocolFee = controller.getModuleFee(address(this), PROTOCOL_STREAMING_FEE_INDEX);
uint256 protocolFeeAmount = _feeQuantity.preciseMul(protocolFee);
uint256 managerFeeAmount = _feeQuantity.sub(protocolFeeAmount);
_setToken.mint(_feeRecipient(_setToken), managerFeeAmount);
if (protocolFeeAmount > 0) {
_setToken.mint(protocolFeeRecipient, protocolFeeAmount);
}
return (managerFeeAmount, protocolFeeAmount);
}
/**
* Calculates new position multiplier according to following formula:
*
* newMultiplier = oldMultiplier * (1-inflationFee)
*
* This reduces position sizes to offset increase in supply due to fee collection.
*
* @param _setToken SetToken instance
* @param _inflationFee Fee inflation rate
*/
function _editPositionMultiplier(ISetToken _setToken, uint256 _inflationFee) internal {
int256 currentMultipler = _setToken.positionMultiplier();
int256 newMultiplier = currentMultipler.preciseMul(
PreciseUnitMath.preciseUnit().sub(_inflationFee).toInt256()
);
_setToken.editPositionMultiplier(newMultiplier);
}
function _feeRecipient(ISetToken _set) internal view returns (address) {
return feeStates[_set].feeRecipient;
}
function _lastStreamingFeeTimestamp(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].lastStreamingFeeTimestamp;
}
function _maxStreamingFeePercentage(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].maxStreamingFeePercentage;
}
function _streamingFeePercentage(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].streamingFeePercentage;
}
} | /**
* @title StreamingFeeModule
* @author Set Protocol
*
* Smart contract that accrues streaming fees for Set managers. Streaming fees are denominated as percent
* per year and realized as Set inflation rewarded to the manager.
*/ | NatSpecMultiLine | _mintManagerAndProtocolFee | function _mintManagerAndProtocolFee(ISetToken _setToken, uint256 _feeQuantity)
internal
returns (uint256, uint256)
{
address protocolFeeRecipient = controller.feeRecipient();
uint256 protocolFee = controller.getModuleFee(address(this), PROTOCOL_STREAMING_FEE_INDEX);
uint256 protocolFeeAmount = _feeQuantity.preciseMul(protocolFee);
uint256 managerFeeAmount = _feeQuantity.sub(protocolFeeAmount);
_setToken.mint(_feeRecipient(_setToken), managerFeeAmount);
if (protocolFeeAmount > 0) {
_setToken.mint(protocolFeeRecipient, protocolFeeAmount);
}
return (managerFeeAmount, protocolFeeAmount);
}
| /**
* Mints sets to both the manager and the protocol. Protocol takes a percentage fee of the total amount of Sets
* minted to manager.
*
* @param _setToken SetToken instance
* @param _feeQuantity Amount of Sets to be minted as fees
* @return uint256 Amount of Sets accrued to manager as fee
* @return uint256 Amount of Sets accrued to protocol as fee
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | None | {
"func_code_index": [
7794,
8442
]
} | 1,482 |
|
StreamingFeeModule | contracts/protocol/modules/StreamingFeeModule.sol | 0xa840939edafa7641cfc7ac1e337e322190ac95ff | Solidity | StreamingFeeModule | contract StreamingFeeModule is ModuleBase, ReentrancyGuard {
using SafeMath for uint256;
using PreciseUnitMath for uint256;
using SafeCast for uint256;
using SignedSafeMath for int256;
using PreciseUnitMath for int256;
using SafeCast for int256;
/* ============ Structs ============ */
struct FeeState {
address feeRecipient; // Address to accrue fees to
uint256 maxStreamingFeePercentage; // Max streaming fee maanager commits to using (1% = 1e16, 100% = 1e18)
uint256 streamingFeePercentage; // Percent of Set accruing to manager annually (1% = 1e16, 100% = 1e18)
uint256 lastStreamingFeeTimestamp; // Timestamp last streaming fee was accrued
}
/* ============ Events ============ */
event FeeActualized(address indexed _setToken, uint256 _managerFee, uint256 _protocolFee);
event StreamingFeeUpdated(address indexed _setToken, uint256 _newStreamingFee);
event FeeRecipientUpdated(address indexed _setToken, address _newFeeRecipient);
/* ============ Constants ============ */
uint256 private constant ONE_YEAR_IN_SECONDS = 365.25 days;
uint256 private constant PROTOCOL_STREAMING_FEE_INDEX = 0;
/* ============ State Variables ============ */
mapping(ISetToken => FeeState) public feeStates;
/* ============ Constructor ============ */
// solhint-disable-next-line no-empty-blocks
constructor(IController _controller) ModuleBase(_controller) {}
/* ============ External Functions ============ */
/*
* Calculates total inflation percentage then mints new Sets to the fee recipient. Position units are
* then adjusted down (in magnitude) in order to ensure full collateralization. Callable by anyone.
*
* @param _setToken Address of SetToken
*/
function accrueFee(ISetToken _setToken)
public
nonReentrant
onlyValidAndInitializedSet(_setToken)
{
uint256 managerFee;
uint256 protocolFee;
if (_streamingFeePercentage(_setToken) > 0) {
uint256 inflationFeePercentage = _calculateStreamingFee(_setToken);
// Calculate incentiveFee inflation
uint256 feeQuantity = _calculateStreamingFeeInflation(_setToken, inflationFeePercentage);
// Mint new Sets to manager and protocol
(managerFee, protocolFee) = _mintManagerAndProtocolFee(_setToken, feeQuantity);
_editPositionMultiplier(_setToken, inflationFeePercentage);
}
// solhint-disable-next-line not-rely-on-time
feeStates[_setToken].lastStreamingFeeTimestamp = block.timestamp;
emit FeeActualized(address(_setToken), managerFee, protocolFee);
}
/**
* SET MANAGER ONLY. Initialize module with SetToken and set the fee state for the SetToken. Passed
* _settings will have lastStreamingFeeTimestamp over-written.
*
* @param _setToken Address of SetToken
* @param _settings FeeState struct defining fee parameters
*/
function initialize(ISetToken _setToken, FeeState memory _settings)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
require(_settings.feeRecipient != address(0), "Fee Recipient must be non-zero address.");
require(
_settings.maxStreamingFeePercentage < PreciseUnitMath.preciseUnit(),
"Max fee must be < 100%."
);
require(
_settings.streamingFeePercentage <= _settings.maxStreamingFeePercentage,
"Fee must be <= max."
);
// solhint-disable-next-line not-rely-on-time
_settings.lastStreamingFeeTimestamp = block.timestamp;
feeStates[_setToken] = _settings;
_setToken.initializeModule();
}
/**
* Removes this module from the SetToken, via call by the SetToken. Manager's feeState is deleted. Fees
* are not accrued in case reason for removing module is related to fee accrual.
*/
function removeModule() external override {
delete feeStates[ISetToken(msg.sender)];
}
/*
* Set new streaming fee. Fees accrue at current rate then new rate is set.
* Fees are accrued to prevent the manager from unfairly accruing a larger percentage.
*
* @param _setToken Address of SetToken
* @param _newFee New streaming fee 18 decimal precision
*/
function updateStreamingFee(ISetToken _setToken, uint256 _newFee)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFee < _maxStreamingFeePercentage(_setToken), "Fee must be less than max");
accrueFee(_setToken);
feeStates[_setToken].streamingFeePercentage = _newFee;
emit StreamingFeeUpdated(address(_setToken), _newFee);
}
/*
* Set new fee recipient.
*
* @param _setToken Address of SetToken
* @param _newFeeRecipient New fee recipient
*/
function updateFeeRecipient(ISetToken _setToken, address _newFeeRecipient)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndInitializedSet(_setToken)
{
require(_newFeeRecipient != address(0), "Fee Recipient must be non-zero address.");
feeStates[_setToken].feeRecipient = _newFeeRecipient;
emit FeeRecipientUpdated(address(_setToken), _newFeeRecipient);
}
/*
* Calculates total inflation percentage in order to accrue fees to manager.
*
* @param _setToken Address of SetToken
* @return uint256 Percent inflation of supply
*/
function getFee(ISetToken _setToken) external view returns (uint256) {
return _calculateStreamingFee(_setToken);
}
/* ============ Internal Functions ============ */
/**
* Calculates streaming fee by multiplying streamingFeePercentage by the elapsed amount of time since the last fee
* was collected divided by one year in seconds, since the fee is a yearly fee.
*
* @param _setToken Address of Set to have feeState updated
* @return uint256 Streaming fee denominated in percentage of totalSupply
*/
function _calculateStreamingFee(ISetToken _setToken) internal view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
uint256 timeSinceLastFee = block.timestamp.sub(_lastStreamingFeeTimestamp(_setToken));
// Streaming fee is streaming fee times years since last fee
return timeSinceLastFee.mul(_streamingFeePercentage(_setToken)).div(ONE_YEAR_IN_SECONDS);
}
/**
* Returns the new incentive fee denominated in the number of SetTokens to mint. The calculation for the fee involves
* implying mint quantity so that the feeRecipient owns the fee percentage of the entire supply of the Set.
*
* The formula to solve for fee is:
* (feeQuantity / feeQuantity) + totalSupply = fee / scaleFactor
*
* The simplified formula utilized below is:
* feeQuantity = fee * totalSupply / (scaleFactor - fee)
*
* @param _setToken SetToken instance
* @param _feePercentage Fee levied to feeRecipient
* @return uint256 New RebalancingSet issue quantity
*/
function _calculateStreamingFeeInflation(ISetToken _setToken, uint256 _feePercentage)
internal
view
returns (uint256)
{
uint256 totalSupply = _setToken.totalSupply();
// fee * totalSupply
uint256 a = _feePercentage.mul(totalSupply);
// ScaleFactor (10e18) - fee
uint256 b = PreciseUnitMath.preciseUnit().sub(_feePercentage);
return a.div(b);
}
/**
* Mints sets to both the manager and the protocol. Protocol takes a percentage fee of the total amount of Sets
* minted to manager.
*
* @param _setToken SetToken instance
* @param _feeQuantity Amount of Sets to be minted as fees
* @return uint256 Amount of Sets accrued to manager as fee
* @return uint256 Amount of Sets accrued to protocol as fee
*/
function _mintManagerAndProtocolFee(ISetToken _setToken, uint256 _feeQuantity)
internal
returns (uint256, uint256)
{
address protocolFeeRecipient = controller.feeRecipient();
uint256 protocolFee = controller.getModuleFee(address(this), PROTOCOL_STREAMING_FEE_INDEX);
uint256 protocolFeeAmount = _feeQuantity.preciseMul(protocolFee);
uint256 managerFeeAmount = _feeQuantity.sub(protocolFeeAmount);
_setToken.mint(_feeRecipient(_setToken), managerFeeAmount);
if (protocolFeeAmount > 0) {
_setToken.mint(protocolFeeRecipient, protocolFeeAmount);
}
return (managerFeeAmount, protocolFeeAmount);
}
/**
* Calculates new position multiplier according to following formula:
*
* newMultiplier = oldMultiplier * (1-inflationFee)
*
* This reduces position sizes to offset increase in supply due to fee collection.
*
* @param _setToken SetToken instance
* @param _inflationFee Fee inflation rate
*/
function _editPositionMultiplier(ISetToken _setToken, uint256 _inflationFee) internal {
int256 currentMultipler = _setToken.positionMultiplier();
int256 newMultiplier = currentMultipler.preciseMul(
PreciseUnitMath.preciseUnit().sub(_inflationFee).toInt256()
);
_setToken.editPositionMultiplier(newMultiplier);
}
function _feeRecipient(ISetToken _set) internal view returns (address) {
return feeStates[_set].feeRecipient;
}
function _lastStreamingFeeTimestamp(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].lastStreamingFeeTimestamp;
}
function _maxStreamingFeePercentage(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].maxStreamingFeePercentage;
}
function _streamingFeePercentage(ISetToken _set) internal view returns (uint256) {
return feeStates[_set].streamingFeePercentage;
}
} | /**
* @title StreamingFeeModule
* @author Set Protocol
*
* Smart contract that accrues streaming fees for Set managers. Streaming fees are denominated as percent
* per year and realized as Set inflation rewarded to the manager.
*/ | NatSpecMultiLine | _editPositionMultiplier | function _editPositionMultiplier(ISetToken _setToken, uint256 _inflationFee) internal {
int256 currentMultipler = _setToken.positionMultiplier();
int256 newMultiplier = currentMultipler.preciseMul(
PreciseUnitMath.preciseUnit().sub(_inflationFee).toInt256()
);
_setToken.editPositionMultiplier(newMultiplier);
}
| /**
* Calculates new position multiplier according to following formula:
*
* newMultiplier = oldMultiplier * (1-inflationFee)
*
* This reduces position sizes to offset increase in supply due to fee collection.
*
* @param _setToken SetToken instance
* @param _inflationFee Fee inflation rate
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | None | {
"func_code_index": [
8795,
9133
]
} | 1,483 |
|
Molecules | contracts/interfaces/IAtomReader.sol | 0xa96c108827674d6a08ed981477b7737495a9c547 | Solidity | IAtomReader | interface IAtomReader{
/// @notice Get atomic number and ionic charge of a specified POWNFT Atom
/// @dev Gets Atom hash from POWNFT contract, so will throw for _tokenId of non-existent token.
/// @param _tokenId TokenId of the Atom to query
/// @return atomicNumber Atomic number of the Atom
/// @return ionCharge Ionic charge of the Atom
function getAtomData(uint _tokenId) external view returns(uint atomicNumber, int8 ionCharge);
/// @notice Get atomic number of a specified POWNFT Atom
/// @dev Gets Atom hash from POWNFT contract, so will throw for _tokenId of non-existent token.
/// @param _tokenId TokenId of the Atom to query
/// @return Atomic number of the Atom
function getAtomicNumber(uint _tokenId) external view returns(uint);
/// @notice Get ionic charge of a specified POWNFT Atom
/// @dev Gets Atom hash from POWNFT contract, so will throw for _tokenId of non-existent token.
/// @param _tokenId TokenId of the Atom to query
/// @return ionic charge of the Atom
function getIonCharge(uint _tokenId) external view returns(int8);
/// @notice Get array of all possible ions for a specified element
/// @param atomicNumber Atomic number of element to query
/// @return Array of possible ionic charges
function getIons(uint atomicNumber) external pure returns(int8[] memory);
/// @notice Check if a given element can have a particular ionic charge
/// @param atomicNumber Atomic number of element to query
/// @param ionCharge Ionic charge to check
/// @return True if this element can have this ion, false otherwise.
function isValidIonCharge(uint atomicNumber, int8 ionCharge) external pure returns(bool);
/// @notice Check if a given element has any potential ions
/// @param atomicNumber Atomic number of element to query
/// @return True if this element can ionise, false otherwise.
function canIonise(uint atomicNumber) external pure returns(bool);
} | /// @title POWNFT Atom Reader
/// @author AnAllergyToAnalogy
/// @notice On-chain calculation atomic number and ionisation data about POWNFT Atoms. Replicates functionality done off-chain for metadata. | NatSpecSingleLine | getAtomData | function getAtomData(uint _tokenId) external view returns(uint atomicNumber, int8 ionCharge);
| /// @notice Get atomic number and ionic charge of a specified POWNFT Atom
/// @dev Gets Atom hash from POWNFT contract, so will throw for _tokenId of non-existent token.
/// @param _tokenId TokenId of the Atom to query
/// @return atomicNumber Atomic number of the Atom
/// @return ionCharge Ionic charge of the Atom | NatSpecSingleLine | v0.8.4+commit.c7e474f2 | {
"func_code_index": [
368,
466
]
} | 1,484 |
||
Molecules | contracts/interfaces/IAtomReader.sol | 0xa96c108827674d6a08ed981477b7737495a9c547 | Solidity | IAtomReader | interface IAtomReader{
/// @notice Get atomic number and ionic charge of a specified POWNFT Atom
/// @dev Gets Atom hash from POWNFT contract, so will throw for _tokenId of non-existent token.
/// @param _tokenId TokenId of the Atom to query
/// @return atomicNumber Atomic number of the Atom
/// @return ionCharge Ionic charge of the Atom
function getAtomData(uint _tokenId) external view returns(uint atomicNumber, int8 ionCharge);
/// @notice Get atomic number of a specified POWNFT Atom
/// @dev Gets Atom hash from POWNFT contract, so will throw for _tokenId of non-existent token.
/// @param _tokenId TokenId of the Atom to query
/// @return Atomic number of the Atom
function getAtomicNumber(uint _tokenId) external view returns(uint);
/// @notice Get ionic charge of a specified POWNFT Atom
/// @dev Gets Atom hash from POWNFT contract, so will throw for _tokenId of non-existent token.
/// @param _tokenId TokenId of the Atom to query
/// @return ionic charge of the Atom
function getIonCharge(uint _tokenId) external view returns(int8);
/// @notice Get array of all possible ions for a specified element
/// @param atomicNumber Atomic number of element to query
/// @return Array of possible ionic charges
function getIons(uint atomicNumber) external pure returns(int8[] memory);
/// @notice Check if a given element can have a particular ionic charge
/// @param atomicNumber Atomic number of element to query
/// @param ionCharge Ionic charge to check
/// @return True if this element can have this ion, false otherwise.
function isValidIonCharge(uint atomicNumber, int8 ionCharge) external pure returns(bool);
/// @notice Check if a given element has any potential ions
/// @param atomicNumber Atomic number of element to query
/// @return True if this element can ionise, false otherwise.
function canIonise(uint atomicNumber) external pure returns(bool);
} | /// @title POWNFT Atom Reader
/// @author AnAllergyToAnalogy
/// @notice On-chain calculation atomic number and ionisation data about POWNFT Atoms. Replicates functionality done off-chain for metadata. | NatSpecSingleLine | getAtomicNumber | function getAtomicNumber(uint _tokenId) external view returns(uint);
| /// @notice Get atomic number of a specified POWNFT Atom
/// @dev Gets Atom hash from POWNFT contract, so will throw for _tokenId of non-existent token.
/// @param _tokenId TokenId of the Atom to query
/// @return Atomic number of the Atom | NatSpecSingleLine | v0.8.4+commit.c7e474f2 | {
"func_code_index": [
729,
802
]
} | 1,485 |
||
Molecules | contracts/interfaces/IAtomReader.sol | 0xa96c108827674d6a08ed981477b7737495a9c547 | Solidity | IAtomReader | interface IAtomReader{
/// @notice Get atomic number and ionic charge of a specified POWNFT Atom
/// @dev Gets Atom hash from POWNFT contract, so will throw for _tokenId of non-existent token.
/// @param _tokenId TokenId of the Atom to query
/// @return atomicNumber Atomic number of the Atom
/// @return ionCharge Ionic charge of the Atom
function getAtomData(uint _tokenId) external view returns(uint atomicNumber, int8 ionCharge);
/// @notice Get atomic number of a specified POWNFT Atom
/// @dev Gets Atom hash from POWNFT contract, so will throw for _tokenId of non-existent token.
/// @param _tokenId TokenId of the Atom to query
/// @return Atomic number of the Atom
function getAtomicNumber(uint _tokenId) external view returns(uint);
/// @notice Get ionic charge of a specified POWNFT Atom
/// @dev Gets Atom hash from POWNFT contract, so will throw for _tokenId of non-existent token.
/// @param _tokenId TokenId of the Atom to query
/// @return ionic charge of the Atom
function getIonCharge(uint _tokenId) external view returns(int8);
/// @notice Get array of all possible ions for a specified element
/// @param atomicNumber Atomic number of element to query
/// @return Array of possible ionic charges
function getIons(uint atomicNumber) external pure returns(int8[] memory);
/// @notice Check if a given element can have a particular ionic charge
/// @param atomicNumber Atomic number of element to query
/// @param ionCharge Ionic charge to check
/// @return True if this element can have this ion, false otherwise.
function isValidIonCharge(uint atomicNumber, int8 ionCharge) external pure returns(bool);
/// @notice Check if a given element has any potential ions
/// @param atomicNumber Atomic number of element to query
/// @return True if this element can ionise, false otherwise.
function canIonise(uint atomicNumber) external pure returns(bool);
} | /// @title POWNFT Atom Reader
/// @author AnAllergyToAnalogy
/// @notice On-chain calculation atomic number and ionisation data about POWNFT Atoms. Replicates functionality done off-chain for metadata. | NatSpecSingleLine | getIonCharge | function getIonCharge(uint _tokenId) external view returns(int8);
| /// @notice Get ionic charge of a specified POWNFT Atom
/// @dev Gets Atom hash from POWNFT contract, so will throw for _tokenId of non-existent token.
/// @param _tokenId TokenId of the Atom to query
/// @return ionic charge of the Atom | NatSpecSingleLine | v0.8.4+commit.c7e474f2 | {
"func_code_index": [
1063,
1133
]
} | 1,486 |
||
Molecules | contracts/interfaces/IAtomReader.sol | 0xa96c108827674d6a08ed981477b7737495a9c547 | Solidity | IAtomReader | interface IAtomReader{
/// @notice Get atomic number and ionic charge of a specified POWNFT Atom
/// @dev Gets Atom hash from POWNFT contract, so will throw for _tokenId of non-existent token.
/// @param _tokenId TokenId of the Atom to query
/// @return atomicNumber Atomic number of the Atom
/// @return ionCharge Ionic charge of the Atom
function getAtomData(uint _tokenId) external view returns(uint atomicNumber, int8 ionCharge);
/// @notice Get atomic number of a specified POWNFT Atom
/// @dev Gets Atom hash from POWNFT contract, so will throw for _tokenId of non-existent token.
/// @param _tokenId TokenId of the Atom to query
/// @return Atomic number of the Atom
function getAtomicNumber(uint _tokenId) external view returns(uint);
/// @notice Get ionic charge of a specified POWNFT Atom
/// @dev Gets Atom hash from POWNFT contract, so will throw for _tokenId of non-existent token.
/// @param _tokenId TokenId of the Atom to query
/// @return ionic charge of the Atom
function getIonCharge(uint _tokenId) external view returns(int8);
/// @notice Get array of all possible ions for a specified element
/// @param atomicNumber Atomic number of element to query
/// @return Array of possible ionic charges
function getIons(uint atomicNumber) external pure returns(int8[] memory);
/// @notice Check if a given element can have a particular ionic charge
/// @param atomicNumber Atomic number of element to query
/// @param ionCharge Ionic charge to check
/// @return True if this element can have this ion, false otherwise.
function isValidIonCharge(uint atomicNumber, int8 ionCharge) external pure returns(bool);
/// @notice Check if a given element has any potential ions
/// @param atomicNumber Atomic number of element to query
/// @return True if this element can ionise, false otherwise.
function canIonise(uint atomicNumber) external pure returns(bool);
} | /// @title POWNFT Atom Reader
/// @author AnAllergyToAnalogy
/// @notice On-chain calculation atomic number and ionisation data about POWNFT Atoms. Replicates functionality done off-chain for metadata. | NatSpecSingleLine | getIons | function getIons(uint atomicNumber) external pure returns(int8[] memory);
| /// @notice Get array of all possible ions for a specified element
/// @param atomicNumber Atomic number of element to query
/// @return Array of possible ionic charges | NatSpecSingleLine | v0.8.4+commit.c7e474f2 | {
"func_code_index": [
1320,
1398
]
} | 1,487 |
||
Molecules | contracts/interfaces/IAtomReader.sol | 0xa96c108827674d6a08ed981477b7737495a9c547 | Solidity | IAtomReader | interface IAtomReader{
/// @notice Get atomic number and ionic charge of a specified POWNFT Atom
/// @dev Gets Atom hash from POWNFT contract, so will throw for _tokenId of non-existent token.
/// @param _tokenId TokenId of the Atom to query
/// @return atomicNumber Atomic number of the Atom
/// @return ionCharge Ionic charge of the Atom
function getAtomData(uint _tokenId) external view returns(uint atomicNumber, int8 ionCharge);
/// @notice Get atomic number of a specified POWNFT Atom
/// @dev Gets Atom hash from POWNFT contract, so will throw for _tokenId of non-existent token.
/// @param _tokenId TokenId of the Atom to query
/// @return Atomic number of the Atom
function getAtomicNumber(uint _tokenId) external view returns(uint);
/// @notice Get ionic charge of a specified POWNFT Atom
/// @dev Gets Atom hash from POWNFT contract, so will throw for _tokenId of non-existent token.
/// @param _tokenId TokenId of the Atom to query
/// @return ionic charge of the Atom
function getIonCharge(uint _tokenId) external view returns(int8);
/// @notice Get array of all possible ions for a specified element
/// @param atomicNumber Atomic number of element to query
/// @return Array of possible ionic charges
function getIons(uint atomicNumber) external pure returns(int8[] memory);
/// @notice Check if a given element can have a particular ionic charge
/// @param atomicNumber Atomic number of element to query
/// @param ionCharge Ionic charge to check
/// @return True if this element can have this ion, false otherwise.
function isValidIonCharge(uint atomicNumber, int8 ionCharge) external pure returns(bool);
/// @notice Check if a given element has any potential ions
/// @param atomicNumber Atomic number of element to query
/// @return True if this element can ionise, false otherwise.
function canIonise(uint atomicNumber) external pure returns(bool);
} | /// @title POWNFT Atom Reader
/// @author AnAllergyToAnalogy
/// @notice On-chain calculation atomic number and ionisation data about POWNFT Atoms. Replicates functionality done off-chain for metadata. | NatSpecSingleLine | isValidIonCharge | function isValidIonCharge(uint atomicNumber, int8 ionCharge) external pure returns(bool);
| /// @notice Check if a given element can have a particular ionic charge
/// @param atomicNumber Atomic number of element to query
/// @param ionCharge Ionic charge to check
/// @return True if this element can have this ion, false otherwise. | NatSpecSingleLine | v0.8.4+commit.c7e474f2 | {
"func_code_index": [
1663,
1757
]
} | 1,488 |
||
Molecules | contracts/interfaces/IAtomReader.sol | 0xa96c108827674d6a08ed981477b7737495a9c547 | Solidity | IAtomReader | interface IAtomReader{
/// @notice Get atomic number and ionic charge of a specified POWNFT Atom
/// @dev Gets Atom hash from POWNFT contract, so will throw for _tokenId of non-existent token.
/// @param _tokenId TokenId of the Atom to query
/// @return atomicNumber Atomic number of the Atom
/// @return ionCharge Ionic charge of the Atom
function getAtomData(uint _tokenId) external view returns(uint atomicNumber, int8 ionCharge);
/// @notice Get atomic number of a specified POWNFT Atom
/// @dev Gets Atom hash from POWNFT contract, so will throw for _tokenId of non-existent token.
/// @param _tokenId TokenId of the Atom to query
/// @return Atomic number of the Atom
function getAtomicNumber(uint _tokenId) external view returns(uint);
/// @notice Get ionic charge of a specified POWNFT Atom
/// @dev Gets Atom hash from POWNFT contract, so will throw for _tokenId of non-existent token.
/// @param _tokenId TokenId of the Atom to query
/// @return ionic charge of the Atom
function getIonCharge(uint _tokenId) external view returns(int8);
/// @notice Get array of all possible ions for a specified element
/// @param atomicNumber Atomic number of element to query
/// @return Array of possible ionic charges
function getIons(uint atomicNumber) external pure returns(int8[] memory);
/// @notice Check if a given element can have a particular ionic charge
/// @param atomicNumber Atomic number of element to query
/// @param ionCharge Ionic charge to check
/// @return True if this element can have this ion, false otherwise.
function isValidIonCharge(uint atomicNumber, int8 ionCharge) external pure returns(bool);
/// @notice Check if a given element has any potential ions
/// @param atomicNumber Atomic number of element to query
/// @return True if this element can ionise, false otherwise.
function canIonise(uint atomicNumber) external pure returns(bool);
} | /// @title POWNFT Atom Reader
/// @author AnAllergyToAnalogy
/// @notice On-chain calculation atomic number and ionisation data about POWNFT Atoms. Replicates functionality done off-chain for metadata. | NatSpecSingleLine | canIonise | function canIonise(uint atomicNumber) external pure returns(bool);
| /// @notice Check if a given element has any potential ions
/// @param atomicNumber Atomic number of element to query
/// @return True if this element can ionise, false otherwise. | NatSpecSingleLine | v0.8.4+commit.c7e474f2 | {
"func_code_index": [
1955,
2026
]
} | 1,489 |
||
FuturesProtocol | FuturesProtocol.sol | 0x245d431c5f5457367c5d967e6528b37da3415e85 | Solidity | FuturesProtocol | contract FuturesProtocol is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "FUPT";
name = "Futures Protocol";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[0xD02EceAfFC3aAAed2De538fFBC32d4f8F45df247] = _totalSupply;
emit Transfer(address(0), 0xD02EceAfFC3aAAed2De538fFBC32d4f8F45df247, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | totalSupply | function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
| // ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://bfad8de18af87243eca99277041ea861b86c65095cae6f7dd0ee50e9f8f1c236 | {
"func_code_index": [
995,
1116
]
} | 1,490 |
FuturesProtocol | FuturesProtocol.sol | 0x245d431c5f5457367c5d967e6528b37da3415e85 | Solidity | FuturesProtocol | contract FuturesProtocol is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "FUPT";
name = "Futures Protocol";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[0xD02EceAfFC3aAAed2De538fFBC32d4f8F45df247] = _totalSupply;
emit Transfer(address(0), 0xD02EceAfFC3aAAed2De538fFBC32d4f8F45df247, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | balanceOf | function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
| // ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://bfad8de18af87243eca99277041ea861b86c65095cae6f7dd0ee50e9f8f1c236 | {
"func_code_index": [
1336,
1465
]
} | 1,491 |
FuturesProtocol | FuturesProtocol.sol | 0x245d431c5f5457367c5d967e6528b37da3415e85 | Solidity | FuturesProtocol | contract FuturesProtocol is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "FUPT";
name = "Futures Protocol";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[0xD02EceAfFC3aAAed2De538fFBC32d4f8F45df247] = _totalSupply;
emit Transfer(address(0), 0xD02EceAfFC3aAAed2De538fFBC32d4f8F45df247, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | transfer | function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
| // ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://bfad8de18af87243eca99277041ea861b86c65095cae6f7dd0ee50e9f8f1c236 | {
"func_code_index": [
1809,
2091
]
} | 1,492 |
FuturesProtocol | FuturesProtocol.sol | 0x245d431c5f5457367c5d967e6528b37da3415e85 | Solidity | FuturesProtocol | contract FuturesProtocol is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "FUPT";
name = "Futures Protocol";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[0xD02EceAfFC3aAAed2De538fFBC32d4f8F45df247] = _totalSupply;
emit Transfer(address(0), 0xD02EceAfFC3aAAed2De538fFBC32d4f8F45df247, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | approve | function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
| // ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://bfad8de18af87243eca99277041ea861b86c65095cae6f7dd0ee50e9f8f1c236 | {
"func_code_index": [
2599,
2812
]
} | 1,493 |
FuturesProtocol | FuturesProtocol.sol | 0x245d431c5f5457367c5d967e6528b37da3415e85 | Solidity | FuturesProtocol | contract FuturesProtocol is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "FUPT";
name = "Futures Protocol";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[0xD02EceAfFC3aAAed2De538fFBC32d4f8F45df247] = _totalSupply;
emit Transfer(address(0), 0xD02EceAfFC3aAAed2De538fFBC32d4f8F45df247, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | transferFrom | function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
| // ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://bfad8de18af87243eca99277041ea861b86c65095cae6f7dd0ee50e9f8f1c236 | {
"func_code_index": [
3343,
3706
]
} | 1,494 |
FuturesProtocol | FuturesProtocol.sol | 0x245d431c5f5457367c5d967e6528b37da3415e85 | Solidity | FuturesProtocol | contract FuturesProtocol is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "FUPT";
name = "Futures Protocol";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[0xD02EceAfFC3aAAed2De538fFBC32d4f8F45df247] = _totalSupply;
emit Transfer(address(0), 0xD02EceAfFC3aAAed2De538fFBC32d4f8F45df247, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | allowance | function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
| // ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://bfad8de18af87243eca99277041ea861b86c65095cae6f7dd0ee50e9f8f1c236 | {
"func_code_index": [
3989,
4145
]
} | 1,495 |
FuturesProtocol | FuturesProtocol.sol | 0x245d431c5f5457367c5d967e6528b37da3415e85 | Solidity | FuturesProtocol | contract FuturesProtocol is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "FUPT";
name = "Futures Protocol";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[0xD02EceAfFC3aAAed2De538fFBC32d4f8F45df247] = _totalSupply;
emit Transfer(address(0), 0xD02EceAfFC3aAAed2De538fFBC32d4f8F45df247, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | approveAndCall | function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
| // ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://bfad8de18af87243eca99277041ea861b86c65095cae6f7dd0ee50e9f8f1c236 | {
"func_code_index": [
4500,
4822
]
} | 1,496 |
FuturesProtocol | FuturesProtocol.sol | 0x245d431c5f5457367c5d967e6528b37da3415e85 | Solidity | FuturesProtocol | contract FuturesProtocol is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "FUPT";
name = "Futures Protocol";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[0xD02EceAfFC3aAAed2De538fFBC32d4f8F45df247] = _totalSupply;
emit Transfer(address(0), 0xD02EceAfFC3aAAed2De538fFBC32d4f8F45df247, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | function () public payable {
revert();
}
| // ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://bfad8de18af87243eca99277041ea861b86c65095cae6f7dd0ee50e9f8f1c236 | {
"func_code_index": [
5014,
5073
]
} | 1,497 |
|
FuturesProtocol | FuturesProtocol.sol | 0x245d431c5f5457367c5d967e6528b37da3415e85 | Solidity | FuturesProtocol | contract FuturesProtocol is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "FUPT";
name = "Futures Protocol";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[0xD02EceAfFC3aAAed2De538fFBC32d4f8F45df247] = _totalSupply;
emit Transfer(address(0), 0xD02EceAfFC3aAAed2De538fFBC32d4f8F45df247, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | // ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ---------------------------------------------------------------------------- | LineComment | transferAnyERC20Token | function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
| // ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------ | LineComment | v0.4.24+commit.e67f0147 | None | bzzr://bfad8de18af87243eca99277041ea861b86c65095cae6f7dd0ee50e9f8f1c236 | {
"func_code_index": [
5306,
5495
]
} | 1,498 |
HubiiCrowdsale | HubiiCrowdsale.sol | 0xb9aac097f4dadcd6f06761eb470346415ef28d5a | Solidity | Ownable | contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | Ownable | function Ownable() {
owner = msg.sender;
}
| /**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/ | NatSpecMultiLine | v0.4.13+commit.fb4cb1a | bzzr://81828f9ae489ed77919587782a892cfe871396b934c3819f5804c4d9732b6c1e | {
"func_code_index": [
170,
223
]
} | 1,499 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.