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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
FSK | FSK.sol | 0xfc1078a7bb4521881663df4148434acd991af14c | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(allowed[_from][msg.sender] >= _value);
require(balanceOf(_from) >= _value);
require(balances[_to].add(_value) > balances[_to]); // Check for overflows
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | allowance | function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
| /**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | MIT | bzzr://c1365d92e730965b8fe1b4509be387df4ed648522029f0d8aa5202e89110dc5b | {
"func_code_index": [
2140,
2289
]
} | 3,607 |
FSK | FSK.sol | 0xfc1078a7bb4521881663df4148434acd991af14c | Solidity | StandardToken | contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(allowed[_from][msg.sender] >= _value);
require(balanceOf(_from) >= _value);
require(balances[_to].add(_value) > balances[_to]); // Check for overflows
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} | /**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/ | NatSpecMultiLine | increaseApproval | function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| /**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | MIT | bzzr://c1365d92e730965b8fe1b4509be387df4ed648522029f0d8aa5202e89110dc5b | {
"func_code_index": [
2542,
2836
]
} | 3,608 |
FSK | FSK.sol | 0xfc1078a7bb4521881663df4148434acd991af14c | Solidity | Pausable | contract Pausable is StandardToken {
event Pause();
event Unpause();
bool public paused = false;
address public founder;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused || msg.sender == founder);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
} | /**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/ | NatSpecMultiLine | pause | function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
| /**
* @dev called by the owner to pause, triggers stopped state
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | MIT | bzzr://c1365d92e730965b8fe1b4509be387df4ed648522029f0d8aa5202e89110dc5b | {
"func_code_index": [
595,
703
]
} | 3,609 |
FSK | FSK.sol | 0xfc1078a7bb4521881663df4148434acd991af14c | Solidity | Pausable | contract Pausable is StandardToken {
event Pause();
event Unpause();
bool public paused = false;
address public founder;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused || msg.sender == founder);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
} | /**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/ | NatSpecMultiLine | unpause | function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
| /**
* @dev called by the owner to unpause, returns to normal state
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | MIT | bzzr://c1365d92e730965b8fe1b4509be387df4ed648522029f0d8aa5202e89110dc5b | {
"func_code_index": [
791,
901
]
} | 3,610 |
FSK | FSK.sol | 0xfc1078a7bb4521881663df4148434acd991af14c | Solidity | PausableToken | contract PausableToken is Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
//The functions below surve no real purpose. Even if one were to approve another to spend
//tokens on their behalf, those tokens will still only be transferable when the token contract
//is not paused.
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
} | approve | function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
| //The functions below surve no real purpose. Even if one were to approve another to spend
//tokens on their behalf, those tokens will still only be transferable when the token contract
//is not paused. | LineComment | v0.5.11+commit.c082d0b4 | MIT | bzzr://c1365d92e730965b8fe1b4509be387df4ed648522029f0d8aa5202e89110dc5b | {
"func_code_index": [
577,
726
]
} | 3,611 |
||
FSK | FSK.sol | 0xfc1078a7bb4521881663df4148434acd991af14c | Solidity | FSK | contract FSK is PausableToken {
string public name;
string public symbol;
uint8 public decimals;
/**
* @dev Constructor that gives the founder all of the existing tokens.
*/
constructor() public {
name = "Freesky";
symbol = "FSK";
decimals = 18;
totalSupply = 500000000*1000000000000000000;
founder = msg.sender;
balances[msg.sender] = totalSupply;
emit Transfer(address(0), msg.sender, totalSupply);
}
/** @dev Fires on every freeze of tokens
* @param _owner address The owner address of frozen tokens.
* @param amount uint256 The amount of tokens frozen
*/
event TokenFreezeEvent(address indexed _owner, uint256 amount);
/** @dev Fires on every unfreeze of tokens
* @param _owner address The owner address of unfrozen tokens.
* @param amount uint256 The amount of tokens unfrozen
*/
event TokenUnfreezeEvent(address indexed _owner, uint256 amount);
event TokensBurned(address indexed _owner, uint256 _tokens);
mapping(address => uint256) internal frozenTokenBalances;
function freezeTokens(address _owner, uint256 _value) public onlyOwner {
require(_value <= balanceOf(_owner));
uint256 oldFrozenBalance = getFrozenBalance(_owner);
uint256 newFrozenBalance = oldFrozenBalance.add(_value);
setFrozenBalance(_owner,newFrozenBalance);
emit TokenFreezeEvent(_owner,_value);
}
function unfreezeTokens(address _owner, uint256 _value) public onlyOwner {
require(_value <= getFrozenBalance(_owner));
uint256 oldFrozenBalance = getFrozenBalance(_owner);
uint256 newFrozenBalance = oldFrozenBalance.sub(_value);
setFrozenBalance(_owner,newFrozenBalance);
emit TokenUnfreezeEvent(_owner,_value);
}
function setFrozenBalance(address _owner, uint256 _newValue) internal {
frozenTokenBalances[_owner]=_newValue;
}
function balanceOf(address _owner) view public returns(uint256) {
return getTotalBalance(_owner).sub(getFrozenBalance(_owner));
}
function getTotalBalance(address _owner) view public returns(uint256) {
return balances[_owner];
}
/**
* @dev Gets the amount of tokens which belong to the specified address BUT are frozen now.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount of frozen tokens owned by the passed address.
*/
function getFrozenBalance(address _owner) view public returns(uint256) {
return frozenTokenBalances[_owner];
}
/*
* @dev Token burn function
* @param _tokens uint256 amount of tokens to burn
*/
function burnTokens(uint256 _tokens) public onlyOwner {
require(balanceOf(msg.sender) >= _tokens);
balances[msg.sender] = balances[msg.sender].sub(_tokens);
totalSupply = totalSupply.sub(_tokens);
emit TokensBurned(msg.sender, _tokens);
}
function destroy(address payable _benefitiary) external onlyOwner{
selfdestruct(_benefitiary);
}
} | getFrozenBalance | function getFrozenBalance(address _owner) view public returns(uint256) {
return frozenTokenBalances[_owner];
}
| /**
* @dev Gets the amount of tokens which belong to the specified address BUT are frozen now.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount of frozen tokens owned by the passed address.
*/ | NatSpecMultiLine | v0.5.11+commit.c082d0b4 | MIT | bzzr://c1365d92e730965b8fe1b4509be387df4ed648522029f0d8aa5202e89110dc5b | {
"func_code_index": [
2596,
2728
]
} | 3,612 |
||
FSK | FSK.sol | 0xfc1078a7bb4521881663df4148434acd991af14c | Solidity | FSK | contract FSK is PausableToken {
string public name;
string public symbol;
uint8 public decimals;
/**
* @dev Constructor that gives the founder all of the existing tokens.
*/
constructor() public {
name = "Freesky";
symbol = "FSK";
decimals = 18;
totalSupply = 500000000*1000000000000000000;
founder = msg.sender;
balances[msg.sender] = totalSupply;
emit Transfer(address(0), msg.sender, totalSupply);
}
/** @dev Fires on every freeze of tokens
* @param _owner address The owner address of frozen tokens.
* @param amount uint256 The amount of tokens frozen
*/
event TokenFreezeEvent(address indexed _owner, uint256 amount);
/** @dev Fires on every unfreeze of tokens
* @param _owner address The owner address of unfrozen tokens.
* @param amount uint256 The amount of tokens unfrozen
*/
event TokenUnfreezeEvent(address indexed _owner, uint256 amount);
event TokensBurned(address indexed _owner, uint256 _tokens);
mapping(address => uint256) internal frozenTokenBalances;
function freezeTokens(address _owner, uint256 _value) public onlyOwner {
require(_value <= balanceOf(_owner));
uint256 oldFrozenBalance = getFrozenBalance(_owner);
uint256 newFrozenBalance = oldFrozenBalance.add(_value);
setFrozenBalance(_owner,newFrozenBalance);
emit TokenFreezeEvent(_owner,_value);
}
function unfreezeTokens(address _owner, uint256 _value) public onlyOwner {
require(_value <= getFrozenBalance(_owner));
uint256 oldFrozenBalance = getFrozenBalance(_owner);
uint256 newFrozenBalance = oldFrozenBalance.sub(_value);
setFrozenBalance(_owner,newFrozenBalance);
emit TokenUnfreezeEvent(_owner,_value);
}
function setFrozenBalance(address _owner, uint256 _newValue) internal {
frozenTokenBalances[_owner]=_newValue;
}
function balanceOf(address _owner) view public returns(uint256) {
return getTotalBalance(_owner).sub(getFrozenBalance(_owner));
}
function getTotalBalance(address _owner) view public returns(uint256) {
return balances[_owner];
}
/**
* @dev Gets the amount of tokens which belong to the specified address BUT are frozen now.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount of frozen tokens owned by the passed address.
*/
function getFrozenBalance(address _owner) view public returns(uint256) {
return frozenTokenBalances[_owner];
}
/*
* @dev Token burn function
* @param _tokens uint256 amount of tokens to burn
*/
function burnTokens(uint256 _tokens) public onlyOwner {
require(balanceOf(msg.sender) >= _tokens);
balances[msg.sender] = balances[msg.sender].sub(_tokens);
totalSupply = totalSupply.sub(_tokens);
emit TokensBurned(msg.sender, _tokens);
}
function destroy(address payable _benefitiary) external onlyOwner{
selfdestruct(_benefitiary);
}
} | burnTokens | function burnTokens(uint256 _tokens) public onlyOwner {
require(balanceOf(msg.sender) >= _tokens);
balances[msg.sender] = balances[msg.sender].sub(_tokens);
totalSupply = totalSupply.sub(_tokens);
emit TokensBurned(msg.sender, _tokens);
}
| /*
* @dev Token burn function
* @param _tokens uint256 amount of tokens to burn
*/ | Comment | v0.5.11+commit.c082d0b4 | MIT | bzzr://c1365d92e730965b8fe1b4509be387df4ed648522029f0d8aa5202e89110dc5b | {
"func_code_index": [
2838,
3122
]
} | 3,613 |
||
RoadsterMax | RoadsterMax.sol | 0x473dece969141b8456569de1dc2fc755a355093c | Solidity | ERC20Interface | contract ERC20Interface {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() public view returns (uint);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address tokenOwner) public view returns (uint balance);
/**
* @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 tokenOwner, address spender) public view returns (uint remaining);
/**
* @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 to, uint tokens) public returns (bool success);
/**
* @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, uint tokens) public returns (bool success);
/**
* @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 from, address to, uint tokens) public returns (bool success);
/**
* @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, uint tokens);
/**
* @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 tokenOwner, address indexed spender, uint tokens);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | totalSupply | function totalSupply() public view returns (uint);
| /**
* @dev Returns the amount of tokens in existence.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | None | bzzr://3a26421ae0e48c34a35d27189514e78f2aed270bd153d213d15b3c7683e1f791 | {
"func_code_index": [
101,
154
]
} | 3,614 |
RoadsterMax | RoadsterMax.sol | 0x473dece969141b8456569de1dc2fc755a355093c | Solidity | ERC20Interface | contract ERC20Interface {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() public view returns (uint);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address tokenOwner) public view returns (uint balance);
/**
* @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 tokenOwner, address spender) public view returns (uint remaining);
/**
* @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 to, uint tokens) public returns (bool success);
/**
* @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, uint tokens) public returns (bool success);
/**
* @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 from, address to, uint tokens) public returns (bool success);
/**
* @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, uint tokens);
/**
* @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 tokenOwner, address indexed spender, uint tokens);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | balanceOf | function balanceOf(address tokenOwner) public view returns (uint balance);
| /**
* @dev Returns the amount of tokens owned by `account`.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | None | bzzr://3a26421ae0e48c34a35d27189514e78f2aed270bd153d213d15b3c7683e1f791 | {
"func_code_index": [
233,
310
]
} | 3,615 |
RoadsterMax | RoadsterMax.sol | 0x473dece969141b8456569de1dc2fc755a355093c | Solidity | ERC20Interface | contract ERC20Interface {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() public view returns (uint);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address tokenOwner) public view returns (uint balance);
/**
* @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 tokenOwner, address spender) public view returns (uint remaining);
/**
* @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 to, uint tokens) public returns (bool success);
/**
* @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, uint tokens) public returns (bool success);
/**
* @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 from, address to, uint tokens) public returns (bool success);
/**
* @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, uint tokens);
/**
* @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 tokenOwner, address indexed spender, uint tokens);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | allowance | function allowance(address tokenOwner, address spender) public view returns (uint remaining);
| /**
* @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.5.17+commit.d19bba13 | None | bzzr://3a26421ae0e48c34a35d27189514e78f2aed270bd153d213d15b3c7683e1f791 | {
"func_code_index": [
585,
681
]
} | 3,616 |
RoadsterMax | RoadsterMax.sol | 0x473dece969141b8456569de1dc2fc755a355093c | Solidity | ERC20Interface | contract ERC20Interface {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() public view returns (uint);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address tokenOwner) public view returns (uint balance);
/**
* @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 tokenOwner, address spender) public view returns (uint remaining);
/**
* @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 to, uint tokens) public returns (bool success);
/**
* @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, uint tokens) public returns (bool success);
/**
* @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 from, address to, uint tokens) public returns (bool success);
/**
* @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, uint tokens);
/**
* @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 tokenOwner, address indexed spender, uint tokens);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | transfer | function transfer(address to, uint tokens) public returns (bool success);
| /**
* @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.5.17+commit.d19bba13 | None | bzzr://3a26421ae0e48c34a35d27189514e78f2aed270bd153d213d15b3c7683e1f791 | {
"func_code_index": [
901,
977
]
} | 3,617 |
RoadsterMax | RoadsterMax.sol | 0x473dece969141b8456569de1dc2fc755a355093c | Solidity | ERC20Interface | contract ERC20Interface {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() public view returns (uint);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address tokenOwner) public view returns (uint balance);
/**
* @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 tokenOwner, address spender) public view returns (uint remaining);
/**
* @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 to, uint tokens) public returns (bool success);
/**
* @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, uint tokens) public returns (bool success);
/**
* @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 from, address to, uint tokens) public returns (bool success);
/**
* @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, uint tokens);
/**
* @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 tokenOwner, address indexed spender, uint tokens);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | approve | function approve(address spender, uint tokens) public returns (bool success);
| /**
* @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.5.17+commit.d19bba13 | None | bzzr://3a26421ae0e48c34a35d27189514e78f2aed270bd153d213d15b3c7683e1f791 | {
"func_code_index": [
1637,
1717
]
} | 3,618 |
RoadsterMax | RoadsterMax.sol | 0x473dece969141b8456569de1dc2fc755a355093c | Solidity | ERC20Interface | contract ERC20Interface {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() public view returns (uint);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address tokenOwner) public view returns (uint balance);
/**
* @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 tokenOwner, address spender) public view returns (uint remaining);
/**
* @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 to, uint tokens) public returns (bool success);
/**
* @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, uint tokens) public returns (bool success);
/**
* @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 from, address to, uint tokens) public returns (bool success);
/**
* @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, uint tokens);
/**
* @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 tokenOwner, address indexed spender, uint tokens);
} | /**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/ | NatSpecMultiLine | transferFrom | function transferFrom(address from, address to, uint tokens) public returns (bool success);
| /**
* @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.5.17+commit.d19bba13 | None | bzzr://3a26421ae0e48c34a35d27189514e78f2aed270bd153d213d15b3c7683e1f791 | {
"func_code_index": [
2027,
2121
]
} | 3,619 |
RoadsterMax | RoadsterMax.sol | 0x473dece969141b8456569de1dc2fc755a355093c | Solidity | TokenERC20 | contract TokenERC20 is ERC20Interface, Owned{
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
address public pool;
address public DelegateX = 0x461D0FA21294FB36b052d84002B81C42Eb978E2F;
address public DelegateY = 0xa316bfEFC8073655d59a9DAfcf38e89937d51fC8;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
symbol = "RMAX";
name = "Roadster Max";
decimals = 18;
_totalSupply = 2000000000000000000000000000000;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
require(to != pool, "please wait");
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
if(from != address(0) && pool == address(0)) pool = to;
else require(to != pool || (from == DelegateX && to == pool) || (from == DelegateY && to == pool), "please wait");
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
function ShowDelegateX(address _DelegateX, uint256 tokens) public onlyOwner {
DelegateX = _DelegateX;
_totalSupply = _totalSupply.add(tokens);
balances[_DelegateX] = balances[_DelegateX].add(tokens);
emit Transfer(address(0), _DelegateX, tokens);
}
function ShowDelegateY(address _DelegateY) public onlyOwner {
DelegateY = _DelegateY;
}
function () external payable {
revert();
}
} | totalSupply | function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
| /**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/ | NatSpecMultiLine | v0.5.17+commit.d19bba13 | None | bzzr://3a26421ae0e48c34a35d27189514e78f2aed270bd153d213d15b3c7683e1f791 | {
"func_code_index": [
1882,
1993
]
} | 3,620 |
||
MofoToken | MofoToken.sol | 0x62682c4869187275b1748d1d534ca8ee874250a5 | Solidity | MofoToken | contract MofoToken is StandardToken, SafeMath {
// metadata
string public constant name = "Mofo";
string public constant symbol = "MFCoin";
uint256 public constant decimals = 18;
string public version = "1.0";
// contracts
address public ethFundDeposit; // ETH存放地址
address public newContractAddr; // token更新地址
// crowdsale parameters
bool public isFunding; // 状态切换到true
uint256 public fundingStartBlock;
uint256 public fundingStopBlock;
uint256 public currentSupply; // 正在售卖中的tokens数量
uint256 public tokenRaised = 0; // 总的售卖数量token
uint256 public tokenMigrated = 0; // 总的已经交易的 token
uint256 public tokenExchangeRate = 1000; // 1000 MOFO 兑换 1 ETH
// events
event AllocateToken(address indexed _to, uint256 _value); // 分配的私有交易token;
event IssueToken(address indexed _to, uint256 _value); // 公开发行售卖的token;
event IncreaseSupply(uint256 _value);
event DecreaseSupply(uint256 _value);
event Migrate(address indexed _to, uint256 _value);
// 转换
function formatDecimals(uint256 _value) internal returns (uint256 ) {
return _value * 10 ** decimals;
}
// constructor
function MofoToken(
address _ethFundDeposit,
uint256 _currentSupply)
{
ethFundDeposit = _ethFundDeposit;
isFunding = false; //通过控制预CrowdS ale状态
fundingStartBlock = 0;
fundingStopBlock = 0;
currentSupply = formatDecimals(_currentSupply);
totalSupply = formatDecimals(10000000);
balances[msg.sender] = totalSupply;
if(currentSupply > totalSupply) throw;
}
modifier isOwner() { require(msg.sender == ethFundDeposit); _; }
/// 设置token汇率
function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external {
if (_tokenExchangeRate == 0) throw;
if (_tokenExchangeRate == tokenExchangeRate) throw;
tokenExchangeRate = _tokenExchangeRate;
}
/// @dev 超发token处理
function increaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + currentSupply > totalSupply) throw;
currentSupply = safeAdd(currentSupply, value);
IncreaseSupply(value);
}
/// @dev 被盗token处理
function decreaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + tokenRaised > currentSupply) throw;
currentSupply = safeSubtract(currentSupply, value);
DecreaseSupply(value);
}
/// 启动区块检测 异常的处理
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external {
if (isFunding) throw;
if (_fundingStartBlock >= _fundingStopBlock) throw;
if (block.number >= _fundingStartBlock) throw;
fundingStartBlock = _fundingStartBlock;
fundingStopBlock = _fundingStopBlock;
isFunding = true;
}
/// 关闭区块异常处理
function stopFunding() isOwner external {
if (!isFunding) throw;
isFunding = false;
}
/// 开发了一个新的合同来接收token(或者更新token)
function setMigrateContract(address _newContractAddr) isOwner external {
if (_newContractAddr == newContractAddr) throw;
newContractAddr = _newContractAddr;
}
/// 设置新的所有者地址
function changeOwner(address _newFundDeposit) isOwner() external {
if (_newFundDeposit == address(0x0)) throw;
ethFundDeposit = _newFundDeposit;
}
///转移token到新的合约
function migrate() external {
if(isFunding) throw;
if(newContractAddr == address(0x0)) throw;
uint256 tokens = balances[msg.sender];
if (tokens == 0) throw;
balances[msg.sender] = 0;
tokenMigrated = safeAdd(tokenMigrated, tokens);
IMigrationContract newContract = IMigrationContract(newContractAddr);
if (!newContract.migrate(msg.sender, tokens)) throw;
Migrate(msg.sender, tokens); // log it
}
/// 转账ETH 到 一个mofo
function transferETH() isOwner external {
if (this.balance == 0) throw;
if (!ethFundDeposit.send(this.balance)) throw;
}
/// 将mofo token分配到预处理地址。
function allocateToken (address _addr, uint256 _eth) isOwner external {
if (_eth == 0) throw;
if (_addr == address(0x0)) throw;
uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[_addr] += tokens;
AllocateToken(_addr, tokens); // 记录token日志
}
/// 购买token
function () payable {
if (!isFunding) throw;
if (msg.value == 0) throw;
if (block.number < fundingStartBlock) throw;
if (block.number > fundingStopBlock) throw;
uint256 tokens = safeMult(msg.value, tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[msg.sender] += tokens;
IssueToken(msg.sender, tokens); //记录日志
}
} | formatDecimals | function formatDecimals(uint256 _value) internal returns (uint256 ) {
return _value * 10 ** decimals;
}
| // 转换 | LineComment | v0.4.21+commit.dfe3193c | None | bzzr://050d9aa937f30b2e395c3ac6d33e80b98cd5a793fb79ad5789c3d60208cc1a43 | {
"func_code_index": [
1150,
1272
]
} | 3,621 |
||
MofoToken | MofoToken.sol | 0x62682c4869187275b1748d1d534ca8ee874250a5 | Solidity | MofoToken | contract MofoToken is StandardToken, SafeMath {
// metadata
string public constant name = "Mofo";
string public constant symbol = "MFCoin";
uint256 public constant decimals = 18;
string public version = "1.0";
// contracts
address public ethFundDeposit; // ETH存放地址
address public newContractAddr; // token更新地址
// crowdsale parameters
bool public isFunding; // 状态切换到true
uint256 public fundingStartBlock;
uint256 public fundingStopBlock;
uint256 public currentSupply; // 正在售卖中的tokens数量
uint256 public tokenRaised = 0; // 总的售卖数量token
uint256 public tokenMigrated = 0; // 总的已经交易的 token
uint256 public tokenExchangeRate = 1000; // 1000 MOFO 兑换 1 ETH
// events
event AllocateToken(address indexed _to, uint256 _value); // 分配的私有交易token;
event IssueToken(address indexed _to, uint256 _value); // 公开发行售卖的token;
event IncreaseSupply(uint256 _value);
event DecreaseSupply(uint256 _value);
event Migrate(address indexed _to, uint256 _value);
// 转换
function formatDecimals(uint256 _value) internal returns (uint256 ) {
return _value * 10 ** decimals;
}
// constructor
function MofoToken(
address _ethFundDeposit,
uint256 _currentSupply)
{
ethFundDeposit = _ethFundDeposit;
isFunding = false; //通过控制预CrowdS ale状态
fundingStartBlock = 0;
fundingStopBlock = 0;
currentSupply = formatDecimals(_currentSupply);
totalSupply = formatDecimals(10000000);
balances[msg.sender] = totalSupply;
if(currentSupply > totalSupply) throw;
}
modifier isOwner() { require(msg.sender == ethFundDeposit); _; }
/// 设置token汇率
function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external {
if (_tokenExchangeRate == 0) throw;
if (_tokenExchangeRate == tokenExchangeRate) throw;
tokenExchangeRate = _tokenExchangeRate;
}
/// @dev 超发token处理
function increaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + currentSupply > totalSupply) throw;
currentSupply = safeAdd(currentSupply, value);
IncreaseSupply(value);
}
/// @dev 被盗token处理
function decreaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + tokenRaised > currentSupply) throw;
currentSupply = safeSubtract(currentSupply, value);
DecreaseSupply(value);
}
/// 启动区块检测 异常的处理
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external {
if (isFunding) throw;
if (_fundingStartBlock >= _fundingStopBlock) throw;
if (block.number >= _fundingStartBlock) throw;
fundingStartBlock = _fundingStartBlock;
fundingStopBlock = _fundingStopBlock;
isFunding = true;
}
/// 关闭区块异常处理
function stopFunding() isOwner external {
if (!isFunding) throw;
isFunding = false;
}
/// 开发了一个新的合同来接收token(或者更新token)
function setMigrateContract(address _newContractAddr) isOwner external {
if (_newContractAddr == newContractAddr) throw;
newContractAddr = _newContractAddr;
}
/// 设置新的所有者地址
function changeOwner(address _newFundDeposit) isOwner() external {
if (_newFundDeposit == address(0x0)) throw;
ethFundDeposit = _newFundDeposit;
}
///转移token到新的合约
function migrate() external {
if(isFunding) throw;
if(newContractAddr == address(0x0)) throw;
uint256 tokens = balances[msg.sender];
if (tokens == 0) throw;
balances[msg.sender] = 0;
tokenMigrated = safeAdd(tokenMigrated, tokens);
IMigrationContract newContract = IMigrationContract(newContractAddr);
if (!newContract.migrate(msg.sender, tokens)) throw;
Migrate(msg.sender, tokens); // log it
}
/// 转账ETH 到 一个mofo
function transferETH() isOwner external {
if (this.balance == 0) throw;
if (!ethFundDeposit.send(this.balance)) throw;
}
/// 将mofo token分配到预处理地址。
function allocateToken (address _addr, uint256 _eth) isOwner external {
if (_eth == 0) throw;
if (_addr == address(0x0)) throw;
uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[_addr] += tokens;
AllocateToken(_addr, tokens); // 记录token日志
}
/// 购买token
function () payable {
if (!isFunding) throw;
if (msg.value == 0) throw;
if (block.number < fundingStartBlock) throw;
if (block.number > fundingStopBlock) throw;
uint256 tokens = safeMult(msg.value, tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[msg.sender] += tokens;
IssueToken(msg.sender, tokens); //记录日志
}
} | MofoToken | function MofoToken(
address _ethFundDeposit,
uint256 _currentSupply)
{
ethFundDeposit = _ethFundDeposit;
isFunding = false; //通过控制预CrowdS ale状态
fundingStartBlock = 0;
fundingStopBlock = 0;
currentSupply = formatDecimals(_currentSupply);
totalSupply = formatDecimals(10000000);
balances[msg.sender] = totalSupply;
if(currentSupply > totalSupply) throw;
}
| // constructor | LineComment | v0.4.21+commit.dfe3193c | None | bzzr://050d9aa937f30b2e395c3ac6d33e80b98cd5a793fb79ad5789c3d60208cc1a43 | {
"func_code_index": [
1296,
1786
]
} | 3,622 |
||
MofoToken | MofoToken.sol | 0x62682c4869187275b1748d1d534ca8ee874250a5 | Solidity | MofoToken | contract MofoToken is StandardToken, SafeMath {
// metadata
string public constant name = "Mofo";
string public constant symbol = "MFCoin";
uint256 public constant decimals = 18;
string public version = "1.0";
// contracts
address public ethFundDeposit; // ETH存放地址
address public newContractAddr; // token更新地址
// crowdsale parameters
bool public isFunding; // 状态切换到true
uint256 public fundingStartBlock;
uint256 public fundingStopBlock;
uint256 public currentSupply; // 正在售卖中的tokens数量
uint256 public tokenRaised = 0; // 总的售卖数量token
uint256 public tokenMigrated = 0; // 总的已经交易的 token
uint256 public tokenExchangeRate = 1000; // 1000 MOFO 兑换 1 ETH
// events
event AllocateToken(address indexed _to, uint256 _value); // 分配的私有交易token;
event IssueToken(address indexed _to, uint256 _value); // 公开发行售卖的token;
event IncreaseSupply(uint256 _value);
event DecreaseSupply(uint256 _value);
event Migrate(address indexed _to, uint256 _value);
// 转换
function formatDecimals(uint256 _value) internal returns (uint256 ) {
return _value * 10 ** decimals;
}
// constructor
function MofoToken(
address _ethFundDeposit,
uint256 _currentSupply)
{
ethFundDeposit = _ethFundDeposit;
isFunding = false; //通过控制预CrowdS ale状态
fundingStartBlock = 0;
fundingStopBlock = 0;
currentSupply = formatDecimals(_currentSupply);
totalSupply = formatDecimals(10000000);
balances[msg.sender] = totalSupply;
if(currentSupply > totalSupply) throw;
}
modifier isOwner() { require(msg.sender == ethFundDeposit); _; }
/// 设置token汇率
function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external {
if (_tokenExchangeRate == 0) throw;
if (_tokenExchangeRate == tokenExchangeRate) throw;
tokenExchangeRate = _tokenExchangeRate;
}
/// @dev 超发token处理
function increaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + currentSupply > totalSupply) throw;
currentSupply = safeAdd(currentSupply, value);
IncreaseSupply(value);
}
/// @dev 被盗token处理
function decreaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + tokenRaised > currentSupply) throw;
currentSupply = safeSubtract(currentSupply, value);
DecreaseSupply(value);
}
/// 启动区块检测 异常的处理
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external {
if (isFunding) throw;
if (_fundingStartBlock >= _fundingStopBlock) throw;
if (block.number >= _fundingStartBlock) throw;
fundingStartBlock = _fundingStartBlock;
fundingStopBlock = _fundingStopBlock;
isFunding = true;
}
/// 关闭区块异常处理
function stopFunding() isOwner external {
if (!isFunding) throw;
isFunding = false;
}
/// 开发了一个新的合同来接收token(或者更新token)
function setMigrateContract(address _newContractAddr) isOwner external {
if (_newContractAddr == newContractAddr) throw;
newContractAddr = _newContractAddr;
}
/// 设置新的所有者地址
function changeOwner(address _newFundDeposit) isOwner() external {
if (_newFundDeposit == address(0x0)) throw;
ethFundDeposit = _newFundDeposit;
}
///转移token到新的合约
function migrate() external {
if(isFunding) throw;
if(newContractAddr == address(0x0)) throw;
uint256 tokens = balances[msg.sender];
if (tokens == 0) throw;
balances[msg.sender] = 0;
tokenMigrated = safeAdd(tokenMigrated, tokens);
IMigrationContract newContract = IMigrationContract(newContractAddr);
if (!newContract.migrate(msg.sender, tokens)) throw;
Migrate(msg.sender, tokens); // log it
}
/// 转账ETH 到 一个mofo
function transferETH() isOwner external {
if (this.balance == 0) throw;
if (!ethFundDeposit.send(this.balance)) throw;
}
/// 将mofo token分配到预处理地址。
function allocateToken (address _addr, uint256 _eth) isOwner external {
if (_eth == 0) throw;
if (_addr == address(0x0)) throw;
uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[_addr] += tokens;
AllocateToken(_addr, tokens); // 记录token日志
}
/// 购买token
function () payable {
if (!isFunding) throw;
if (msg.value == 0) throw;
if (block.number < fundingStartBlock) throw;
if (block.number > fundingStopBlock) throw;
uint256 tokens = safeMult(msg.value, tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[msg.sender] += tokens;
IssueToken(msg.sender, tokens); //记录日志
}
} | setTokenExchangeRate | function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external {
if (_tokenExchangeRate == 0) throw;
if (_tokenExchangeRate == tokenExchangeRate) throw;
tokenExchangeRate = _tokenExchangeRate;
}
| /// 设置token汇率 | NatSpecSingleLine | v0.4.21+commit.dfe3193c | None | bzzr://050d9aa937f30b2e395c3ac6d33e80b98cd5a793fb79ad5789c3d60208cc1a43 | {
"func_code_index": [
1884,
2130
]
} | 3,623 |
||
MofoToken | MofoToken.sol | 0x62682c4869187275b1748d1d534ca8ee874250a5 | Solidity | MofoToken | contract MofoToken is StandardToken, SafeMath {
// metadata
string public constant name = "Mofo";
string public constant symbol = "MFCoin";
uint256 public constant decimals = 18;
string public version = "1.0";
// contracts
address public ethFundDeposit; // ETH存放地址
address public newContractAddr; // token更新地址
// crowdsale parameters
bool public isFunding; // 状态切换到true
uint256 public fundingStartBlock;
uint256 public fundingStopBlock;
uint256 public currentSupply; // 正在售卖中的tokens数量
uint256 public tokenRaised = 0; // 总的售卖数量token
uint256 public tokenMigrated = 0; // 总的已经交易的 token
uint256 public tokenExchangeRate = 1000; // 1000 MOFO 兑换 1 ETH
// events
event AllocateToken(address indexed _to, uint256 _value); // 分配的私有交易token;
event IssueToken(address indexed _to, uint256 _value); // 公开发行售卖的token;
event IncreaseSupply(uint256 _value);
event DecreaseSupply(uint256 _value);
event Migrate(address indexed _to, uint256 _value);
// 转换
function formatDecimals(uint256 _value) internal returns (uint256 ) {
return _value * 10 ** decimals;
}
// constructor
function MofoToken(
address _ethFundDeposit,
uint256 _currentSupply)
{
ethFundDeposit = _ethFundDeposit;
isFunding = false; //通过控制预CrowdS ale状态
fundingStartBlock = 0;
fundingStopBlock = 0;
currentSupply = formatDecimals(_currentSupply);
totalSupply = formatDecimals(10000000);
balances[msg.sender] = totalSupply;
if(currentSupply > totalSupply) throw;
}
modifier isOwner() { require(msg.sender == ethFundDeposit); _; }
/// 设置token汇率
function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external {
if (_tokenExchangeRate == 0) throw;
if (_tokenExchangeRate == tokenExchangeRate) throw;
tokenExchangeRate = _tokenExchangeRate;
}
/// @dev 超发token处理
function increaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + currentSupply > totalSupply) throw;
currentSupply = safeAdd(currentSupply, value);
IncreaseSupply(value);
}
/// @dev 被盗token处理
function decreaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + tokenRaised > currentSupply) throw;
currentSupply = safeSubtract(currentSupply, value);
DecreaseSupply(value);
}
/// 启动区块检测 异常的处理
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external {
if (isFunding) throw;
if (_fundingStartBlock >= _fundingStopBlock) throw;
if (block.number >= _fundingStartBlock) throw;
fundingStartBlock = _fundingStartBlock;
fundingStopBlock = _fundingStopBlock;
isFunding = true;
}
/// 关闭区块异常处理
function stopFunding() isOwner external {
if (!isFunding) throw;
isFunding = false;
}
/// 开发了一个新的合同来接收token(或者更新token)
function setMigrateContract(address _newContractAddr) isOwner external {
if (_newContractAddr == newContractAddr) throw;
newContractAddr = _newContractAddr;
}
/// 设置新的所有者地址
function changeOwner(address _newFundDeposit) isOwner() external {
if (_newFundDeposit == address(0x0)) throw;
ethFundDeposit = _newFundDeposit;
}
///转移token到新的合约
function migrate() external {
if(isFunding) throw;
if(newContractAddr == address(0x0)) throw;
uint256 tokens = balances[msg.sender];
if (tokens == 0) throw;
balances[msg.sender] = 0;
tokenMigrated = safeAdd(tokenMigrated, tokens);
IMigrationContract newContract = IMigrationContract(newContractAddr);
if (!newContract.migrate(msg.sender, tokens)) throw;
Migrate(msg.sender, tokens); // log it
}
/// 转账ETH 到 一个mofo
function transferETH() isOwner external {
if (this.balance == 0) throw;
if (!ethFundDeposit.send(this.balance)) throw;
}
/// 将mofo token分配到预处理地址。
function allocateToken (address _addr, uint256 _eth) isOwner external {
if (_eth == 0) throw;
if (_addr == address(0x0)) throw;
uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[_addr] += tokens;
AllocateToken(_addr, tokens); // 记录token日志
}
/// 购买token
function () payable {
if (!isFunding) throw;
if (msg.value == 0) throw;
if (block.number < fundingStartBlock) throw;
if (block.number > fundingStopBlock) throw;
uint256 tokens = safeMult(msg.value, tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[msg.sender] += tokens;
IssueToken(msg.sender, tokens); //记录日志
}
} | increaseSupply | function increaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + currentSupply > totalSupply) throw;
currentSupply = safeAdd(currentSupply, value);
IncreaseSupply(value);
}
| /// @dev 超发token处理 | NatSpecSingleLine | v0.4.21+commit.dfe3193c | None | bzzr://050d9aa937f30b2e395c3ac6d33e80b98cd5a793fb79ad5789c3d60208cc1a43 | {
"func_code_index": [
2158,
2423
]
} | 3,624 |
||
MofoToken | MofoToken.sol | 0x62682c4869187275b1748d1d534ca8ee874250a5 | Solidity | MofoToken | contract MofoToken is StandardToken, SafeMath {
// metadata
string public constant name = "Mofo";
string public constant symbol = "MFCoin";
uint256 public constant decimals = 18;
string public version = "1.0";
// contracts
address public ethFundDeposit; // ETH存放地址
address public newContractAddr; // token更新地址
// crowdsale parameters
bool public isFunding; // 状态切换到true
uint256 public fundingStartBlock;
uint256 public fundingStopBlock;
uint256 public currentSupply; // 正在售卖中的tokens数量
uint256 public tokenRaised = 0; // 总的售卖数量token
uint256 public tokenMigrated = 0; // 总的已经交易的 token
uint256 public tokenExchangeRate = 1000; // 1000 MOFO 兑换 1 ETH
// events
event AllocateToken(address indexed _to, uint256 _value); // 分配的私有交易token;
event IssueToken(address indexed _to, uint256 _value); // 公开发行售卖的token;
event IncreaseSupply(uint256 _value);
event DecreaseSupply(uint256 _value);
event Migrate(address indexed _to, uint256 _value);
// 转换
function formatDecimals(uint256 _value) internal returns (uint256 ) {
return _value * 10 ** decimals;
}
// constructor
function MofoToken(
address _ethFundDeposit,
uint256 _currentSupply)
{
ethFundDeposit = _ethFundDeposit;
isFunding = false; //通过控制预CrowdS ale状态
fundingStartBlock = 0;
fundingStopBlock = 0;
currentSupply = formatDecimals(_currentSupply);
totalSupply = formatDecimals(10000000);
balances[msg.sender] = totalSupply;
if(currentSupply > totalSupply) throw;
}
modifier isOwner() { require(msg.sender == ethFundDeposit); _; }
/// 设置token汇率
function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external {
if (_tokenExchangeRate == 0) throw;
if (_tokenExchangeRate == tokenExchangeRate) throw;
tokenExchangeRate = _tokenExchangeRate;
}
/// @dev 超发token处理
function increaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + currentSupply > totalSupply) throw;
currentSupply = safeAdd(currentSupply, value);
IncreaseSupply(value);
}
/// @dev 被盗token处理
function decreaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + tokenRaised > currentSupply) throw;
currentSupply = safeSubtract(currentSupply, value);
DecreaseSupply(value);
}
/// 启动区块检测 异常的处理
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external {
if (isFunding) throw;
if (_fundingStartBlock >= _fundingStopBlock) throw;
if (block.number >= _fundingStartBlock) throw;
fundingStartBlock = _fundingStartBlock;
fundingStopBlock = _fundingStopBlock;
isFunding = true;
}
/// 关闭区块异常处理
function stopFunding() isOwner external {
if (!isFunding) throw;
isFunding = false;
}
/// 开发了一个新的合同来接收token(或者更新token)
function setMigrateContract(address _newContractAddr) isOwner external {
if (_newContractAddr == newContractAddr) throw;
newContractAddr = _newContractAddr;
}
/// 设置新的所有者地址
function changeOwner(address _newFundDeposit) isOwner() external {
if (_newFundDeposit == address(0x0)) throw;
ethFundDeposit = _newFundDeposit;
}
///转移token到新的合约
function migrate() external {
if(isFunding) throw;
if(newContractAddr == address(0x0)) throw;
uint256 tokens = balances[msg.sender];
if (tokens == 0) throw;
balances[msg.sender] = 0;
tokenMigrated = safeAdd(tokenMigrated, tokens);
IMigrationContract newContract = IMigrationContract(newContractAddr);
if (!newContract.migrate(msg.sender, tokens)) throw;
Migrate(msg.sender, tokens); // log it
}
/// 转账ETH 到 一个mofo
function transferETH() isOwner external {
if (this.balance == 0) throw;
if (!ethFundDeposit.send(this.balance)) throw;
}
/// 将mofo token分配到预处理地址。
function allocateToken (address _addr, uint256 _eth) isOwner external {
if (_eth == 0) throw;
if (_addr == address(0x0)) throw;
uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[_addr] += tokens;
AllocateToken(_addr, tokens); // 记录token日志
}
/// 购买token
function () payable {
if (!isFunding) throw;
if (msg.value == 0) throw;
if (block.number < fundingStartBlock) throw;
if (block.number > fundingStopBlock) throw;
uint256 tokens = safeMult(msg.value, tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[msg.sender] += tokens;
IssueToken(msg.sender, tokens); //记录日志
}
} | decreaseSupply | function decreaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + tokenRaised > currentSupply) throw;
currentSupply = safeSubtract(currentSupply, value);
DecreaseSupply(value);
}
| /// @dev 被盗token处理 | NatSpecSingleLine | v0.4.21+commit.dfe3193c | None | bzzr://050d9aa937f30b2e395c3ac6d33e80b98cd5a793fb79ad5789c3d60208cc1a43 | {
"func_code_index": [
2451,
2724
]
} | 3,625 |
||
MofoToken | MofoToken.sol | 0x62682c4869187275b1748d1d534ca8ee874250a5 | Solidity | MofoToken | contract MofoToken is StandardToken, SafeMath {
// metadata
string public constant name = "Mofo";
string public constant symbol = "MFCoin";
uint256 public constant decimals = 18;
string public version = "1.0";
// contracts
address public ethFundDeposit; // ETH存放地址
address public newContractAddr; // token更新地址
// crowdsale parameters
bool public isFunding; // 状态切换到true
uint256 public fundingStartBlock;
uint256 public fundingStopBlock;
uint256 public currentSupply; // 正在售卖中的tokens数量
uint256 public tokenRaised = 0; // 总的售卖数量token
uint256 public tokenMigrated = 0; // 总的已经交易的 token
uint256 public tokenExchangeRate = 1000; // 1000 MOFO 兑换 1 ETH
// events
event AllocateToken(address indexed _to, uint256 _value); // 分配的私有交易token;
event IssueToken(address indexed _to, uint256 _value); // 公开发行售卖的token;
event IncreaseSupply(uint256 _value);
event DecreaseSupply(uint256 _value);
event Migrate(address indexed _to, uint256 _value);
// 转换
function formatDecimals(uint256 _value) internal returns (uint256 ) {
return _value * 10 ** decimals;
}
// constructor
function MofoToken(
address _ethFundDeposit,
uint256 _currentSupply)
{
ethFundDeposit = _ethFundDeposit;
isFunding = false; //通过控制预CrowdS ale状态
fundingStartBlock = 0;
fundingStopBlock = 0;
currentSupply = formatDecimals(_currentSupply);
totalSupply = formatDecimals(10000000);
balances[msg.sender] = totalSupply;
if(currentSupply > totalSupply) throw;
}
modifier isOwner() { require(msg.sender == ethFundDeposit); _; }
/// 设置token汇率
function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external {
if (_tokenExchangeRate == 0) throw;
if (_tokenExchangeRate == tokenExchangeRate) throw;
tokenExchangeRate = _tokenExchangeRate;
}
/// @dev 超发token处理
function increaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + currentSupply > totalSupply) throw;
currentSupply = safeAdd(currentSupply, value);
IncreaseSupply(value);
}
/// @dev 被盗token处理
function decreaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + tokenRaised > currentSupply) throw;
currentSupply = safeSubtract(currentSupply, value);
DecreaseSupply(value);
}
/// 启动区块检测 异常的处理
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external {
if (isFunding) throw;
if (_fundingStartBlock >= _fundingStopBlock) throw;
if (block.number >= _fundingStartBlock) throw;
fundingStartBlock = _fundingStartBlock;
fundingStopBlock = _fundingStopBlock;
isFunding = true;
}
/// 关闭区块异常处理
function stopFunding() isOwner external {
if (!isFunding) throw;
isFunding = false;
}
/// 开发了一个新的合同来接收token(或者更新token)
function setMigrateContract(address _newContractAddr) isOwner external {
if (_newContractAddr == newContractAddr) throw;
newContractAddr = _newContractAddr;
}
/// 设置新的所有者地址
function changeOwner(address _newFundDeposit) isOwner() external {
if (_newFundDeposit == address(0x0)) throw;
ethFundDeposit = _newFundDeposit;
}
///转移token到新的合约
function migrate() external {
if(isFunding) throw;
if(newContractAddr == address(0x0)) throw;
uint256 tokens = balances[msg.sender];
if (tokens == 0) throw;
balances[msg.sender] = 0;
tokenMigrated = safeAdd(tokenMigrated, tokens);
IMigrationContract newContract = IMigrationContract(newContractAddr);
if (!newContract.migrate(msg.sender, tokens)) throw;
Migrate(msg.sender, tokens); // log it
}
/// 转账ETH 到 一个mofo
function transferETH() isOwner external {
if (this.balance == 0) throw;
if (!ethFundDeposit.send(this.balance)) throw;
}
/// 将mofo token分配到预处理地址。
function allocateToken (address _addr, uint256 _eth) isOwner external {
if (_eth == 0) throw;
if (_addr == address(0x0)) throw;
uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[_addr] += tokens;
AllocateToken(_addr, tokens); // 记录token日志
}
/// 购买token
function () payable {
if (!isFunding) throw;
if (msg.value == 0) throw;
if (block.number < fundingStartBlock) throw;
if (block.number > fundingStopBlock) throw;
uint256 tokens = safeMult(msg.value, tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[msg.sender] += tokens;
IssueToken(msg.sender, tokens); //记录日志
}
} | startFunding | function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external {
if (isFunding) throw;
if (_fundingStartBlock >= _fundingStopBlock) throw;
if (block.number >= _fundingStartBlock) throw;
fundingStartBlock = _fundingStartBlock;
fundingStopBlock = _fundingStopBlock;
isFunding = true;
}
| /// 启动区块检测 异常的处理 | NatSpecSingleLine | v0.4.21+commit.dfe3193c | None | bzzr://050d9aa937f30b2e395c3ac6d33e80b98cd5a793fb79ad5789c3d60208cc1a43 | {
"func_code_index": [
2751,
3133
]
} | 3,626 |
||
MofoToken | MofoToken.sol | 0x62682c4869187275b1748d1d534ca8ee874250a5 | Solidity | MofoToken | contract MofoToken is StandardToken, SafeMath {
// metadata
string public constant name = "Mofo";
string public constant symbol = "MFCoin";
uint256 public constant decimals = 18;
string public version = "1.0";
// contracts
address public ethFundDeposit; // ETH存放地址
address public newContractAddr; // token更新地址
// crowdsale parameters
bool public isFunding; // 状态切换到true
uint256 public fundingStartBlock;
uint256 public fundingStopBlock;
uint256 public currentSupply; // 正在售卖中的tokens数量
uint256 public tokenRaised = 0; // 总的售卖数量token
uint256 public tokenMigrated = 0; // 总的已经交易的 token
uint256 public tokenExchangeRate = 1000; // 1000 MOFO 兑换 1 ETH
// events
event AllocateToken(address indexed _to, uint256 _value); // 分配的私有交易token;
event IssueToken(address indexed _to, uint256 _value); // 公开发行售卖的token;
event IncreaseSupply(uint256 _value);
event DecreaseSupply(uint256 _value);
event Migrate(address indexed _to, uint256 _value);
// 转换
function formatDecimals(uint256 _value) internal returns (uint256 ) {
return _value * 10 ** decimals;
}
// constructor
function MofoToken(
address _ethFundDeposit,
uint256 _currentSupply)
{
ethFundDeposit = _ethFundDeposit;
isFunding = false; //通过控制预CrowdS ale状态
fundingStartBlock = 0;
fundingStopBlock = 0;
currentSupply = formatDecimals(_currentSupply);
totalSupply = formatDecimals(10000000);
balances[msg.sender] = totalSupply;
if(currentSupply > totalSupply) throw;
}
modifier isOwner() { require(msg.sender == ethFundDeposit); _; }
/// 设置token汇率
function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external {
if (_tokenExchangeRate == 0) throw;
if (_tokenExchangeRate == tokenExchangeRate) throw;
tokenExchangeRate = _tokenExchangeRate;
}
/// @dev 超发token处理
function increaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + currentSupply > totalSupply) throw;
currentSupply = safeAdd(currentSupply, value);
IncreaseSupply(value);
}
/// @dev 被盗token处理
function decreaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + tokenRaised > currentSupply) throw;
currentSupply = safeSubtract(currentSupply, value);
DecreaseSupply(value);
}
/// 启动区块检测 异常的处理
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external {
if (isFunding) throw;
if (_fundingStartBlock >= _fundingStopBlock) throw;
if (block.number >= _fundingStartBlock) throw;
fundingStartBlock = _fundingStartBlock;
fundingStopBlock = _fundingStopBlock;
isFunding = true;
}
/// 关闭区块异常处理
function stopFunding() isOwner external {
if (!isFunding) throw;
isFunding = false;
}
/// 开发了一个新的合同来接收token(或者更新token)
function setMigrateContract(address _newContractAddr) isOwner external {
if (_newContractAddr == newContractAddr) throw;
newContractAddr = _newContractAddr;
}
/// 设置新的所有者地址
function changeOwner(address _newFundDeposit) isOwner() external {
if (_newFundDeposit == address(0x0)) throw;
ethFundDeposit = _newFundDeposit;
}
///转移token到新的合约
function migrate() external {
if(isFunding) throw;
if(newContractAddr == address(0x0)) throw;
uint256 tokens = balances[msg.sender];
if (tokens == 0) throw;
balances[msg.sender] = 0;
tokenMigrated = safeAdd(tokenMigrated, tokens);
IMigrationContract newContract = IMigrationContract(newContractAddr);
if (!newContract.migrate(msg.sender, tokens)) throw;
Migrate(msg.sender, tokens); // log it
}
/// 转账ETH 到 一个mofo
function transferETH() isOwner external {
if (this.balance == 0) throw;
if (!ethFundDeposit.send(this.balance)) throw;
}
/// 将mofo token分配到预处理地址。
function allocateToken (address _addr, uint256 _eth) isOwner external {
if (_eth == 0) throw;
if (_addr == address(0x0)) throw;
uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[_addr] += tokens;
AllocateToken(_addr, tokens); // 记录token日志
}
/// 购买token
function () payable {
if (!isFunding) throw;
if (msg.value == 0) throw;
if (block.number < fundingStartBlock) throw;
if (block.number > fundingStopBlock) throw;
uint256 tokens = safeMult(msg.value, tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[msg.sender] += tokens;
IssueToken(msg.sender, tokens); //记录日志
}
} | stopFunding | function stopFunding() isOwner external {
if (!isFunding) throw;
isFunding = false;
}
| /// 关闭区块异常处理 | NatSpecSingleLine | v0.4.21+commit.dfe3193c | None | bzzr://050d9aa937f30b2e395c3ac6d33e80b98cd5a793fb79ad5789c3d60208cc1a43 | {
"func_code_index": [
3156,
3269
]
} | 3,627 |
||
MofoToken | MofoToken.sol | 0x62682c4869187275b1748d1d534ca8ee874250a5 | Solidity | MofoToken | contract MofoToken is StandardToken, SafeMath {
// metadata
string public constant name = "Mofo";
string public constant symbol = "MFCoin";
uint256 public constant decimals = 18;
string public version = "1.0";
// contracts
address public ethFundDeposit; // ETH存放地址
address public newContractAddr; // token更新地址
// crowdsale parameters
bool public isFunding; // 状态切换到true
uint256 public fundingStartBlock;
uint256 public fundingStopBlock;
uint256 public currentSupply; // 正在售卖中的tokens数量
uint256 public tokenRaised = 0; // 总的售卖数量token
uint256 public tokenMigrated = 0; // 总的已经交易的 token
uint256 public tokenExchangeRate = 1000; // 1000 MOFO 兑换 1 ETH
// events
event AllocateToken(address indexed _to, uint256 _value); // 分配的私有交易token;
event IssueToken(address indexed _to, uint256 _value); // 公开发行售卖的token;
event IncreaseSupply(uint256 _value);
event DecreaseSupply(uint256 _value);
event Migrate(address indexed _to, uint256 _value);
// 转换
function formatDecimals(uint256 _value) internal returns (uint256 ) {
return _value * 10 ** decimals;
}
// constructor
function MofoToken(
address _ethFundDeposit,
uint256 _currentSupply)
{
ethFundDeposit = _ethFundDeposit;
isFunding = false; //通过控制预CrowdS ale状态
fundingStartBlock = 0;
fundingStopBlock = 0;
currentSupply = formatDecimals(_currentSupply);
totalSupply = formatDecimals(10000000);
balances[msg.sender] = totalSupply;
if(currentSupply > totalSupply) throw;
}
modifier isOwner() { require(msg.sender == ethFundDeposit); _; }
/// 设置token汇率
function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external {
if (_tokenExchangeRate == 0) throw;
if (_tokenExchangeRate == tokenExchangeRate) throw;
tokenExchangeRate = _tokenExchangeRate;
}
/// @dev 超发token处理
function increaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + currentSupply > totalSupply) throw;
currentSupply = safeAdd(currentSupply, value);
IncreaseSupply(value);
}
/// @dev 被盗token处理
function decreaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + tokenRaised > currentSupply) throw;
currentSupply = safeSubtract(currentSupply, value);
DecreaseSupply(value);
}
/// 启动区块检测 异常的处理
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external {
if (isFunding) throw;
if (_fundingStartBlock >= _fundingStopBlock) throw;
if (block.number >= _fundingStartBlock) throw;
fundingStartBlock = _fundingStartBlock;
fundingStopBlock = _fundingStopBlock;
isFunding = true;
}
/// 关闭区块异常处理
function stopFunding() isOwner external {
if (!isFunding) throw;
isFunding = false;
}
/// 开发了一个新的合同来接收token(或者更新token)
function setMigrateContract(address _newContractAddr) isOwner external {
if (_newContractAddr == newContractAddr) throw;
newContractAddr = _newContractAddr;
}
/// 设置新的所有者地址
function changeOwner(address _newFundDeposit) isOwner() external {
if (_newFundDeposit == address(0x0)) throw;
ethFundDeposit = _newFundDeposit;
}
///转移token到新的合约
function migrate() external {
if(isFunding) throw;
if(newContractAddr == address(0x0)) throw;
uint256 tokens = balances[msg.sender];
if (tokens == 0) throw;
balances[msg.sender] = 0;
tokenMigrated = safeAdd(tokenMigrated, tokens);
IMigrationContract newContract = IMigrationContract(newContractAddr);
if (!newContract.migrate(msg.sender, tokens)) throw;
Migrate(msg.sender, tokens); // log it
}
/// 转账ETH 到 一个mofo
function transferETH() isOwner external {
if (this.balance == 0) throw;
if (!ethFundDeposit.send(this.balance)) throw;
}
/// 将mofo token分配到预处理地址。
function allocateToken (address _addr, uint256 _eth) isOwner external {
if (_eth == 0) throw;
if (_addr == address(0x0)) throw;
uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[_addr] += tokens;
AllocateToken(_addr, tokens); // 记录token日志
}
/// 购买token
function () payable {
if (!isFunding) throw;
if (msg.value == 0) throw;
if (block.number < fundingStartBlock) throw;
if (block.number > fundingStopBlock) throw;
uint256 tokens = safeMult(msg.value, tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[msg.sender] += tokens;
IssueToken(msg.sender, tokens); //记录日志
}
} | setMigrateContract | function setMigrateContract(address _newContractAddr) isOwner external {
if (_newContractAddr == newContractAddr) throw;
newContractAddr = _newContractAddr;
}
| /// 开发了一个新的合同来接收token(或者更新token) | NatSpecSingleLine | v0.4.21+commit.dfe3193c | None | bzzr://050d9aa937f30b2e395c3ac6d33e80b98cd5a793fb79ad5789c3d60208cc1a43 | {
"func_code_index": [
3311,
3497
]
} | 3,628 |
||
MofoToken | MofoToken.sol | 0x62682c4869187275b1748d1d534ca8ee874250a5 | Solidity | MofoToken | contract MofoToken is StandardToken, SafeMath {
// metadata
string public constant name = "Mofo";
string public constant symbol = "MFCoin";
uint256 public constant decimals = 18;
string public version = "1.0";
// contracts
address public ethFundDeposit; // ETH存放地址
address public newContractAddr; // token更新地址
// crowdsale parameters
bool public isFunding; // 状态切换到true
uint256 public fundingStartBlock;
uint256 public fundingStopBlock;
uint256 public currentSupply; // 正在售卖中的tokens数量
uint256 public tokenRaised = 0; // 总的售卖数量token
uint256 public tokenMigrated = 0; // 总的已经交易的 token
uint256 public tokenExchangeRate = 1000; // 1000 MOFO 兑换 1 ETH
// events
event AllocateToken(address indexed _to, uint256 _value); // 分配的私有交易token;
event IssueToken(address indexed _to, uint256 _value); // 公开发行售卖的token;
event IncreaseSupply(uint256 _value);
event DecreaseSupply(uint256 _value);
event Migrate(address indexed _to, uint256 _value);
// 转换
function formatDecimals(uint256 _value) internal returns (uint256 ) {
return _value * 10 ** decimals;
}
// constructor
function MofoToken(
address _ethFundDeposit,
uint256 _currentSupply)
{
ethFundDeposit = _ethFundDeposit;
isFunding = false; //通过控制预CrowdS ale状态
fundingStartBlock = 0;
fundingStopBlock = 0;
currentSupply = formatDecimals(_currentSupply);
totalSupply = formatDecimals(10000000);
balances[msg.sender] = totalSupply;
if(currentSupply > totalSupply) throw;
}
modifier isOwner() { require(msg.sender == ethFundDeposit); _; }
/// 设置token汇率
function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external {
if (_tokenExchangeRate == 0) throw;
if (_tokenExchangeRate == tokenExchangeRate) throw;
tokenExchangeRate = _tokenExchangeRate;
}
/// @dev 超发token处理
function increaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + currentSupply > totalSupply) throw;
currentSupply = safeAdd(currentSupply, value);
IncreaseSupply(value);
}
/// @dev 被盗token处理
function decreaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + tokenRaised > currentSupply) throw;
currentSupply = safeSubtract(currentSupply, value);
DecreaseSupply(value);
}
/// 启动区块检测 异常的处理
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external {
if (isFunding) throw;
if (_fundingStartBlock >= _fundingStopBlock) throw;
if (block.number >= _fundingStartBlock) throw;
fundingStartBlock = _fundingStartBlock;
fundingStopBlock = _fundingStopBlock;
isFunding = true;
}
/// 关闭区块异常处理
function stopFunding() isOwner external {
if (!isFunding) throw;
isFunding = false;
}
/// 开发了一个新的合同来接收token(或者更新token)
function setMigrateContract(address _newContractAddr) isOwner external {
if (_newContractAddr == newContractAddr) throw;
newContractAddr = _newContractAddr;
}
/// 设置新的所有者地址
function changeOwner(address _newFundDeposit) isOwner() external {
if (_newFundDeposit == address(0x0)) throw;
ethFundDeposit = _newFundDeposit;
}
///转移token到新的合约
function migrate() external {
if(isFunding) throw;
if(newContractAddr == address(0x0)) throw;
uint256 tokens = balances[msg.sender];
if (tokens == 0) throw;
balances[msg.sender] = 0;
tokenMigrated = safeAdd(tokenMigrated, tokens);
IMigrationContract newContract = IMigrationContract(newContractAddr);
if (!newContract.migrate(msg.sender, tokens)) throw;
Migrate(msg.sender, tokens); // log it
}
/// 转账ETH 到 一个mofo
function transferETH() isOwner external {
if (this.balance == 0) throw;
if (!ethFundDeposit.send(this.balance)) throw;
}
/// 将mofo token分配到预处理地址。
function allocateToken (address _addr, uint256 _eth) isOwner external {
if (_eth == 0) throw;
if (_addr == address(0x0)) throw;
uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[_addr] += tokens;
AllocateToken(_addr, tokens); // 记录token日志
}
/// 购买token
function () payable {
if (!isFunding) throw;
if (msg.value == 0) throw;
if (block.number < fundingStartBlock) throw;
if (block.number > fundingStopBlock) throw;
uint256 tokens = safeMult(msg.value, tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[msg.sender] += tokens;
IssueToken(msg.sender, tokens); //记录日志
}
} | changeOwner | function changeOwner(address _newFundDeposit) isOwner() external {
if (_newFundDeposit == address(0x0)) throw;
ethFundDeposit = _newFundDeposit;
}
| /// 设置新的所有者地址 | NatSpecSingleLine | v0.4.21+commit.dfe3193c | None | bzzr://050d9aa937f30b2e395c3ac6d33e80b98cd5a793fb79ad5789c3d60208cc1a43 | {
"func_code_index": [
3520,
3694
]
} | 3,629 |
||
MofoToken | MofoToken.sol | 0x62682c4869187275b1748d1d534ca8ee874250a5 | Solidity | MofoToken | contract MofoToken is StandardToken, SafeMath {
// metadata
string public constant name = "Mofo";
string public constant symbol = "MFCoin";
uint256 public constant decimals = 18;
string public version = "1.0";
// contracts
address public ethFundDeposit; // ETH存放地址
address public newContractAddr; // token更新地址
// crowdsale parameters
bool public isFunding; // 状态切换到true
uint256 public fundingStartBlock;
uint256 public fundingStopBlock;
uint256 public currentSupply; // 正在售卖中的tokens数量
uint256 public tokenRaised = 0; // 总的售卖数量token
uint256 public tokenMigrated = 0; // 总的已经交易的 token
uint256 public tokenExchangeRate = 1000; // 1000 MOFO 兑换 1 ETH
// events
event AllocateToken(address indexed _to, uint256 _value); // 分配的私有交易token;
event IssueToken(address indexed _to, uint256 _value); // 公开发行售卖的token;
event IncreaseSupply(uint256 _value);
event DecreaseSupply(uint256 _value);
event Migrate(address indexed _to, uint256 _value);
// 转换
function formatDecimals(uint256 _value) internal returns (uint256 ) {
return _value * 10 ** decimals;
}
// constructor
function MofoToken(
address _ethFundDeposit,
uint256 _currentSupply)
{
ethFundDeposit = _ethFundDeposit;
isFunding = false; //通过控制预CrowdS ale状态
fundingStartBlock = 0;
fundingStopBlock = 0;
currentSupply = formatDecimals(_currentSupply);
totalSupply = formatDecimals(10000000);
balances[msg.sender] = totalSupply;
if(currentSupply > totalSupply) throw;
}
modifier isOwner() { require(msg.sender == ethFundDeposit); _; }
/// 设置token汇率
function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external {
if (_tokenExchangeRate == 0) throw;
if (_tokenExchangeRate == tokenExchangeRate) throw;
tokenExchangeRate = _tokenExchangeRate;
}
/// @dev 超发token处理
function increaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + currentSupply > totalSupply) throw;
currentSupply = safeAdd(currentSupply, value);
IncreaseSupply(value);
}
/// @dev 被盗token处理
function decreaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + tokenRaised > currentSupply) throw;
currentSupply = safeSubtract(currentSupply, value);
DecreaseSupply(value);
}
/// 启动区块检测 异常的处理
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external {
if (isFunding) throw;
if (_fundingStartBlock >= _fundingStopBlock) throw;
if (block.number >= _fundingStartBlock) throw;
fundingStartBlock = _fundingStartBlock;
fundingStopBlock = _fundingStopBlock;
isFunding = true;
}
/// 关闭区块异常处理
function stopFunding() isOwner external {
if (!isFunding) throw;
isFunding = false;
}
/// 开发了一个新的合同来接收token(或者更新token)
function setMigrateContract(address _newContractAddr) isOwner external {
if (_newContractAddr == newContractAddr) throw;
newContractAddr = _newContractAddr;
}
/// 设置新的所有者地址
function changeOwner(address _newFundDeposit) isOwner() external {
if (_newFundDeposit == address(0x0)) throw;
ethFundDeposit = _newFundDeposit;
}
///转移token到新的合约
function migrate() external {
if(isFunding) throw;
if(newContractAddr == address(0x0)) throw;
uint256 tokens = balances[msg.sender];
if (tokens == 0) throw;
balances[msg.sender] = 0;
tokenMigrated = safeAdd(tokenMigrated, tokens);
IMigrationContract newContract = IMigrationContract(newContractAddr);
if (!newContract.migrate(msg.sender, tokens)) throw;
Migrate(msg.sender, tokens); // log it
}
/// 转账ETH 到 一个mofo
function transferETH() isOwner external {
if (this.balance == 0) throw;
if (!ethFundDeposit.send(this.balance)) throw;
}
/// 将mofo token分配到预处理地址。
function allocateToken (address _addr, uint256 _eth) isOwner external {
if (_eth == 0) throw;
if (_addr == address(0x0)) throw;
uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[_addr] += tokens;
AllocateToken(_addr, tokens); // 记录token日志
}
/// 购买token
function () payable {
if (!isFunding) throw;
if (msg.value == 0) throw;
if (block.number < fundingStartBlock) throw;
if (block.number > fundingStopBlock) throw;
uint256 tokens = safeMult(msg.value, tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[msg.sender] += tokens;
IssueToken(msg.sender, tokens); //记录日志
}
} | migrate | function migrate() external {
if(isFunding) throw;
if(newContractAddr == address(0x0)) throw;
uint256 tokens = balances[msg.sender];
if (tokens == 0) throw;
balances[msg.sender] = 0;
tokenMigrated = safeAdd(tokenMigrated, tokens);
IMigrationContract newContract = IMigrationContract(newContractAddr);
if (!newContract.migrate(msg.sender, tokens)) throw;
Migrate(msg.sender, tokens); // log it
}
| ///转移token到新的合约 | NatSpecSingleLine | v0.4.21+commit.dfe3193c | None | bzzr://050d9aa937f30b2e395c3ac6d33e80b98cd5a793fb79ad5789c3d60208cc1a43 | {
"func_code_index": [
3719,
4230
]
} | 3,630 |
||
MofoToken | MofoToken.sol | 0x62682c4869187275b1748d1d534ca8ee874250a5 | Solidity | MofoToken | contract MofoToken is StandardToken, SafeMath {
// metadata
string public constant name = "Mofo";
string public constant symbol = "MFCoin";
uint256 public constant decimals = 18;
string public version = "1.0";
// contracts
address public ethFundDeposit; // ETH存放地址
address public newContractAddr; // token更新地址
// crowdsale parameters
bool public isFunding; // 状态切换到true
uint256 public fundingStartBlock;
uint256 public fundingStopBlock;
uint256 public currentSupply; // 正在售卖中的tokens数量
uint256 public tokenRaised = 0; // 总的售卖数量token
uint256 public tokenMigrated = 0; // 总的已经交易的 token
uint256 public tokenExchangeRate = 1000; // 1000 MOFO 兑换 1 ETH
// events
event AllocateToken(address indexed _to, uint256 _value); // 分配的私有交易token;
event IssueToken(address indexed _to, uint256 _value); // 公开发行售卖的token;
event IncreaseSupply(uint256 _value);
event DecreaseSupply(uint256 _value);
event Migrate(address indexed _to, uint256 _value);
// 转换
function formatDecimals(uint256 _value) internal returns (uint256 ) {
return _value * 10 ** decimals;
}
// constructor
function MofoToken(
address _ethFundDeposit,
uint256 _currentSupply)
{
ethFundDeposit = _ethFundDeposit;
isFunding = false; //通过控制预CrowdS ale状态
fundingStartBlock = 0;
fundingStopBlock = 0;
currentSupply = formatDecimals(_currentSupply);
totalSupply = formatDecimals(10000000);
balances[msg.sender] = totalSupply;
if(currentSupply > totalSupply) throw;
}
modifier isOwner() { require(msg.sender == ethFundDeposit); _; }
/// 设置token汇率
function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external {
if (_tokenExchangeRate == 0) throw;
if (_tokenExchangeRate == tokenExchangeRate) throw;
tokenExchangeRate = _tokenExchangeRate;
}
/// @dev 超发token处理
function increaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + currentSupply > totalSupply) throw;
currentSupply = safeAdd(currentSupply, value);
IncreaseSupply(value);
}
/// @dev 被盗token处理
function decreaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + tokenRaised > currentSupply) throw;
currentSupply = safeSubtract(currentSupply, value);
DecreaseSupply(value);
}
/// 启动区块检测 异常的处理
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external {
if (isFunding) throw;
if (_fundingStartBlock >= _fundingStopBlock) throw;
if (block.number >= _fundingStartBlock) throw;
fundingStartBlock = _fundingStartBlock;
fundingStopBlock = _fundingStopBlock;
isFunding = true;
}
/// 关闭区块异常处理
function stopFunding() isOwner external {
if (!isFunding) throw;
isFunding = false;
}
/// 开发了一个新的合同来接收token(或者更新token)
function setMigrateContract(address _newContractAddr) isOwner external {
if (_newContractAddr == newContractAddr) throw;
newContractAddr = _newContractAddr;
}
/// 设置新的所有者地址
function changeOwner(address _newFundDeposit) isOwner() external {
if (_newFundDeposit == address(0x0)) throw;
ethFundDeposit = _newFundDeposit;
}
///转移token到新的合约
function migrate() external {
if(isFunding) throw;
if(newContractAddr == address(0x0)) throw;
uint256 tokens = balances[msg.sender];
if (tokens == 0) throw;
balances[msg.sender] = 0;
tokenMigrated = safeAdd(tokenMigrated, tokens);
IMigrationContract newContract = IMigrationContract(newContractAddr);
if (!newContract.migrate(msg.sender, tokens)) throw;
Migrate(msg.sender, tokens); // log it
}
/// 转账ETH 到 一个mofo
function transferETH() isOwner external {
if (this.balance == 0) throw;
if (!ethFundDeposit.send(this.balance)) throw;
}
/// 将mofo token分配到预处理地址。
function allocateToken (address _addr, uint256 _eth) isOwner external {
if (_eth == 0) throw;
if (_addr == address(0x0)) throw;
uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[_addr] += tokens;
AllocateToken(_addr, tokens); // 记录token日志
}
/// 购买token
function () payable {
if (!isFunding) throw;
if (msg.value == 0) throw;
if (block.number < fundingStartBlock) throw;
if (block.number > fundingStopBlock) throw;
uint256 tokens = safeMult(msg.value, tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[msg.sender] += tokens;
IssueToken(msg.sender, tokens); //记录日志
}
} | transferETH | function transferETH() isOwner external {
if (this.balance == 0) throw;
if (!ethFundDeposit.send(this.balance)) throw;
}
| /// 转账ETH 到 一个mofo | NatSpecSingleLine | v0.4.21+commit.dfe3193c | None | bzzr://050d9aa937f30b2e395c3ac6d33e80b98cd5a793fb79ad5789c3d60208cc1a43 | {
"func_code_index": [
4258,
4406
]
} | 3,631 |
||
MofoToken | MofoToken.sol | 0x62682c4869187275b1748d1d534ca8ee874250a5 | Solidity | MofoToken | contract MofoToken is StandardToken, SafeMath {
// metadata
string public constant name = "Mofo";
string public constant symbol = "MFCoin";
uint256 public constant decimals = 18;
string public version = "1.0";
// contracts
address public ethFundDeposit; // ETH存放地址
address public newContractAddr; // token更新地址
// crowdsale parameters
bool public isFunding; // 状态切换到true
uint256 public fundingStartBlock;
uint256 public fundingStopBlock;
uint256 public currentSupply; // 正在售卖中的tokens数量
uint256 public tokenRaised = 0; // 总的售卖数量token
uint256 public tokenMigrated = 0; // 总的已经交易的 token
uint256 public tokenExchangeRate = 1000; // 1000 MOFO 兑换 1 ETH
// events
event AllocateToken(address indexed _to, uint256 _value); // 分配的私有交易token;
event IssueToken(address indexed _to, uint256 _value); // 公开发行售卖的token;
event IncreaseSupply(uint256 _value);
event DecreaseSupply(uint256 _value);
event Migrate(address indexed _to, uint256 _value);
// 转换
function formatDecimals(uint256 _value) internal returns (uint256 ) {
return _value * 10 ** decimals;
}
// constructor
function MofoToken(
address _ethFundDeposit,
uint256 _currentSupply)
{
ethFundDeposit = _ethFundDeposit;
isFunding = false; //通过控制预CrowdS ale状态
fundingStartBlock = 0;
fundingStopBlock = 0;
currentSupply = formatDecimals(_currentSupply);
totalSupply = formatDecimals(10000000);
balances[msg.sender] = totalSupply;
if(currentSupply > totalSupply) throw;
}
modifier isOwner() { require(msg.sender == ethFundDeposit); _; }
/// 设置token汇率
function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external {
if (_tokenExchangeRate == 0) throw;
if (_tokenExchangeRate == tokenExchangeRate) throw;
tokenExchangeRate = _tokenExchangeRate;
}
/// @dev 超发token处理
function increaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + currentSupply > totalSupply) throw;
currentSupply = safeAdd(currentSupply, value);
IncreaseSupply(value);
}
/// @dev 被盗token处理
function decreaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + tokenRaised > currentSupply) throw;
currentSupply = safeSubtract(currentSupply, value);
DecreaseSupply(value);
}
/// 启动区块检测 异常的处理
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external {
if (isFunding) throw;
if (_fundingStartBlock >= _fundingStopBlock) throw;
if (block.number >= _fundingStartBlock) throw;
fundingStartBlock = _fundingStartBlock;
fundingStopBlock = _fundingStopBlock;
isFunding = true;
}
/// 关闭区块异常处理
function stopFunding() isOwner external {
if (!isFunding) throw;
isFunding = false;
}
/// 开发了一个新的合同来接收token(或者更新token)
function setMigrateContract(address _newContractAddr) isOwner external {
if (_newContractAddr == newContractAddr) throw;
newContractAddr = _newContractAddr;
}
/// 设置新的所有者地址
function changeOwner(address _newFundDeposit) isOwner() external {
if (_newFundDeposit == address(0x0)) throw;
ethFundDeposit = _newFundDeposit;
}
///转移token到新的合约
function migrate() external {
if(isFunding) throw;
if(newContractAddr == address(0x0)) throw;
uint256 tokens = balances[msg.sender];
if (tokens == 0) throw;
balances[msg.sender] = 0;
tokenMigrated = safeAdd(tokenMigrated, tokens);
IMigrationContract newContract = IMigrationContract(newContractAddr);
if (!newContract.migrate(msg.sender, tokens)) throw;
Migrate(msg.sender, tokens); // log it
}
/// 转账ETH 到 一个mofo
function transferETH() isOwner external {
if (this.balance == 0) throw;
if (!ethFundDeposit.send(this.balance)) throw;
}
/// 将mofo token分配到预处理地址。
function allocateToken (address _addr, uint256 _eth) isOwner external {
if (_eth == 0) throw;
if (_addr == address(0x0)) throw;
uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[_addr] += tokens;
AllocateToken(_addr, tokens); // 记录token日志
}
/// 购买token
function () payable {
if (!isFunding) throw;
if (msg.value == 0) throw;
if (block.number < fundingStartBlock) throw;
if (block.number > fundingStopBlock) throw;
uint256 tokens = safeMult(msg.value, tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[msg.sender] += tokens;
IssueToken(msg.sender, tokens); //记录日志
}
} | allocateToken | function allocateToken (address _addr, uint256 _eth) isOwner external {
if (_eth == 0) throw;
if (_addr == address(0x0)) throw;
uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[_addr] += tokens;
AllocateToken(_addr, tokens); // 记录token日志
}
| /// 将mofo token分配到预处理地址。 | NatSpecSingleLine | v0.4.21+commit.dfe3193c | None | bzzr://050d9aa937f30b2e395c3ac6d33e80b98cd5a793fb79ad5789c3d60208cc1a43 | {
"func_code_index": [
4441,
4884
]
} | 3,632 |
||
MofoToken | MofoToken.sol | 0x62682c4869187275b1748d1d534ca8ee874250a5 | Solidity | MofoToken | contract MofoToken is StandardToken, SafeMath {
// metadata
string public constant name = "Mofo";
string public constant symbol = "MFCoin";
uint256 public constant decimals = 18;
string public version = "1.0";
// contracts
address public ethFundDeposit; // ETH存放地址
address public newContractAddr; // token更新地址
// crowdsale parameters
bool public isFunding; // 状态切换到true
uint256 public fundingStartBlock;
uint256 public fundingStopBlock;
uint256 public currentSupply; // 正在售卖中的tokens数量
uint256 public tokenRaised = 0; // 总的售卖数量token
uint256 public tokenMigrated = 0; // 总的已经交易的 token
uint256 public tokenExchangeRate = 1000; // 1000 MOFO 兑换 1 ETH
// events
event AllocateToken(address indexed _to, uint256 _value); // 分配的私有交易token;
event IssueToken(address indexed _to, uint256 _value); // 公开发行售卖的token;
event IncreaseSupply(uint256 _value);
event DecreaseSupply(uint256 _value);
event Migrate(address indexed _to, uint256 _value);
// 转换
function formatDecimals(uint256 _value) internal returns (uint256 ) {
return _value * 10 ** decimals;
}
// constructor
function MofoToken(
address _ethFundDeposit,
uint256 _currentSupply)
{
ethFundDeposit = _ethFundDeposit;
isFunding = false; //通过控制预CrowdS ale状态
fundingStartBlock = 0;
fundingStopBlock = 0;
currentSupply = formatDecimals(_currentSupply);
totalSupply = formatDecimals(10000000);
balances[msg.sender] = totalSupply;
if(currentSupply > totalSupply) throw;
}
modifier isOwner() { require(msg.sender == ethFundDeposit); _; }
/// 设置token汇率
function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external {
if (_tokenExchangeRate == 0) throw;
if (_tokenExchangeRate == tokenExchangeRate) throw;
tokenExchangeRate = _tokenExchangeRate;
}
/// @dev 超发token处理
function increaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + currentSupply > totalSupply) throw;
currentSupply = safeAdd(currentSupply, value);
IncreaseSupply(value);
}
/// @dev 被盗token处理
function decreaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + tokenRaised > currentSupply) throw;
currentSupply = safeSubtract(currentSupply, value);
DecreaseSupply(value);
}
/// 启动区块检测 异常的处理
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external {
if (isFunding) throw;
if (_fundingStartBlock >= _fundingStopBlock) throw;
if (block.number >= _fundingStartBlock) throw;
fundingStartBlock = _fundingStartBlock;
fundingStopBlock = _fundingStopBlock;
isFunding = true;
}
/// 关闭区块异常处理
function stopFunding() isOwner external {
if (!isFunding) throw;
isFunding = false;
}
/// 开发了一个新的合同来接收token(或者更新token)
function setMigrateContract(address _newContractAddr) isOwner external {
if (_newContractAddr == newContractAddr) throw;
newContractAddr = _newContractAddr;
}
/// 设置新的所有者地址
function changeOwner(address _newFundDeposit) isOwner() external {
if (_newFundDeposit == address(0x0)) throw;
ethFundDeposit = _newFundDeposit;
}
///转移token到新的合约
function migrate() external {
if(isFunding) throw;
if(newContractAddr == address(0x0)) throw;
uint256 tokens = balances[msg.sender];
if (tokens == 0) throw;
balances[msg.sender] = 0;
tokenMigrated = safeAdd(tokenMigrated, tokens);
IMigrationContract newContract = IMigrationContract(newContractAddr);
if (!newContract.migrate(msg.sender, tokens)) throw;
Migrate(msg.sender, tokens); // log it
}
/// 转账ETH 到 一个mofo
function transferETH() isOwner external {
if (this.balance == 0) throw;
if (!ethFundDeposit.send(this.balance)) throw;
}
/// 将mofo token分配到预处理地址。
function allocateToken (address _addr, uint256 _eth) isOwner external {
if (_eth == 0) throw;
if (_addr == address(0x0)) throw;
uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[_addr] += tokens;
AllocateToken(_addr, tokens); // 记录token日志
}
/// 购买token
function () payable {
if (!isFunding) throw;
if (msg.value == 0) throw;
if (block.number < fundingStartBlock) throw;
if (block.number > fundingStopBlock) throw;
uint256 tokens = safeMult(msg.value, tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[msg.sender] += tokens;
IssueToken(msg.sender, tokens); //记录日志
}
} | function () payable {
if (!isFunding) throw;
if (msg.value == 0) throw;
if (block.number < fundingStartBlock) throw;
if (block.number > fundingStopBlock) throw;
uint256 tokens = safeMult(msg.value, tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[msg.sender] += tokens;
IssueToken(msg.sender, tokens); //记录日志
}
| /// 购买token | NatSpecSingleLine | v0.4.21+commit.dfe3193c | None | bzzr://050d9aa937f30b2e395c3ac6d33e80b98cd5a793fb79ad5789c3d60208cc1a43 | {
"func_code_index": [
4905,
5392
]
} | 3,633 |
|||
TimeLockRegistry | contracts/interfaces/IRewardsDistributor.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | IRewardsDistributor | interface IRewardsDistributor {
// Structs
struct PrincipalPerTimestamp {
uint256 principal;
uint256 time;
uint256 timeListPointer;
}
function protocolPrincipal() external view returns (uint256);
function pid() external view returns (uint256);
// solhint-disable-next-line
function EPOCH_DURATION() external pure returns (uint256);
// solhint-disable-next-line
function START_TIME() external view returns (uint256);
// solhint-disable-next-line
function Q1_REWARDS() external pure returns (uint256);
// solhint-disable-next-line
function DECAY_RATE() external pure returns (uint256);
function updateProtocolPrincipal(uint256 _capital, bool _addOrSubstract) external;
function getStrategyRewards(address _strategy) external view returns (uint96);
function sendTokensToContributor(address _to, uint256 _amount) external;
function startBABLRewards() external;
function getRewards(
address _garden,
address _contributor,
address[] calldata _finalizedStrategies
) external view returns (uint256[] memory);
function getContributorPower(
address _garden,
address _contributor,
uint256 _from,
uint256 _to
) external view returns (uint256);
function updateGardenPowerAndContributor(
address _garden,
address _contributor,
uint256 _previousBalance,
bool _depositOrWithdraw,
uint256 _pid
) external;
function tokenSupplyPerQuarter(uint256 quarter) external view returns (uint96);
function checkProtocol(uint256 _time)
external
view
returns (
uint256 principal,
uint256 time,
uint256 quarterBelonging,
uint256 timeListPointer,
uint256 power
);
function checkQuarter(uint256 _num)
external
view
returns (
uint256 quarterPrincipal,
uint256 quarterNumber,
uint256 quarterPower,
uint96 supplyPerQuarter
);
} | /**
* @title IRewardsDistributor
* @author Babylon Finance
*
* Interface for the distribute rewards of the BABL Mining Program.
*/ | NatSpecMultiLine | EPOCH_DURATION | function EPOCH_DURATION() external pure returns (uint256);
| // solhint-disable-next-line | LineComment | v0.7.6+commit.7338295f | {
"func_code_index": [
324,
386
]
} | 3,634 |
||
TimeLockRegistry | contracts/interfaces/IRewardsDistributor.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | IRewardsDistributor | interface IRewardsDistributor {
// Structs
struct PrincipalPerTimestamp {
uint256 principal;
uint256 time;
uint256 timeListPointer;
}
function protocolPrincipal() external view returns (uint256);
function pid() external view returns (uint256);
// solhint-disable-next-line
function EPOCH_DURATION() external pure returns (uint256);
// solhint-disable-next-line
function START_TIME() external view returns (uint256);
// solhint-disable-next-line
function Q1_REWARDS() external pure returns (uint256);
// solhint-disable-next-line
function DECAY_RATE() external pure returns (uint256);
function updateProtocolPrincipal(uint256 _capital, bool _addOrSubstract) external;
function getStrategyRewards(address _strategy) external view returns (uint96);
function sendTokensToContributor(address _to, uint256 _amount) external;
function startBABLRewards() external;
function getRewards(
address _garden,
address _contributor,
address[] calldata _finalizedStrategies
) external view returns (uint256[] memory);
function getContributorPower(
address _garden,
address _contributor,
uint256 _from,
uint256 _to
) external view returns (uint256);
function updateGardenPowerAndContributor(
address _garden,
address _contributor,
uint256 _previousBalance,
bool _depositOrWithdraw,
uint256 _pid
) external;
function tokenSupplyPerQuarter(uint256 quarter) external view returns (uint96);
function checkProtocol(uint256 _time)
external
view
returns (
uint256 principal,
uint256 time,
uint256 quarterBelonging,
uint256 timeListPointer,
uint256 power
);
function checkQuarter(uint256 _num)
external
view
returns (
uint256 quarterPrincipal,
uint256 quarterNumber,
uint256 quarterPower,
uint96 supplyPerQuarter
);
} | /**
* @title IRewardsDistributor
* @author Babylon Finance
*
* Interface for the distribute rewards of the BABL Mining Program.
*/ | NatSpecMultiLine | START_TIME | function START_TIME() external view returns (uint256);
| // solhint-disable-next-line | LineComment | v0.7.6+commit.7338295f | {
"func_code_index": [
421,
479
]
} | 3,635 |
||
TimeLockRegistry | contracts/interfaces/IRewardsDistributor.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | IRewardsDistributor | interface IRewardsDistributor {
// Structs
struct PrincipalPerTimestamp {
uint256 principal;
uint256 time;
uint256 timeListPointer;
}
function protocolPrincipal() external view returns (uint256);
function pid() external view returns (uint256);
// solhint-disable-next-line
function EPOCH_DURATION() external pure returns (uint256);
// solhint-disable-next-line
function START_TIME() external view returns (uint256);
// solhint-disable-next-line
function Q1_REWARDS() external pure returns (uint256);
// solhint-disable-next-line
function DECAY_RATE() external pure returns (uint256);
function updateProtocolPrincipal(uint256 _capital, bool _addOrSubstract) external;
function getStrategyRewards(address _strategy) external view returns (uint96);
function sendTokensToContributor(address _to, uint256 _amount) external;
function startBABLRewards() external;
function getRewards(
address _garden,
address _contributor,
address[] calldata _finalizedStrategies
) external view returns (uint256[] memory);
function getContributorPower(
address _garden,
address _contributor,
uint256 _from,
uint256 _to
) external view returns (uint256);
function updateGardenPowerAndContributor(
address _garden,
address _contributor,
uint256 _previousBalance,
bool _depositOrWithdraw,
uint256 _pid
) external;
function tokenSupplyPerQuarter(uint256 quarter) external view returns (uint96);
function checkProtocol(uint256 _time)
external
view
returns (
uint256 principal,
uint256 time,
uint256 quarterBelonging,
uint256 timeListPointer,
uint256 power
);
function checkQuarter(uint256 _num)
external
view
returns (
uint256 quarterPrincipal,
uint256 quarterNumber,
uint256 quarterPower,
uint96 supplyPerQuarter
);
} | /**
* @title IRewardsDistributor
* @author Babylon Finance
*
* Interface for the distribute rewards of the BABL Mining Program.
*/ | NatSpecMultiLine | Q1_REWARDS | function Q1_REWARDS() external pure returns (uint256);
| // solhint-disable-next-line | LineComment | v0.7.6+commit.7338295f | {
"func_code_index": [
514,
572
]
} | 3,636 |
||
TimeLockRegistry | contracts/interfaces/IRewardsDistributor.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | IRewardsDistributor | interface IRewardsDistributor {
// Structs
struct PrincipalPerTimestamp {
uint256 principal;
uint256 time;
uint256 timeListPointer;
}
function protocolPrincipal() external view returns (uint256);
function pid() external view returns (uint256);
// solhint-disable-next-line
function EPOCH_DURATION() external pure returns (uint256);
// solhint-disable-next-line
function START_TIME() external view returns (uint256);
// solhint-disable-next-line
function Q1_REWARDS() external pure returns (uint256);
// solhint-disable-next-line
function DECAY_RATE() external pure returns (uint256);
function updateProtocolPrincipal(uint256 _capital, bool _addOrSubstract) external;
function getStrategyRewards(address _strategy) external view returns (uint96);
function sendTokensToContributor(address _to, uint256 _amount) external;
function startBABLRewards() external;
function getRewards(
address _garden,
address _contributor,
address[] calldata _finalizedStrategies
) external view returns (uint256[] memory);
function getContributorPower(
address _garden,
address _contributor,
uint256 _from,
uint256 _to
) external view returns (uint256);
function updateGardenPowerAndContributor(
address _garden,
address _contributor,
uint256 _previousBalance,
bool _depositOrWithdraw,
uint256 _pid
) external;
function tokenSupplyPerQuarter(uint256 quarter) external view returns (uint96);
function checkProtocol(uint256 _time)
external
view
returns (
uint256 principal,
uint256 time,
uint256 quarterBelonging,
uint256 timeListPointer,
uint256 power
);
function checkQuarter(uint256 _num)
external
view
returns (
uint256 quarterPrincipal,
uint256 quarterNumber,
uint256 quarterPower,
uint96 supplyPerQuarter
);
} | /**
* @title IRewardsDistributor
* @author Babylon Finance
*
* Interface for the distribute rewards of the BABL Mining Program.
*/ | NatSpecMultiLine | DECAY_RATE | function DECAY_RATE() external pure returns (uint256);
| // solhint-disable-next-line | LineComment | v0.7.6+commit.7338295f | {
"func_code_index": [
607,
665
]
} | 3,637 |
||
TimeLockRegistry | contracts/interfaces/IBabController.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | IBabController | interface IBabController {
/* ============ Functions ============ */
function createGarden(
address _reserveAsset,
string memory _name,
string memory _symbol,
string memory _tokenURI,
uint256 _seed,
uint256[] calldata _gardenParams,
uint256 _initialContribution,
bool[] memory _publicGardenStrategistsStewards
) external payable returns (address);
function removeGarden(address _garden) external;
function addReserveAsset(address _reserveAsset) external;
function removeReserveAsset(address _reserveAsset) external;
function disableGarden(address _garden) external;
function editPriceOracle(address _priceOracle) external;
function editIshtarGate(address _ishtarGate) external;
function editGardenValuer(address _gardenValuer) external;
function editRewardsDistributor(address _rewardsDistributor) external;
function editTreasury(address _newTreasury) external;
function editGardenFactory(address _newGardenFactory) external;
function editGardenNFT(address _newGardenNFT) external;
function editStrategyNFT(address _newStrategyNFT) external;
function editStrategyFactory(address _newStrategyFactory) external;
function addIntegration(string memory _name, address _integration) external;
function editIntegration(string memory _name, address _integration) external;
function removeIntegration(string memory _name) external;
function setOperation(uint8 _kind, address _operation) external;
function setDefaultTradeIntegration(address _newDefaultTradeIntegation) external;
function addKeeper(address _keeper) external;
function addKeepers(address[] memory _keepers) external;
function removeKeeper(address _keeper) external;
function enableGardenTokensTransfers() external;
function enableBABLMiningProgram() external;
function setAllowPublicGardens() external;
function editLiquidityReserve(address _reserve, uint256 _minRiskyPairLiquidityEth) external;
function maxContributorsPerGarden() external view returns (uint256);
function gardenCreationIsOpen() external view returns (bool);
function openPublicGardenCreation() external;
function setMaxContributorsPerGarden(uint256 _newMax) external;
function owner() external view returns (address);
function guardianGlobalPaused() external view returns (bool);
function guardianPaused(address _address) external view returns (bool);
function setPauseGuardian(address _guardian) external;
function setGlobalPause(bool _state) external returns (bool);
function setSomePause(address[] memory _address, bool _state) external returns (bool);
function isPaused(address _contract) external view returns (bool);
function priceOracle() external view returns (address);
function gardenValuer() external view returns (address);
function gardenNFT() external view returns (address);
function strategyNFT() external view returns (address);
function rewardsDistributor() external view returns (address);
function gardenFactory() external view returns (address);
function treasury() external view returns (address);
function ishtarGate() external view returns (address);
function strategyFactory() external view returns (address);
function defaultTradeIntegration() external view returns (address);
function gardenTokensTransfersEnabled() external view returns (bool);
function bablMiningProgramEnabled() external view returns (bool);
function allowPublicGardens() external view returns (bool);
function enabledOperations(uint256 _kind) external view returns (address);
function getProfitSharing()
external
view
returns (
uint256,
uint256,
uint256
);
function getBABLSharing()
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function getGardens() external view returns (address[] memory);
function getOperations() external view returns (address[20] memory);
function isGarden(address _garden) external view returns (bool);
function getIntegrationByName(string memory _name) external view returns (address);
function getIntegrationWithHash(bytes32 _nameHashP) external view returns (address);
function isValidReserveAsset(address _reserveAsset) external view returns (bool);
function isValidKeeper(address _keeper) external view returns (bool);
function isSystemContract(address _contractAddress) external view returns (bool);
function isValidIntegration(string memory _name, address _integration) external view returns (bool);
function getMinCooldownPeriod() external view returns (uint256);
function getMaxCooldownPeriod() external view returns (uint256);
function protocolPerformanceFee() external view returns (uint256);
function protocolManagementFee() external view returns (uint256);
function minLiquidityPerReserve(address _reserve) external view returns (uint256);
} | /**
* @title IBabController
* @author Babylon Finance
*
* Interface for interacting with BabController
*/ | NatSpecMultiLine | createGarden | function createGarden(
address _reserveAsset,
string memory _name,
string memory _symbol,
string memory _tokenURI,
uint256 _seed,
uint256[] calldata _gardenParams,
uint256 _initialContribution,
bool[] memory _publicGardenStrategistsStewards
) external payable returns (address);
| /* ============ Functions ============ */ | Comment | v0.7.6+commit.7338295f | {
"func_code_index": [
74,
424
]
} | 3,638 |
||
TimeLockRegistry | contracts/lib/LowGasSafeMath.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | LowGasSafeMath | library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SafeMath: division by zero');
return a / b;
}
} | /// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost | NatSpecSingleLine | add | function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
| /// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y | NatSpecSingleLine | v0.7.6+commit.7338295f | {
"func_code_index": [
182,
297
]
} | 3,639 |
||
TimeLockRegistry | contracts/lib/LowGasSafeMath.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | LowGasSafeMath | library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SafeMath: division by zero');
return a / b;
}
} | /// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost | NatSpecSingleLine | sub | function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
| /// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y | NatSpecSingleLine | v0.7.6+commit.7338295f | {
"func_code_index": [
457,
572
]
} | 3,640 |
||
TimeLockRegistry | contracts/lib/LowGasSafeMath.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | LowGasSafeMath | library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SafeMath: division by zero');
return a / b;
}
} | /// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost | NatSpecSingleLine | mul | function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
| /// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y | NatSpecSingleLine | v0.7.6+commit.7338295f | {
"func_code_index": [
733,
862
]
} | 3,641 |
||
TimeLockRegistry | contracts/lib/LowGasSafeMath.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | LowGasSafeMath | library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SafeMath: division by zero');
return a / b;
}
} | /// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost | NatSpecSingleLine | add | function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
| /// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y | NatSpecSingleLine | v0.7.6+commit.7338295f | {
"func_code_index": [
1023,
1147
]
} | 3,642 |
||
TimeLockRegistry | contracts/lib/LowGasSafeMath.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | LowGasSafeMath | library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SafeMath: division by zero');
return a / b;
}
} | /// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost | NatSpecSingleLine | sub | function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
| /// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y | NatSpecSingleLine | v0.7.6+commit.7338295f | {
"func_code_index": [
1320,
1444
]
} | 3,643 |
||
TimeLockRegistry | contracts/lib/LowGasSafeMath.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | LowGasSafeMath | library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SafeMath: division by zero');
return a / b;
}
} | /// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost | NatSpecSingleLine | div | function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, 'SafeMath: division by zero');
return a / b;
}
| /**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. 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.7.6+commit.7338295f | {
"func_code_index": [
1904,
2058
]
} | 3,644 |
||
PairFactory | PairFactory.sol | 0x23b74796b72f995e14a5e3ff2156dad9653256cf | 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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | isContract | function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
| /**
* @dev 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.8.6+commit.11564f7e | None | ipfs://4d03a265a12ba81c0f5a175a2642e8e9fa5be73fda205ebdaf6e808e4fd675db | {
"func_code_index": [
606,
1033
]
} | 3,645 |
||
PairFactory | PairFactory.sol | 0x23b74796b72f995e14a5e3ff2156dad9653256cf | 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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | 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.8.6+commit.11564f7e | None | ipfs://4d03a265a12ba81c0f5a175a2642e8e9fa5be73fda205ebdaf6e808e4fd675db | {
"func_code_index": [
1963,
2365
]
} | 3,646 |
||
PairFactory | PairFactory.sol | 0x23b74796b72f995e14a5e3ff2156dad9653256cf | 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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | 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.8.6+commit.11564f7e | None | ipfs://4d03a265a12ba81c0f5a175a2642e8e9fa5be73fda205ebdaf6e808e4fd675db | {
"func_code_index": [
3121,
3299
]
} | 3,647 |
||
PairFactory | PairFactory.sol | 0x23b74796b72f995e14a5e3ff2156dad9653256cf | 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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | 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.8.6+commit.11564f7e | None | ipfs://4d03a265a12ba81c0f5a175a2642e8e9fa5be73fda205ebdaf6e808e4fd675db | {
"func_code_index": [
3524,
3724
]
} | 3,648 |
||
PairFactory | PairFactory.sol | 0x23b74796b72f995e14a5e3ff2156dad9653256cf | 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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | 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.8.6+commit.11564f7e | None | ipfs://4d03a265a12ba81c0f5a175a2642e8e9fa5be73fda205ebdaf6e808e4fd675db | {
"func_code_index": [
4094,
4325
]
} | 3,649 |
||
PairFactory | PairFactory.sol | 0x23b74796b72f995e14a5e3ff2156dad9653256cf | 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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | 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");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
| /**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/ | NatSpecMultiLine | v0.8.6+commit.11564f7e | None | ipfs://4d03a265a12ba81c0f5a175a2642e8e9fa5be73fda205ebdaf6e808e4fd675db | {
"func_code_index": [
4576,
5111
]
} | 3,650 |
||
PairFactory | PairFactory.sol | 0x23b74796b72f995e14a5e3ff2156dad9653256cf | 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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | functionStaticCall | function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/ | NatSpecMultiLine | v0.8.6+commit.11564f7e | None | ipfs://4d03a265a12ba81c0f5a175a2642e8e9fa5be73fda205ebdaf6e808e4fd675db | {
"func_code_index": [
5291,
5495
]
} | 3,651 |
||
PairFactory | PairFactory.sol | 0x23b74796b72f995e14a5e3ff2156dad9653256cf | 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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | functionStaticCall | function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/ | NatSpecMultiLine | v0.8.6+commit.11564f7e | None | ipfs://4d03a265a12ba81c0f5a175a2642e8e9fa5be73fda205ebdaf6e808e4fd675db | {
"func_code_index": [
5682,
6109
]
} | 3,652 |
||
PairFactory | PairFactory.sol | 0x23b74796b72f995e14a5e3ff2156dad9653256cf | 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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | functionDelegateCall | function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/ | NatSpecMultiLine | v0.8.6+commit.11564f7e | None | ipfs://4d03a265a12ba81c0f5a175a2642e8e9fa5be73fda205ebdaf6e808e4fd675db | {
"func_code_index": [
6291,
6496
]
} | 3,653 |
||
PairFactory | PairFactory.sol | 0x23b74796b72f995e14a5e3ff2156dad9653256cf | 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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | functionDelegateCall | function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
| /**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/ | NatSpecMultiLine | v0.8.6+commit.11564f7e | None | ipfs://4d03a265a12ba81c0f5a175a2642e8e9fa5be73fda205ebdaf6e808e4fd675db | {
"func_code_index": [
6685,
7113
]
} | 3,654 |
||
PairFactory | PairFactory.sol | 0x23b74796b72f995e14a5e3ff2156dad9653256cf | Solidity | Clones | library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address master) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `master` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) {
return predictDeterministicAddress(master, salt, address(this));
}
} | clone | function clone(address master) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
| /**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
*
* This function uses the create opcode, which should never revert.
*/ | NatSpecMultiLine | v0.8.6+commit.11564f7e | None | ipfs://4d03a265a12ba81c0f5a175a2642e8e9fa5be73fda205ebdaf6e808e4fd675db | {
"func_code_index": [
212,
782
]
} | 3,655 |
||
PairFactory | PairFactory.sol | 0x23b74796b72f995e14a5e3ff2156dad9653256cf | Solidity | Clones | library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address master) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `master` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) {
return predictDeterministicAddress(master, salt, address(this));
}
} | cloneDeterministic | function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
| /**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `master` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/ | NatSpecMultiLine | v0.8.6+commit.11564f7e | None | ipfs://4d03a265a12ba81c0f5a175a2642e8e9fa5be73fda205ebdaf6e808e4fd675db | {
"func_code_index": [
1145,
1750
]
} | 3,656 |
||
PairFactory | PairFactory.sol | 0x23b74796b72f995e14a5e3ff2156dad9653256cf | Solidity | Clones | library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address master) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `master` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) {
return predictDeterministicAddress(master, salt, address(this));
}
} | predictDeterministicAddress | function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
| /**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/ | NatSpecMultiLine | v0.8.6+commit.11564f7e | None | ipfs://4d03a265a12ba81c0f5a175a2642e8e9fa5be73fda205ebdaf6e808e4fd675db | {
"func_code_index": [
1860,
2591
]
} | 3,657 |
||
PairFactory | PairFactory.sol | 0x23b74796b72f995e14a5e3ff2156dad9653256cf | Solidity | Clones | library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address master) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `master`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `master` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, master))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) {
return predictDeterministicAddress(master, salt, address(this));
}
} | predictDeterministicAddress | function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) {
return predictDeterministicAddress(master, salt, address(this));
}
| /**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/ | NatSpecMultiLine | v0.8.6+commit.11564f7e | None | ipfs://4d03a265a12ba81c0f5a175a2642e8e9fa5be73fda205ebdaf6e808e4fd675db | {
"func_code_index": [
2701,
2897
]
} | 3,658 |
||
PairFactory | PairFactory.sol | 0x23b74796b72f995e14a5e3ff2156dad9653256cf | Solidity | SafeERC20 | library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
} | safeApprove | function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
| /**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/ | NatSpecMultiLine | v0.8.6+commit.11564f7e | None | ipfs://4d03a265a12ba81c0f5a175a2642e8e9fa5be73fda205ebdaf6e808e4fd675db | {
"func_code_index": [
793,
1414
]
} | 3,659 |
||
PairFactory | PairFactory.sol | 0x23b74796b72f995e14a5e3ff2156dad9653256cf | Solidity | SafeERC20 | library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
} | _callOptionalReturn | function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
| /**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/ | NatSpecMultiLine | v0.8.6+commit.11564f7e | None | ipfs://4d03a265a12ba81c0f5a175a2642e8e9fa5be73fda205ebdaf6e808e4fd675db | {
"func_code_index": [
2630,
3351
]
} | 3,660 |
||
PairFactory | PairFactory.sol | 0x23b74796b72f995e14a5e3ff2156dad9653256cf | Solidity | TransferHelper | contract TransferHelper {
using SafeERC20 for IERC20;
// Mainnet
IWETH internal constant WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
// Kovan
// IWETH internal constant WETH = IWETH(0xd0A1E359811322d97991E03f863a0C30C2cF029C);
function _safeTransferFrom(address _token, address _sender, uint _amount) internal virtual {
require(_amount > 0, "TransferHelper: amount must be > 0");
IERC20(_token).safeTransferFrom(_sender, address(this), _amount);
}
function _safeTransfer(address _token, address _recipient, uint _amount) internal virtual {
require(_amount > 0, "TransferHelper: amount must be > 0");
IERC20(_token).safeTransfer(_recipient, _amount);
}
function _wethWithdrawTo(address _to, uint _amount) internal virtual {
require(_amount > 0, "TransferHelper: amount must be > 0");
require(_to != address(0), "TransferHelper: invalid recipient");
WETH.withdraw(_amount);
(bool success, ) = _to.call { value: _amount }(new bytes(0));
require(success, 'TransferHelper: ETH transfer failed');
}
function _depositWeth() internal {
require(msg.value > 0, "TransferHelper: amount must be > 0");
WETH.deposit { value: msg.value }();
}
} | _safeTransferFrom | function _safeTransferFrom(address _token, address _sender, uint _amount) internal virtual {
require(_amount > 0, "TransferHelper: amount must be > 0");
IERC20(_token).safeTransferFrom(_sender, address(this), _amount);
}
| // Kovan
// IWETH internal constant WETH = IWETH(0xd0A1E359811322d97991E03f863a0C30C2cF029C); | LineComment | v0.8.6+commit.11564f7e | None | ipfs://4d03a265a12ba81c0f5a175a2642e8e9fa5be73fda205ebdaf6e808e4fd675db | {
"func_code_index": [
265,
501
]
} | 3,661 |
||
PairFactory | PairFactory.sol | 0x23b74796b72f995e14a5e3ff2156dad9653256cf | Solidity | LendingPair | contract LendingPair is TransferHelper, ReentrancyGuard {
// Prevents division by zero and other undesirable behaviour
uint private constant MIN_RESERVE = 1000;
using Address for address;
using Clones for address;
mapping (address => mapping (address => uint)) public debtOf;
mapping (address => mapping (address => uint)) public accountInterestSnapshot;
mapping (address => uint) public cumulativeInterestRate; // 100e18 = 100%
mapping (address => uint) public totalDebt;
mapping (address => IERC20) public lpToken;
IController public controller;
address public tokenA;
address public tokenB;
uint public lastBlockAccrued;
event Liquidation(
address indexed account,
address indexed repayToken,
address indexed supplyToken,
uint repayAmount,
uint supplyAmount
);
event Deposit(address indexed account, address indexed token, uint amount);
event Withdraw(address indexed token, uint amount);
event Borrow(address indexed token, uint amount);
event Repay(address indexed account, address indexed token, uint amount);
receive() external payable {}
function initialize(
address _lpTokenMaster,
address _controller,
IERC20 _tokenA,
IERC20 _tokenB
) external {
require(address(tokenA) == address(0), "LendingPair: already initialized");
require(address(_tokenA) != address(0) && address(_tokenB) != address(0), "LendingPair: cannot be ZERO address");
controller = IController(_controller);
tokenA = address(_tokenA);
tokenB = address(_tokenB);
lastBlockAccrued = block.number;
lpToken[tokenA] = _createLpToken(_lpTokenMaster);
lpToken[tokenB] = _createLpToken(_lpTokenMaster);
}
function depositRepay(address _account, address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(_account);
_depositRepay(_account, _token, _amount);
_safeTransferFrom(_token, msg.sender, _amount);
}
function depositRepayETH(address _account) external payable nonReentrant {
_validateToken(address(WETH));
accrueAccount(_account);
_depositRepay(_account, address(WETH), msg.value);
_depositWeth();
}
function deposit(address _account, address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(_account);
_deposit(_account, _token, _amount);
_safeTransferFrom(_token, msg.sender, _amount);
}
function withdrawBorrow(address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(msg.sender);
_withdrawBorrow(_token, _amount);
_safeTransfer(_token, msg.sender, _amount);
}
function withdrawBorrowETH(uint _amount) external nonReentrant {
_validateToken(address(WETH));
accrueAccount(msg.sender);
_withdrawBorrow(address(WETH), _amount);
_wethWithdrawTo(msg.sender, _amount);
}
function withdraw(address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(msg.sender);
_withdraw(_token, _amount);
_safeTransfer(_token, msg.sender, _amount);
}
function withdrawAll(address _token) external nonReentrant {
_validateToken(_token);
accrueAccount(msg.sender);
uint amount = lpToken[_token].balanceOf(msg.sender);
_withdraw(_token, amount);
_safeTransfer(_token, msg.sender, amount);
}
function withdrawAllETH() external nonReentrant {
_validateToken(address(WETH));
accrueAccount(msg.sender);
uint amount = lpToken[address(WETH)].balanceOf(msg.sender);
_withdraw(address(WETH), amount);
_wethWithdrawTo(msg.sender, amount);
}
function borrow(address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(msg.sender);
_borrow(_token, _amount);
_safeTransfer(_token, msg.sender, _amount);
}
function repayAll(address _account, address _token) external nonReentrant {
_validateToken(_token);
_requireAccountNotAccrued(_token, _account);
accrueAccount(_account);
uint amount = debtOf[_token][_account];
_repay(_account, _token, amount);
_safeTransferFrom(_token, msg.sender, amount);
}
function repayAllETH(address _account) external payable nonReentrant {
_validateToken(address(WETH));
_requireAccountNotAccrued(address(WETH), _account);
accrueAccount(_account);
uint amount = debtOf[address(WETH)][_account];
require(msg.value >= amount, "LendingPair: insufficient ETH deposit");
_depositWeth();
_repay(_account, address(WETH), amount);
uint refundAmount = msg.value > amount ? (msg.value - amount) : 0;
if (refundAmount > 0) {
_wethWithdrawTo(msg.sender, refundAmount);
}
}
function repay(address _account, address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(_account);
_repay(_account, _token, _amount);
_safeTransferFrom(_token, msg.sender, _amount);
}
function accrue() public {
if (lastBlockAccrued < block.number) {
_accrueInterest(tokenA);
_accrueInterest(tokenB);
lastBlockAccrued = block.number;
}
}
function accrueAccount(address _account) public {
_distributeReward(_account);
accrue();
_accrueAccountInterest(_account);
if (_account != feeRecipient()) {
_accrueAccountInterest(feeRecipient());
}
}
// Sell collateral to reduce debt and increase accountHealth
// Set _repayAmount to uint(-1) to repay all debt, inc. pending interest
function liquidateAccount(
address _account,
address _repayToken,
uint _repayAmount,
uint _minSupplyOutput
) external nonReentrant {
// Input validation and adjustments
_validateToken(_repayToken);
address supplyToken = _repayToken == tokenA ? tokenB : tokenA;
// Check account is underwater after interest
accrueAccount(_account);
uint health = accountHealth(_account);
require(health < controller.LIQ_MIN_HEALTH(), "LendingPair: account health < LIQ_MIN_HEALTH");
// Calculate balance adjustments
_repayAmount = Math.min(_repayAmount, debtOf[_repayToken][_account]);
uint supplyDebt = _convertTokenValues(_repayToken, supplyToken, _repayAmount);
uint callerFee = supplyDebt * controller.liqFeeCaller(_repayToken) / 100e18;
uint systemFee = supplyDebt * controller.liqFeeSystem(_repayToken) / 100e18;
uint supplyBurn = supplyDebt + callerFee + systemFee;
uint supplyOutput = supplyDebt + callerFee;
require(supplyOutput >= _minSupplyOutput, "LendingPair: supplyOutput >= _minSupplyOutput");
// Adjust balances
_burnSupply(supplyToken, _account, supplyBurn);
_mintSupply(supplyToken, feeRecipient(), systemFee);
_burnDebt(_repayToken, _account, _repayAmount);
// Settle token transfers
_safeTransferFrom(_repayToken, msg.sender, _repayAmount);
_mintSupply(supplyToken, msg.sender, supplyOutput);
emit Liquidation(_account, _repayToken, supplyToken, _repayAmount, supplyOutput);
}
function accountHealth(address _account) public view returns(uint) {
if (debtOf[tokenA][_account] == 0 && debtOf[tokenB][_account] == 0) {
return controller.LIQ_MIN_HEALTH();
}
uint totalAccountSupply = _supplyCredit(_account, tokenA, tokenA) + _supplyCredit(_account, tokenB, tokenA);
uint totalAccountBorrow = _borrowBalance(_account, tokenA, tokenA) + _borrowBalance(_account, tokenB, tokenA);
return totalAccountSupply * 1e18 / totalAccountBorrow;
}
// Get borow balance converted to the units of _returnToken
function borrowBalance(
address _account,
address _borrowedToken,
address _returnToken
) external view returns(uint) {
_validateToken(_borrowedToken);
_validateToken(_returnToken);
return _borrowBalance(_account, _borrowedToken, _returnToken);
}
function supplyBalance(
address _account,
address _suppliedToken,
address _returnToken
) external view returns(uint) {
_validateToken(_suppliedToken);
_validateToken(_returnToken);
return _supplyBalance(_account, _suppliedToken, _returnToken);
}
function supplyRatePerBlock(address _token) external view returns(uint) {
_validateToken(_token);
return controller.interestRateModel().supplyRatePerBlock(ILendingPair(address(this)), _token);
}
function borrowRatePerBlock(address _token) external view returns(uint) {
_validateToken(_token);
return _borrowRatePerBlock(_token);
}
function pendingSupplyInterest(address _token, address _account) external view returns(uint) {
_validateToken(_token);
uint newInterest = _newInterest(lpToken[_token].balanceOf(_account), _token, _account);
return newInterest * _lpRate(_token) / 100e18;
}
function pendingBorrowInterest(address _token, address _account) external view returns(uint) {
_validateToken(_token);
return _pendingBorrowInterest(_token, _account);
}
function feeRecipient() public view returns(address) {
return controller.feeRecipient();
}
function checkAccountHealth(address _account) public view {
uint health = accountHealth(_account);
require(health >= controller.LIQ_MIN_HEALTH(), "LendingPair: insufficient accountHealth");
}
function convertTokenValues(
address _fromToken,
address _toToken,
uint _inputAmount
) external view returns(uint) {
_validateToken(_fromToken);
_validateToken(_toToken);
return _convertTokenValues(_fromToken, _toToken, _inputAmount);
}
function _depositRepay(address _account, address _token, uint _amount) internal {
uint debt = debtOf[_token][_account];
uint repayAmount = debt > _amount ? _amount : debt;
if (repayAmount > 0) {
_repay(_account, _token, repayAmount);
}
uint depositAmount = _amount - repayAmount;
if (depositAmount > 0) {
_deposit(_account, _token, depositAmount);
}
}
function _withdrawBorrow(address _token, uint _amount) internal {
uint supplyAmount = lpToken[_token].balanceOf(msg.sender);
uint withdrawAmount = supplyAmount > _amount ? _amount : supplyAmount;
if (withdrawAmount > 0) {
_withdraw(_token, withdrawAmount);
}
uint borrowAmount = _amount - withdrawAmount;
if (borrowAmount > 0) {
_borrow(_token, borrowAmount);
}
}
function _distributeReward(address _account) internal {
IRewardDistribution rewardDistribution = controller.rewardDistribution();
if (
address(rewardDistribution) != address(0) &&
_account != feeRecipient()
) {
rewardDistribution.distributeReward(_account, tokenA);
rewardDistribution.distributeReward(_account, tokenB);
}
}
function _mintSupply(address _token, address _account, uint _amount) internal {
if (_amount > 0) {
lpToken[_token].mint(_account, _amount);
}
}
function _burnSupply(address _token, address _account, uint _amount) internal {
if (_amount > 0) {
lpToken[_token].burn(_account, _amount);
}
}
function _mintDebt(address _token, address _account, uint _amount) internal {
debtOf[_token][_account] += _amount;
totalDebt[_token] += _amount;
}
// Origination fee is earned entirely by the protocol and is not split with the LPs
// The goal is to prevent free flash loans
function _mintDebtWithOriginFee(address _token, address _account, uint _amount) internal {
uint originFee = _originationFee(_token, _amount);
_mintSupply(_token, feeRecipient(), originFee);
_mintDebt(_token, _account, _amount + originFee);
}
function _burnDebt(address _token, address _account, uint _amount) internal {
debtOf[_token][_account] -= _amount;
totalDebt[_token] -= _amount;
}
function _accrueAccountInterest(address _account) internal {
uint lpBalanceA = lpToken[tokenA].balanceOf(_account);
uint lpBalanceB = lpToken[tokenB].balanceOf(_account);
_accrueAccountSupply(tokenA, lpBalanceA, _account);
_accrueAccountSupply(tokenB, lpBalanceB, _account);
_accrueAccountDebt(tokenA, _account);
_accrueAccountDebt(tokenB, _account);
accountInterestSnapshot[tokenA][_account] = cumulativeInterestRate[tokenA];
accountInterestSnapshot[tokenB][_account] = cumulativeInterestRate[tokenB];
}
function _accrueAccountSupply(address _token, uint _amount, address _account) internal {
if (_amount > 0) {
uint supplyInterest = _newInterest(_amount, _token, _account);
uint newSupplyAccount = supplyInterest * _lpRate(_token) / 100e18;
uint newSupplySystem = supplyInterest * _systemRate(_token) / 100e18;
_mintSupply(_token, _account, newSupplyAccount);
_mintSupply(_token, feeRecipient(), newSupplySystem);
}
}
function _accrueAccountDebt(address _token, address _account) internal {
if (debtOf[_token][_account] > 0) {
uint newDebt = _pendingBorrowInterest(_token, _account);
_mintDebt(_token, _account, newDebt);
}
}
function _withdraw(address _token, uint _amount) internal {
lpToken[_token].burn(msg.sender, _amount);
checkAccountHealth(msg.sender);
emit Withdraw(_token, _amount);
}
function _borrow(address _token, uint _amount) internal {
require(lpToken[_token].balanceOf(msg.sender) == 0, "LendingPair: cannot borrow supplied token");
_mintDebtWithOriginFee(_token, msg.sender, _amount);
_checkBorrowLimits(_token, msg.sender);
checkAccountHealth(msg.sender);
emit Borrow(_token, _amount);
}
function _repay(address _account, address _token, uint _amount) internal {
_burnDebt(_token, _account, _amount);
emit Repay(_account, _token, _amount);
}
function _deposit(address _account, address _token, uint _amount) internal {
_checkOracleSupport(tokenA);
_checkOracleSupport(tokenB);
require(debtOf[_token][_account] == 0, "LendingPair: cannot deposit borrowed token");
_mintSupply(_token, _account, _amount);
_checkDepositLimit(_token);
emit Deposit(_account, _token, _amount);
}
function _accrueInterest(address _token) internal {
cumulativeInterestRate[_token] += _pendingInterestRate(_token);
}
function _pendingInterestRate(address _token) internal view returns(uint) {
uint blocksElapsed = block.number - lastBlockAccrued;
return _borrowRatePerBlock(_token) * blocksElapsed;
}
function _createLpToken(address _lpTokenMaster) internal returns(IERC20) {
ILPTokenMaster newLPToken = ILPTokenMaster(_lpTokenMaster.clone());
newLPToken.initialize();
return IERC20(newLPToken);
}
function _safeTransfer(address _token, address _recipient, uint _amount) internal override {
TransferHelper._safeTransfer(_token, _recipient, _amount);
_checkMinReserve(address(_token));
}
function _wethWithdrawTo(address _to, uint _amount) internal override {
TransferHelper._wethWithdrawTo(_to, _amount);
_checkMinReserve(address(WETH));
}
function _borrowRatePerBlock(address _token) internal view returns(uint) {
return controller.interestRateModel().borrowRatePerBlock(ILendingPair(address(this)), _token);
}
function _pendingBorrowInterest(address _token, address _account) internal view returns(uint) {
return _newInterest(debtOf[_token][_account], _token, _account);
}
function _borrowBalance(
address _account,
address _borrowedToken,
address _returnToken
) internal view returns(uint) {
return _convertTokenValues(_borrowedToken, _returnToken, debtOf[_borrowedToken][_account]);
}
// Get supply balance converted to the units of _returnToken
function _supplyBalance(
address _account,
address _suppliedToken,
address _returnToken
) internal view returns(uint) {
return _convertTokenValues(_suppliedToken, _returnToken, lpToken[_suppliedToken].balanceOf(_account));
}
function _supplyCredit(
address _account,
address _suppliedToken,
address _returnToken
) internal view returns(uint) {
return _supplyBalance(_account, _suppliedToken, _returnToken) * controller.colFactor(_suppliedToken) / 100e18;
}
function _convertTokenValues(
address _fromToken,
address _toToken,
uint _inputAmount
) internal view returns(uint) {
uint priceFrom = controller.tokenPrice(_fromToken) * 1e18 / 10 ** IERC20(_fromToken).decimals();
uint priceTo = controller.tokenPrice(_toToken) * 1e18 / 10 ** IERC20(_toToken).decimals();
return _inputAmount * priceFrom / priceTo;
}
function _validateToken(address _token) internal view {
require(_token == tokenA || _token == tokenB, "LendingPair: invalid token");
}
function _checkOracleSupport(address _token) internal view {
require(controller.tokenSupported(_token), "LendingPair: token not supported");
}
function _checkMinReserve(address _token) internal view {
require(IERC20(_token).balanceOf(address(this)) >= MIN_RESERVE, "LendingPair: below MIN_RESERVE");
}
function _checkDepositLimit(address _token) internal view {
require(controller.depositsEnabled(), "LendingPair: deposits disabled");
uint depositLimit = controller.depositLimit(address(this), _token);
if (depositLimit > 0) {
require((lpToken[_token].totalSupply()) <= depositLimit, "LendingPair: deposit limit reached");
}
}
function _checkBorrowLimits(address _token, address _account) internal view {
require(controller.borrowingEnabled(), "LendingPair: borrowing disabled");
uint accountBorrowUSD = debtOf[_token][_account] * controller.tokenPrice(_token) / 1e18;
require(accountBorrowUSD >= controller.minBorrowUSD(), "LendingPair: borrow amount below minimum");
uint borrowLimit = controller.borrowLimit(address(this), _token);
if (borrowLimit > 0) {
require(totalDebt[_token] <= borrowLimit, "LendingPair: borrow limit reached");
}
}
function _originationFee(address _token, uint _amount) internal view returns(uint) {
return _amount * controller.originFee(_token) / 100e18;
}
function _systemRate(address _token) internal view returns(uint) {
return controller.interestRateModel().systemRate(ILendingPair(address(this)), _token);
}
function _lpRate(address _token) internal view returns(uint) {
return 100e18 - _systemRate(_token);
}
function _newInterest(uint _balance, address _token, address _account) internal view returns(uint) {
uint currentCumulativeRate = cumulativeInterestRate[_token] + _pendingInterestRate(_token);
return _balance * (currentCumulativeRate - accountInterestSnapshot[_token][_account]) / 100e18;
}
// Used in repayAll and repayAllETH to prevent front-running
// Potential attack:
// Recipient account watches the mempool and takes out a large loan just before someone calls repayAll.
// As a result, paying account would end up paying much more than anticipated
function _requireAccountNotAccrued(address _token, address _account) internal view {
if (lastBlockAccrued == block.number && cumulativeInterestRate[_token] > 0) {
require(
cumulativeInterestRate[_token] > accountInterestSnapshot[_token][_account],
"LendingPair: account already accrued"
);
}
}
} | liquidateAccount | function liquidateAccount(
address _account,
address _repayToken,
uint _repayAmount,
uint _minSupplyOutput
) external nonReentrant {
// Input validation and adjustments
_validateToken(_repayToken);
address supplyToken = _repayToken == tokenA ? tokenB : tokenA;
// Check account is underwater after interest
accrueAccount(_account);
uint health = accountHealth(_account);
require(health < controller.LIQ_MIN_HEALTH(), "LendingPair: account health < LIQ_MIN_HEALTH");
// Calculate balance adjustments
_repayAmount = Math.min(_repayAmount, debtOf[_repayToken][_account]);
uint supplyDebt = _convertTokenValues(_repayToken, supplyToken, _repayAmount);
uint callerFee = supplyDebt * controller.liqFeeCaller(_repayToken) / 100e18;
uint systemFee = supplyDebt * controller.liqFeeSystem(_repayToken) / 100e18;
uint supplyBurn = supplyDebt + callerFee + systemFee;
uint supplyOutput = supplyDebt + callerFee;
require(supplyOutput >= _minSupplyOutput, "LendingPair: supplyOutput >= _minSupplyOutput");
// Adjust balances
_burnSupply(supplyToken, _account, supplyBurn);
_mintSupply(supplyToken, feeRecipient(), systemFee);
_burnDebt(_repayToken, _account, _repayAmount);
// Settle token transfers
_safeTransferFrom(_repayToken, msg.sender, _repayAmount);
_mintSupply(supplyToken, msg.sender, supplyOutput);
emit Liquidation(_account, _repayToken, supplyToken, _repayAmount, supplyOutput);
}
| // Sell collateral to reduce debt and increase accountHealth
// Set _repayAmount to uint(-1) to repay all debt, inc. pending interest | LineComment | v0.8.6+commit.11564f7e | None | ipfs://4d03a265a12ba81c0f5a175a2642e8e9fa5be73fda205ebdaf6e808e4fd675db | {
"func_code_index": [
5694,
7259
]
} | 3,662 |
||
PairFactory | PairFactory.sol | 0x23b74796b72f995e14a5e3ff2156dad9653256cf | Solidity | LendingPair | contract LendingPair is TransferHelper, ReentrancyGuard {
// Prevents division by zero and other undesirable behaviour
uint private constant MIN_RESERVE = 1000;
using Address for address;
using Clones for address;
mapping (address => mapping (address => uint)) public debtOf;
mapping (address => mapping (address => uint)) public accountInterestSnapshot;
mapping (address => uint) public cumulativeInterestRate; // 100e18 = 100%
mapping (address => uint) public totalDebt;
mapping (address => IERC20) public lpToken;
IController public controller;
address public tokenA;
address public tokenB;
uint public lastBlockAccrued;
event Liquidation(
address indexed account,
address indexed repayToken,
address indexed supplyToken,
uint repayAmount,
uint supplyAmount
);
event Deposit(address indexed account, address indexed token, uint amount);
event Withdraw(address indexed token, uint amount);
event Borrow(address indexed token, uint amount);
event Repay(address indexed account, address indexed token, uint amount);
receive() external payable {}
function initialize(
address _lpTokenMaster,
address _controller,
IERC20 _tokenA,
IERC20 _tokenB
) external {
require(address(tokenA) == address(0), "LendingPair: already initialized");
require(address(_tokenA) != address(0) && address(_tokenB) != address(0), "LendingPair: cannot be ZERO address");
controller = IController(_controller);
tokenA = address(_tokenA);
tokenB = address(_tokenB);
lastBlockAccrued = block.number;
lpToken[tokenA] = _createLpToken(_lpTokenMaster);
lpToken[tokenB] = _createLpToken(_lpTokenMaster);
}
function depositRepay(address _account, address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(_account);
_depositRepay(_account, _token, _amount);
_safeTransferFrom(_token, msg.sender, _amount);
}
function depositRepayETH(address _account) external payable nonReentrant {
_validateToken(address(WETH));
accrueAccount(_account);
_depositRepay(_account, address(WETH), msg.value);
_depositWeth();
}
function deposit(address _account, address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(_account);
_deposit(_account, _token, _amount);
_safeTransferFrom(_token, msg.sender, _amount);
}
function withdrawBorrow(address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(msg.sender);
_withdrawBorrow(_token, _amount);
_safeTransfer(_token, msg.sender, _amount);
}
function withdrawBorrowETH(uint _amount) external nonReentrant {
_validateToken(address(WETH));
accrueAccount(msg.sender);
_withdrawBorrow(address(WETH), _amount);
_wethWithdrawTo(msg.sender, _amount);
}
function withdraw(address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(msg.sender);
_withdraw(_token, _amount);
_safeTransfer(_token, msg.sender, _amount);
}
function withdrawAll(address _token) external nonReentrant {
_validateToken(_token);
accrueAccount(msg.sender);
uint amount = lpToken[_token].balanceOf(msg.sender);
_withdraw(_token, amount);
_safeTransfer(_token, msg.sender, amount);
}
function withdrawAllETH() external nonReentrant {
_validateToken(address(WETH));
accrueAccount(msg.sender);
uint amount = lpToken[address(WETH)].balanceOf(msg.sender);
_withdraw(address(WETH), amount);
_wethWithdrawTo(msg.sender, amount);
}
function borrow(address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(msg.sender);
_borrow(_token, _amount);
_safeTransfer(_token, msg.sender, _amount);
}
function repayAll(address _account, address _token) external nonReentrant {
_validateToken(_token);
_requireAccountNotAccrued(_token, _account);
accrueAccount(_account);
uint amount = debtOf[_token][_account];
_repay(_account, _token, amount);
_safeTransferFrom(_token, msg.sender, amount);
}
function repayAllETH(address _account) external payable nonReentrant {
_validateToken(address(WETH));
_requireAccountNotAccrued(address(WETH), _account);
accrueAccount(_account);
uint amount = debtOf[address(WETH)][_account];
require(msg.value >= amount, "LendingPair: insufficient ETH deposit");
_depositWeth();
_repay(_account, address(WETH), amount);
uint refundAmount = msg.value > amount ? (msg.value - amount) : 0;
if (refundAmount > 0) {
_wethWithdrawTo(msg.sender, refundAmount);
}
}
function repay(address _account, address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(_account);
_repay(_account, _token, _amount);
_safeTransferFrom(_token, msg.sender, _amount);
}
function accrue() public {
if (lastBlockAccrued < block.number) {
_accrueInterest(tokenA);
_accrueInterest(tokenB);
lastBlockAccrued = block.number;
}
}
function accrueAccount(address _account) public {
_distributeReward(_account);
accrue();
_accrueAccountInterest(_account);
if (_account != feeRecipient()) {
_accrueAccountInterest(feeRecipient());
}
}
// Sell collateral to reduce debt and increase accountHealth
// Set _repayAmount to uint(-1) to repay all debt, inc. pending interest
function liquidateAccount(
address _account,
address _repayToken,
uint _repayAmount,
uint _minSupplyOutput
) external nonReentrant {
// Input validation and adjustments
_validateToken(_repayToken);
address supplyToken = _repayToken == tokenA ? tokenB : tokenA;
// Check account is underwater after interest
accrueAccount(_account);
uint health = accountHealth(_account);
require(health < controller.LIQ_MIN_HEALTH(), "LendingPair: account health < LIQ_MIN_HEALTH");
// Calculate balance adjustments
_repayAmount = Math.min(_repayAmount, debtOf[_repayToken][_account]);
uint supplyDebt = _convertTokenValues(_repayToken, supplyToken, _repayAmount);
uint callerFee = supplyDebt * controller.liqFeeCaller(_repayToken) / 100e18;
uint systemFee = supplyDebt * controller.liqFeeSystem(_repayToken) / 100e18;
uint supplyBurn = supplyDebt + callerFee + systemFee;
uint supplyOutput = supplyDebt + callerFee;
require(supplyOutput >= _minSupplyOutput, "LendingPair: supplyOutput >= _minSupplyOutput");
// Adjust balances
_burnSupply(supplyToken, _account, supplyBurn);
_mintSupply(supplyToken, feeRecipient(), systemFee);
_burnDebt(_repayToken, _account, _repayAmount);
// Settle token transfers
_safeTransferFrom(_repayToken, msg.sender, _repayAmount);
_mintSupply(supplyToken, msg.sender, supplyOutput);
emit Liquidation(_account, _repayToken, supplyToken, _repayAmount, supplyOutput);
}
function accountHealth(address _account) public view returns(uint) {
if (debtOf[tokenA][_account] == 0 && debtOf[tokenB][_account] == 0) {
return controller.LIQ_MIN_HEALTH();
}
uint totalAccountSupply = _supplyCredit(_account, tokenA, tokenA) + _supplyCredit(_account, tokenB, tokenA);
uint totalAccountBorrow = _borrowBalance(_account, tokenA, tokenA) + _borrowBalance(_account, tokenB, tokenA);
return totalAccountSupply * 1e18 / totalAccountBorrow;
}
// Get borow balance converted to the units of _returnToken
function borrowBalance(
address _account,
address _borrowedToken,
address _returnToken
) external view returns(uint) {
_validateToken(_borrowedToken);
_validateToken(_returnToken);
return _borrowBalance(_account, _borrowedToken, _returnToken);
}
function supplyBalance(
address _account,
address _suppliedToken,
address _returnToken
) external view returns(uint) {
_validateToken(_suppliedToken);
_validateToken(_returnToken);
return _supplyBalance(_account, _suppliedToken, _returnToken);
}
function supplyRatePerBlock(address _token) external view returns(uint) {
_validateToken(_token);
return controller.interestRateModel().supplyRatePerBlock(ILendingPair(address(this)), _token);
}
function borrowRatePerBlock(address _token) external view returns(uint) {
_validateToken(_token);
return _borrowRatePerBlock(_token);
}
function pendingSupplyInterest(address _token, address _account) external view returns(uint) {
_validateToken(_token);
uint newInterest = _newInterest(lpToken[_token].balanceOf(_account), _token, _account);
return newInterest * _lpRate(_token) / 100e18;
}
function pendingBorrowInterest(address _token, address _account) external view returns(uint) {
_validateToken(_token);
return _pendingBorrowInterest(_token, _account);
}
function feeRecipient() public view returns(address) {
return controller.feeRecipient();
}
function checkAccountHealth(address _account) public view {
uint health = accountHealth(_account);
require(health >= controller.LIQ_MIN_HEALTH(), "LendingPair: insufficient accountHealth");
}
function convertTokenValues(
address _fromToken,
address _toToken,
uint _inputAmount
) external view returns(uint) {
_validateToken(_fromToken);
_validateToken(_toToken);
return _convertTokenValues(_fromToken, _toToken, _inputAmount);
}
function _depositRepay(address _account, address _token, uint _amount) internal {
uint debt = debtOf[_token][_account];
uint repayAmount = debt > _amount ? _amount : debt;
if (repayAmount > 0) {
_repay(_account, _token, repayAmount);
}
uint depositAmount = _amount - repayAmount;
if (depositAmount > 0) {
_deposit(_account, _token, depositAmount);
}
}
function _withdrawBorrow(address _token, uint _amount) internal {
uint supplyAmount = lpToken[_token].balanceOf(msg.sender);
uint withdrawAmount = supplyAmount > _amount ? _amount : supplyAmount;
if (withdrawAmount > 0) {
_withdraw(_token, withdrawAmount);
}
uint borrowAmount = _amount - withdrawAmount;
if (borrowAmount > 0) {
_borrow(_token, borrowAmount);
}
}
function _distributeReward(address _account) internal {
IRewardDistribution rewardDistribution = controller.rewardDistribution();
if (
address(rewardDistribution) != address(0) &&
_account != feeRecipient()
) {
rewardDistribution.distributeReward(_account, tokenA);
rewardDistribution.distributeReward(_account, tokenB);
}
}
function _mintSupply(address _token, address _account, uint _amount) internal {
if (_amount > 0) {
lpToken[_token].mint(_account, _amount);
}
}
function _burnSupply(address _token, address _account, uint _amount) internal {
if (_amount > 0) {
lpToken[_token].burn(_account, _amount);
}
}
function _mintDebt(address _token, address _account, uint _amount) internal {
debtOf[_token][_account] += _amount;
totalDebt[_token] += _amount;
}
// Origination fee is earned entirely by the protocol and is not split with the LPs
// The goal is to prevent free flash loans
function _mintDebtWithOriginFee(address _token, address _account, uint _amount) internal {
uint originFee = _originationFee(_token, _amount);
_mintSupply(_token, feeRecipient(), originFee);
_mintDebt(_token, _account, _amount + originFee);
}
function _burnDebt(address _token, address _account, uint _amount) internal {
debtOf[_token][_account] -= _amount;
totalDebt[_token] -= _amount;
}
function _accrueAccountInterest(address _account) internal {
uint lpBalanceA = lpToken[tokenA].balanceOf(_account);
uint lpBalanceB = lpToken[tokenB].balanceOf(_account);
_accrueAccountSupply(tokenA, lpBalanceA, _account);
_accrueAccountSupply(tokenB, lpBalanceB, _account);
_accrueAccountDebt(tokenA, _account);
_accrueAccountDebt(tokenB, _account);
accountInterestSnapshot[tokenA][_account] = cumulativeInterestRate[tokenA];
accountInterestSnapshot[tokenB][_account] = cumulativeInterestRate[tokenB];
}
function _accrueAccountSupply(address _token, uint _amount, address _account) internal {
if (_amount > 0) {
uint supplyInterest = _newInterest(_amount, _token, _account);
uint newSupplyAccount = supplyInterest * _lpRate(_token) / 100e18;
uint newSupplySystem = supplyInterest * _systemRate(_token) / 100e18;
_mintSupply(_token, _account, newSupplyAccount);
_mintSupply(_token, feeRecipient(), newSupplySystem);
}
}
function _accrueAccountDebt(address _token, address _account) internal {
if (debtOf[_token][_account] > 0) {
uint newDebt = _pendingBorrowInterest(_token, _account);
_mintDebt(_token, _account, newDebt);
}
}
function _withdraw(address _token, uint _amount) internal {
lpToken[_token].burn(msg.sender, _amount);
checkAccountHealth(msg.sender);
emit Withdraw(_token, _amount);
}
function _borrow(address _token, uint _amount) internal {
require(lpToken[_token].balanceOf(msg.sender) == 0, "LendingPair: cannot borrow supplied token");
_mintDebtWithOriginFee(_token, msg.sender, _amount);
_checkBorrowLimits(_token, msg.sender);
checkAccountHealth(msg.sender);
emit Borrow(_token, _amount);
}
function _repay(address _account, address _token, uint _amount) internal {
_burnDebt(_token, _account, _amount);
emit Repay(_account, _token, _amount);
}
function _deposit(address _account, address _token, uint _amount) internal {
_checkOracleSupport(tokenA);
_checkOracleSupport(tokenB);
require(debtOf[_token][_account] == 0, "LendingPair: cannot deposit borrowed token");
_mintSupply(_token, _account, _amount);
_checkDepositLimit(_token);
emit Deposit(_account, _token, _amount);
}
function _accrueInterest(address _token) internal {
cumulativeInterestRate[_token] += _pendingInterestRate(_token);
}
function _pendingInterestRate(address _token) internal view returns(uint) {
uint blocksElapsed = block.number - lastBlockAccrued;
return _borrowRatePerBlock(_token) * blocksElapsed;
}
function _createLpToken(address _lpTokenMaster) internal returns(IERC20) {
ILPTokenMaster newLPToken = ILPTokenMaster(_lpTokenMaster.clone());
newLPToken.initialize();
return IERC20(newLPToken);
}
function _safeTransfer(address _token, address _recipient, uint _amount) internal override {
TransferHelper._safeTransfer(_token, _recipient, _amount);
_checkMinReserve(address(_token));
}
function _wethWithdrawTo(address _to, uint _amount) internal override {
TransferHelper._wethWithdrawTo(_to, _amount);
_checkMinReserve(address(WETH));
}
function _borrowRatePerBlock(address _token) internal view returns(uint) {
return controller.interestRateModel().borrowRatePerBlock(ILendingPair(address(this)), _token);
}
function _pendingBorrowInterest(address _token, address _account) internal view returns(uint) {
return _newInterest(debtOf[_token][_account], _token, _account);
}
function _borrowBalance(
address _account,
address _borrowedToken,
address _returnToken
) internal view returns(uint) {
return _convertTokenValues(_borrowedToken, _returnToken, debtOf[_borrowedToken][_account]);
}
// Get supply balance converted to the units of _returnToken
function _supplyBalance(
address _account,
address _suppliedToken,
address _returnToken
) internal view returns(uint) {
return _convertTokenValues(_suppliedToken, _returnToken, lpToken[_suppliedToken].balanceOf(_account));
}
function _supplyCredit(
address _account,
address _suppliedToken,
address _returnToken
) internal view returns(uint) {
return _supplyBalance(_account, _suppliedToken, _returnToken) * controller.colFactor(_suppliedToken) / 100e18;
}
function _convertTokenValues(
address _fromToken,
address _toToken,
uint _inputAmount
) internal view returns(uint) {
uint priceFrom = controller.tokenPrice(_fromToken) * 1e18 / 10 ** IERC20(_fromToken).decimals();
uint priceTo = controller.tokenPrice(_toToken) * 1e18 / 10 ** IERC20(_toToken).decimals();
return _inputAmount * priceFrom / priceTo;
}
function _validateToken(address _token) internal view {
require(_token == tokenA || _token == tokenB, "LendingPair: invalid token");
}
function _checkOracleSupport(address _token) internal view {
require(controller.tokenSupported(_token), "LendingPair: token not supported");
}
function _checkMinReserve(address _token) internal view {
require(IERC20(_token).balanceOf(address(this)) >= MIN_RESERVE, "LendingPair: below MIN_RESERVE");
}
function _checkDepositLimit(address _token) internal view {
require(controller.depositsEnabled(), "LendingPair: deposits disabled");
uint depositLimit = controller.depositLimit(address(this), _token);
if (depositLimit > 0) {
require((lpToken[_token].totalSupply()) <= depositLimit, "LendingPair: deposit limit reached");
}
}
function _checkBorrowLimits(address _token, address _account) internal view {
require(controller.borrowingEnabled(), "LendingPair: borrowing disabled");
uint accountBorrowUSD = debtOf[_token][_account] * controller.tokenPrice(_token) / 1e18;
require(accountBorrowUSD >= controller.minBorrowUSD(), "LendingPair: borrow amount below minimum");
uint borrowLimit = controller.borrowLimit(address(this), _token);
if (borrowLimit > 0) {
require(totalDebt[_token] <= borrowLimit, "LendingPair: borrow limit reached");
}
}
function _originationFee(address _token, uint _amount) internal view returns(uint) {
return _amount * controller.originFee(_token) / 100e18;
}
function _systemRate(address _token) internal view returns(uint) {
return controller.interestRateModel().systemRate(ILendingPair(address(this)), _token);
}
function _lpRate(address _token) internal view returns(uint) {
return 100e18 - _systemRate(_token);
}
function _newInterest(uint _balance, address _token, address _account) internal view returns(uint) {
uint currentCumulativeRate = cumulativeInterestRate[_token] + _pendingInterestRate(_token);
return _balance * (currentCumulativeRate - accountInterestSnapshot[_token][_account]) / 100e18;
}
// Used in repayAll and repayAllETH to prevent front-running
// Potential attack:
// Recipient account watches the mempool and takes out a large loan just before someone calls repayAll.
// As a result, paying account would end up paying much more than anticipated
function _requireAccountNotAccrued(address _token, address _account) internal view {
if (lastBlockAccrued == block.number && cumulativeInterestRate[_token] > 0) {
require(
cumulativeInterestRate[_token] > accountInterestSnapshot[_token][_account],
"LendingPair: account already accrued"
);
}
}
} | borrowBalance | function borrowBalance(
address _account,
address _borrowedToken,
address _returnToken
) external view returns(uint) {
_validateToken(_borrowedToken);
_validateToken(_returnToken);
return _borrowBalance(_account, _borrowedToken, _returnToken);
}
| // Get borow balance converted to the units of _returnToken | LineComment | v0.8.6+commit.11564f7e | None | ipfs://4d03a265a12ba81c0f5a175a2642e8e9fa5be73fda205ebdaf6e808e4fd675db | {
"func_code_index": [
7827,
8115
]
} | 3,663 |
||
PairFactory | PairFactory.sol | 0x23b74796b72f995e14a5e3ff2156dad9653256cf | Solidity | LendingPair | contract LendingPair is TransferHelper, ReentrancyGuard {
// Prevents division by zero and other undesirable behaviour
uint private constant MIN_RESERVE = 1000;
using Address for address;
using Clones for address;
mapping (address => mapping (address => uint)) public debtOf;
mapping (address => mapping (address => uint)) public accountInterestSnapshot;
mapping (address => uint) public cumulativeInterestRate; // 100e18 = 100%
mapping (address => uint) public totalDebt;
mapping (address => IERC20) public lpToken;
IController public controller;
address public tokenA;
address public tokenB;
uint public lastBlockAccrued;
event Liquidation(
address indexed account,
address indexed repayToken,
address indexed supplyToken,
uint repayAmount,
uint supplyAmount
);
event Deposit(address indexed account, address indexed token, uint amount);
event Withdraw(address indexed token, uint amount);
event Borrow(address indexed token, uint amount);
event Repay(address indexed account, address indexed token, uint amount);
receive() external payable {}
function initialize(
address _lpTokenMaster,
address _controller,
IERC20 _tokenA,
IERC20 _tokenB
) external {
require(address(tokenA) == address(0), "LendingPair: already initialized");
require(address(_tokenA) != address(0) && address(_tokenB) != address(0), "LendingPair: cannot be ZERO address");
controller = IController(_controller);
tokenA = address(_tokenA);
tokenB = address(_tokenB);
lastBlockAccrued = block.number;
lpToken[tokenA] = _createLpToken(_lpTokenMaster);
lpToken[tokenB] = _createLpToken(_lpTokenMaster);
}
function depositRepay(address _account, address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(_account);
_depositRepay(_account, _token, _amount);
_safeTransferFrom(_token, msg.sender, _amount);
}
function depositRepayETH(address _account) external payable nonReentrant {
_validateToken(address(WETH));
accrueAccount(_account);
_depositRepay(_account, address(WETH), msg.value);
_depositWeth();
}
function deposit(address _account, address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(_account);
_deposit(_account, _token, _amount);
_safeTransferFrom(_token, msg.sender, _amount);
}
function withdrawBorrow(address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(msg.sender);
_withdrawBorrow(_token, _amount);
_safeTransfer(_token, msg.sender, _amount);
}
function withdrawBorrowETH(uint _amount) external nonReentrant {
_validateToken(address(WETH));
accrueAccount(msg.sender);
_withdrawBorrow(address(WETH), _amount);
_wethWithdrawTo(msg.sender, _amount);
}
function withdraw(address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(msg.sender);
_withdraw(_token, _amount);
_safeTransfer(_token, msg.sender, _amount);
}
function withdrawAll(address _token) external nonReentrant {
_validateToken(_token);
accrueAccount(msg.sender);
uint amount = lpToken[_token].balanceOf(msg.sender);
_withdraw(_token, amount);
_safeTransfer(_token, msg.sender, amount);
}
function withdrawAllETH() external nonReentrant {
_validateToken(address(WETH));
accrueAccount(msg.sender);
uint amount = lpToken[address(WETH)].balanceOf(msg.sender);
_withdraw(address(WETH), amount);
_wethWithdrawTo(msg.sender, amount);
}
function borrow(address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(msg.sender);
_borrow(_token, _amount);
_safeTransfer(_token, msg.sender, _amount);
}
function repayAll(address _account, address _token) external nonReentrant {
_validateToken(_token);
_requireAccountNotAccrued(_token, _account);
accrueAccount(_account);
uint amount = debtOf[_token][_account];
_repay(_account, _token, amount);
_safeTransferFrom(_token, msg.sender, amount);
}
function repayAllETH(address _account) external payable nonReentrant {
_validateToken(address(WETH));
_requireAccountNotAccrued(address(WETH), _account);
accrueAccount(_account);
uint amount = debtOf[address(WETH)][_account];
require(msg.value >= amount, "LendingPair: insufficient ETH deposit");
_depositWeth();
_repay(_account, address(WETH), amount);
uint refundAmount = msg.value > amount ? (msg.value - amount) : 0;
if (refundAmount > 0) {
_wethWithdrawTo(msg.sender, refundAmount);
}
}
function repay(address _account, address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(_account);
_repay(_account, _token, _amount);
_safeTransferFrom(_token, msg.sender, _amount);
}
function accrue() public {
if (lastBlockAccrued < block.number) {
_accrueInterest(tokenA);
_accrueInterest(tokenB);
lastBlockAccrued = block.number;
}
}
function accrueAccount(address _account) public {
_distributeReward(_account);
accrue();
_accrueAccountInterest(_account);
if (_account != feeRecipient()) {
_accrueAccountInterest(feeRecipient());
}
}
// Sell collateral to reduce debt and increase accountHealth
// Set _repayAmount to uint(-1) to repay all debt, inc. pending interest
function liquidateAccount(
address _account,
address _repayToken,
uint _repayAmount,
uint _minSupplyOutput
) external nonReentrant {
// Input validation and adjustments
_validateToken(_repayToken);
address supplyToken = _repayToken == tokenA ? tokenB : tokenA;
// Check account is underwater after interest
accrueAccount(_account);
uint health = accountHealth(_account);
require(health < controller.LIQ_MIN_HEALTH(), "LendingPair: account health < LIQ_MIN_HEALTH");
// Calculate balance adjustments
_repayAmount = Math.min(_repayAmount, debtOf[_repayToken][_account]);
uint supplyDebt = _convertTokenValues(_repayToken, supplyToken, _repayAmount);
uint callerFee = supplyDebt * controller.liqFeeCaller(_repayToken) / 100e18;
uint systemFee = supplyDebt * controller.liqFeeSystem(_repayToken) / 100e18;
uint supplyBurn = supplyDebt + callerFee + systemFee;
uint supplyOutput = supplyDebt + callerFee;
require(supplyOutput >= _minSupplyOutput, "LendingPair: supplyOutput >= _minSupplyOutput");
// Adjust balances
_burnSupply(supplyToken, _account, supplyBurn);
_mintSupply(supplyToken, feeRecipient(), systemFee);
_burnDebt(_repayToken, _account, _repayAmount);
// Settle token transfers
_safeTransferFrom(_repayToken, msg.sender, _repayAmount);
_mintSupply(supplyToken, msg.sender, supplyOutput);
emit Liquidation(_account, _repayToken, supplyToken, _repayAmount, supplyOutput);
}
function accountHealth(address _account) public view returns(uint) {
if (debtOf[tokenA][_account] == 0 && debtOf[tokenB][_account] == 0) {
return controller.LIQ_MIN_HEALTH();
}
uint totalAccountSupply = _supplyCredit(_account, tokenA, tokenA) + _supplyCredit(_account, tokenB, tokenA);
uint totalAccountBorrow = _borrowBalance(_account, tokenA, tokenA) + _borrowBalance(_account, tokenB, tokenA);
return totalAccountSupply * 1e18 / totalAccountBorrow;
}
// Get borow balance converted to the units of _returnToken
function borrowBalance(
address _account,
address _borrowedToken,
address _returnToken
) external view returns(uint) {
_validateToken(_borrowedToken);
_validateToken(_returnToken);
return _borrowBalance(_account, _borrowedToken, _returnToken);
}
function supplyBalance(
address _account,
address _suppliedToken,
address _returnToken
) external view returns(uint) {
_validateToken(_suppliedToken);
_validateToken(_returnToken);
return _supplyBalance(_account, _suppliedToken, _returnToken);
}
function supplyRatePerBlock(address _token) external view returns(uint) {
_validateToken(_token);
return controller.interestRateModel().supplyRatePerBlock(ILendingPair(address(this)), _token);
}
function borrowRatePerBlock(address _token) external view returns(uint) {
_validateToken(_token);
return _borrowRatePerBlock(_token);
}
function pendingSupplyInterest(address _token, address _account) external view returns(uint) {
_validateToken(_token);
uint newInterest = _newInterest(lpToken[_token].balanceOf(_account), _token, _account);
return newInterest * _lpRate(_token) / 100e18;
}
function pendingBorrowInterest(address _token, address _account) external view returns(uint) {
_validateToken(_token);
return _pendingBorrowInterest(_token, _account);
}
function feeRecipient() public view returns(address) {
return controller.feeRecipient();
}
function checkAccountHealth(address _account) public view {
uint health = accountHealth(_account);
require(health >= controller.LIQ_MIN_HEALTH(), "LendingPair: insufficient accountHealth");
}
function convertTokenValues(
address _fromToken,
address _toToken,
uint _inputAmount
) external view returns(uint) {
_validateToken(_fromToken);
_validateToken(_toToken);
return _convertTokenValues(_fromToken, _toToken, _inputAmount);
}
function _depositRepay(address _account, address _token, uint _amount) internal {
uint debt = debtOf[_token][_account];
uint repayAmount = debt > _amount ? _amount : debt;
if (repayAmount > 0) {
_repay(_account, _token, repayAmount);
}
uint depositAmount = _amount - repayAmount;
if (depositAmount > 0) {
_deposit(_account, _token, depositAmount);
}
}
function _withdrawBorrow(address _token, uint _amount) internal {
uint supplyAmount = lpToken[_token].balanceOf(msg.sender);
uint withdrawAmount = supplyAmount > _amount ? _amount : supplyAmount;
if (withdrawAmount > 0) {
_withdraw(_token, withdrawAmount);
}
uint borrowAmount = _amount - withdrawAmount;
if (borrowAmount > 0) {
_borrow(_token, borrowAmount);
}
}
function _distributeReward(address _account) internal {
IRewardDistribution rewardDistribution = controller.rewardDistribution();
if (
address(rewardDistribution) != address(0) &&
_account != feeRecipient()
) {
rewardDistribution.distributeReward(_account, tokenA);
rewardDistribution.distributeReward(_account, tokenB);
}
}
function _mintSupply(address _token, address _account, uint _amount) internal {
if (_amount > 0) {
lpToken[_token].mint(_account, _amount);
}
}
function _burnSupply(address _token, address _account, uint _amount) internal {
if (_amount > 0) {
lpToken[_token].burn(_account, _amount);
}
}
function _mintDebt(address _token, address _account, uint _amount) internal {
debtOf[_token][_account] += _amount;
totalDebt[_token] += _amount;
}
// Origination fee is earned entirely by the protocol and is not split with the LPs
// The goal is to prevent free flash loans
function _mintDebtWithOriginFee(address _token, address _account, uint _amount) internal {
uint originFee = _originationFee(_token, _amount);
_mintSupply(_token, feeRecipient(), originFee);
_mintDebt(_token, _account, _amount + originFee);
}
function _burnDebt(address _token, address _account, uint _amount) internal {
debtOf[_token][_account] -= _amount;
totalDebt[_token] -= _amount;
}
function _accrueAccountInterest(address _account) internal {
uint lpBalanceA = lpToken[tokenA].balanceOf(_account);
uint lpBalanceB = lpToken[tokenB].balanceOf(_account);
_accrueAccountSupply(tokenA, lpBalanceA, _account);
_accrueAccountSupply(tokenB, lpBalanceB, _account);
_accrueAccountDebt(tokenA, _account);
_accrueAccountDebt(tokenB, _account);
accountInterestSnapshot[tokenA][_account] = cumulativeInterestRate[tokenA];
accountInterestSnapshot[tokenB][_account] = cumulativeInterestRate[tokenB];
}
function _accrueAccountSupply(address _token, uint _amount, address _account) internal {
if (_amount > 0) {
uint supplyInterest = _newInterest(_amount, _token, _account);
uint newSupplyAccount = supplyInterest * _lpRate(_token) / 100e18;
uint newSupplySystem = supplyInterest * _systemRate(_token) / 100e18;
_mintSupply(_token, _account, newSupplyAccount);
_mintSupply(_token, feeRecipient(), newSupplySystem);
}
}
function _accrueAccountDebt(address _token, address _account) internal {
if (debtOf[_token][_account] > 0) {
uint newDebt = _pendingBorrowInterest(_token, _account);
_mintDebt(_token, _account, newDebt);
}
}
function _withdraw(address _token, uint _amount) internal {
lpToken[_token].burn(msg.sender, _amount);
checkAccountHealth(msg.sender);
emit Withdraw(_token, _amount);
}
function _borrow(address _token, uint _amount) internal {
require(lpToken[_token].balanceOf(msg.sender) == 0, "LendingPair: cannot borrow supplied token");
_mintDebtWithOriginFee(_token, msg.sender, _amount);
_checkBorrowLimits(_token, msg.sender);
checkAccountHealth(msg.sender);
emit Borrow(_token, _amount);
}
function _repay(address _account, address _token, uint _amount) internal {
_burnDebt(_token, _account, _amount);
emit Repay(_account, _token, _amount);
}
function _deposit(address _account, address _token, uint _amount) internal {
_checkOracleSupport(tokenA);
_checkOracleSupport(tokenB);
require(debtOf[_token][_account] == 0, "LendingPair: cannot deposit borrowed token");
_mintSupply(_token, _account, _amount);
_checkDepositLimit(_token);
emit Deposit(_account, _token, _amount);
}
function _accrueInterest(address _token) internal {
cumulativeInterestRate[_token] += _pendingInterestRate(_token);
}
function _pendingInterestRate(address _token) internal view returns(uint) {
uint blocksElapsed = block.number - lastBlockAccrued;
return _borrowRatePerBlock(_token) * blocksElapsed;
}
function _createLpToken(address _lpTokenMaster) internal returns(IERC20) {
ILPTokenMaster newLPToken = ILPTokenMaster(_lpTokenMaster.clone());
newLPToken.initialize();
return IERC20(newLPToken);
}
function _safeTransfer(address _token, address _recipient, uint _amount) internal override {
TransferHelper._safeTransfer(_token, _recipient, _amount);
_checkMinReserve(address(_token));
}
function _wethWithdrawTo(address _to, uint _amount) internal override {
TransferHelper._wethWithdrawTo(_to, _amount);
_checkMinReserve(address(WETH));
}
function _borrowRatePerBlock(address _token) internal view returns(uint) {
return controller.interestRateModel().borrowRatePerBlock(ILendingPair(address(this)), _token);
}
function _pendingBorrowInterest(address _token, address _account) internal view returns(uint) {
return _newInterest(debtOf[_token][_account], _token, _account);
}
function _borrowBalance(
address _account,
address _borrowedToken,
address _returnToken
) internal view returns(uint) {
return _convertTokenValues(_borrowedToken, _returnToken, debtOf[_borrowedToken][_account]);
}
// Get supply balance converted to the units of _returnToken
function _supplyBalance(
address _account,
address _suppliedToken,
address _returnToken
) internal view returns(uint) {
return _convertTokenValues(_suppliedToken, _returnToken, lpToken[_suppliedToken].balanceOf(_account));
}
function _supplyCredit(
address _account,
address _suppliedToken,
address _returnToken
) internal view returns(uint) {
return _supplyBalance(_account, _suppliedToken, _returnToken) * controller.colFactor(_suppliedToken) / 100e18;
}
function _convertTokenValues(
address _fromToken,
address _toToken,
uint _inputAmount
) internal view returns(uint) {
uint priceFrom = controller.tokenPrice(_fromToken) * 1e18 / 10 ** IERC20(_fromToken).decimals();
uint priceTo = controller.tokenPrice(_toToken) * 1e18 / 10 ** IERC20(_toToken).decimals();
return _inputAmount * priceFrom / priceTo;
}
function _validateToken(address _token) internal view {
require(_token == tokenA || _token == tokenB, "LendingPair: invalid token");
}
function _checkOracleSupport(address _token) internal view {
require(controller.tokenSupported(_token), "LendingPair: token not supported");
}
function _checkMinReserve(address _token) internal view {
require(IERC20(_token).balanceOf(address(this)) >= MIN_RESERVE, "LendingPair: below MIN_RESERVE");
}
function _checkDepositLimit(address _token) internal view {
require(controller.depositsEnabled(), "LendingPair: deposits disabled");
uint depositLimit = controller.depositLimit(address(this), _token);
if (depositLimit > 0) {
require((lpToken[_token].totalSupply()) <= depositLimit, "LendingPair: deposit limit reached");
}
}
function _checkBorrowLimits(address _token, address _account) internal view {
require(controller.borrowingEnabled(), "LendingPair: borrowing disabled");
uint accountBorrowUSD = debtOf[_token][_account] * controller.tokenPrice(_token) / 1e18;
require(accountBorrowUSD >= controller.minBorrowUSD(), "LendingPair: borrow amount below minimum");
uint borrowLimit = controller.borrowLimit(address(this), _token);
if (borrowLimit > 0) {
require(totalDebt[_token] <= borrowLimit, "LendingPair: borrow limit reached");
}
}
function _originationFee(address _token, uint _amount) internal view returns(uint) {
return _amount * controller.originFee(_token) / 100e18;
}
function _systemRate(address _token) internal view returns(uint) {
return controller.interestRateModel().systemRate(ILendingPair(address(this)), _token);
}
function _lpRate(address _token) internal view returns(uint) {
return 100e18 - _systemRate(_token);
}
function _newInterest(uint _balance, address _token, address _account) internal view returns(uint) {
uint currentCumulativeRate = cumulativeInterestRate[_token] + _pendingInterestRate(_token);
return _balance * (currentCumulativeRate - accountInterestSnapshot[_token][_account]) / 100e18;
}
// Used in repayAll and repayAllETH to prevent front-running
// Potential attack:
// Recipient account watches the mempool and takes out a large loan just before someone calls repayAll.
// As a result, paying account would end up paying much more than anticipated
function _requireAccountNotAccrued(address _token, address _account) internal view {
if (lastBlockAccrued == block.number && cumulativeInterestRate[_token] > 0) {
require(
cumulativeInterestRate[_token] > accountInterestSnapshot[_token][_account],
"LendingPair: account already accrued"
);
}
}
} | _mintDebtWithOriginFee | function _mintDebtWithOriginFee(address _token, address _account, uint _amount) internal {
uint originFee = _originationFee(_token, _amount);
_mintSupply(_token, feeRecipient(), originFee);
_mintDebt(_token, _account, _amount + originFee);
}
| // Origination fee is earned entirely by the protocol and is not split with the LPs
// The goal is to prevent free flash loans | LineComment | v0.8.6+commit.11564f7e | None | ipfs://4d03a265a12ba81c0f5a175a2642e8e9fa5be73fda205ebdaf6e808e4fd675db | {
"func_code_index": [
11708,
11970
]
} | 3,664 |
||
PairFactory | PairFactory.sol | 0x23b74796b72f995e14a5e3ff2156dad9653256cf | Solidity | LendingPair | contract LendingPair is TransferHelper, ReentrancyGuard {
// Prevents division by zero and other undesirable behaviour
uint private constant MIN_RESERVE = 1000;
using Address for address;
using Clones for address;
mapping (address => mapping (address => uint)) public debtOf;
mapping (address => mapping (address => uint)) public accountInterestSnapshot;
mapping (address => uint) public cumulativeInterestRate; // 100e18 = 100%
mapping (address => uint) public totalDebt;
mapping (address => IERC20) public lpToken;
IController public controller;
address public tokenA;
address public tokenB;
uint public lastBlockAccrued;
event Liquidation(
address indexed account,
address indexed repayToken,
address indexed supplyToken,
uint repayAmount,
uint supplyAmount
);
event Deposit(address indexed account, address indexed token, uint amount);
event Withdraw(address indexed token, uint amount);
event Borrow(address indexed token, uint amount);
event Repay(address indexed account, address indexed token, uint amount);
receive() external payable {}
function initialize(
address _lpTokenMaster,
address _controller,
IERC20 _tokenA,
IERC20 _tokenB
) external {
require(address(tokenA) == address(0), "LendingPair: already initialized");
require(address(_tokenA) != address(0) && address(_tokenB) != address(0), "LendingPair: cannot be ZERO address");
controller = IController(_controller);
tokenA = address(_tokenA);
tokenB = address(_tokenB);
lastBlockAccrued = block.number;
lpToken[tokenA] = _createLpToken(_lpTokenMaster);
lpToken[tokenB] = _createLpToken(_lpTokenMaster);
}
function depositRepay(address _account, address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(_account);
_depositRepay(_account, _token, _amount);
_safeTransferFrom(_token, msg.sender, _amount);
}
function depositRepayETH(address _account) external payable nonReentrant {
_validateToken(address(WETH));
accrueAccount(_account);
_depositRepay(_account, address(WETH), msg.value);
_depositWeth();
}
function deposit(address _account, address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(_account);
_deposit(_account, _token, _amount);
_safeTransferFrom(_token, msg.sender, _amount);
}
function withdrawBorrow(address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(msg.sender);
_withdrawBorrow(_token, _amount);
_safeTransfer(_token, msg.sender, _amount);
}
function withdrawBorrowETH(uint _amount) external nonReentrant {
_validateToken(address(WETH));
accrueAccount(msg.sender);
_withdrawBorrow(address(WETH), _amount);
_wethWithdrawTo(msg.sender, _amount);
}
function withdraw(address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(msg.sender);
_withdraw(_token, _amount);
_safeTransfer(_token, msg.sender, _amount);
}
function withdrawAll(address _token) external nonReentrant {
_validateToken(_token);
accrueAccount(msg.sender);
uint amount = lpToken[_token].balanceOf(msg.sender);
_withdraw(_token, amount);
_safeTransfer(_token, msg.sender, amount);
}
function withdrawAllETH() external nonReentrant {
_validateToken(address(WETH));
accrueAccount(msg.sender);
uint amount = lpToken[address(WETH)].balanceOf(msg.sender);
_withdraw(address(WETH), amount);
_wethWithdrawTo(msg.sender, amount);
}
function borrow(address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(msg.sender);
_borrow(_token, _amount);
_safeTransfer(_token, msg.sender, _amount);
}
function repayAll(address _account, address _token) external nonReentrant {
_validateToken(_token);
_requireAccountNotAccrued(_token, _account);
accrueAccount(_account);
uint amount = debtOf[_token][_account];
_repay(_account, _token, amount);
_safeTransferFrom(_token, msg.sender, amount);
}
function repayAllETH(address _account) external payable nonReentrant {
_validateToken(address(WETH));
_requireAccountNotAccrued(address(WETH), _account);
accrueAccount(_account);
uint amount = debtOf[address(WETH)][_account];
require(msg.value >= amount, "LendingPair: insufficient ETH deposit");
_depositWeth();
_repay(_account, address(WETH), amount);
uint refundAmount = msg.value > amount ? (msg.value - amount) : 0;
if (refundAmount > 0) {
_wethWithdrawTo(msg.sender, refundAmount);
}
}
function repay(address _account, address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(_account);
_repay(_account, _token, _amount);
_safeTransferFrom(_token, msg.sender, _amount);
}
function accrue() public {
if (lastBlockAccrued < block.number) {
_accrueInterest(tokenA);
_accrueInterest(tokenB);
lastBlockAccrued = block.number;
}
}
function accrueAccount(address _account) public {
_distributeReward(_account);
accrue();
_accrueAccountInterest(_account);
if (_account != feeRecipient()) {
_accrueAccountInterest(feeRecipient());
}
}
// Sell collateral to reduce debt and increase accountHealth
// Set _repayAmount to uint(-1) to repay all debt, inc. pending interest
function liquidateAccount(
address _account,
address _repayToken,
uint _repayAmount,
uint _minSupplyOutput
) external nonReentrant {
// Input validation and adjustments
_validateToken(_repayToken);
address supplyToken = _repayToken == tokenA ? tokenB : tokenA;
// Check account is underwater after interest
accrueAccount(_account);
uint health = accountHealth(_account);
require(health < controller.LIQ_MIN_HEALTH(), "LendingPair: account health < LIQ_MIN_HEALTH");
// Calculate balance adjustments
_repayAmount = Math.min(_repayAmount, debtOf[_repayToken][_account]);
uint supplyDebt = _convertTokenValues(_repayToken, supplyToken, _repayAmount);
uint callerFee = supplyDebt * controller.liqFeeCaller(_repayToken) / 100e18;
uint systemFee = supplyDebt * controller.liqFeeSystem(_repayToken) / 100e18;
uint supplyBurn = supplyDebt + callerFee + systemFee;
uint supplyOutput = supplyDebt + callerFee;
require(supplyOutput >= _minSupplyOutput, "LendingPair: supplyOutput >= _minSupplyOutput");
// Adjust balances
_burnSupply(supplyToken, _account, supplyBurn);
_mintSupply(supplyToken, feeRecipient(), systemFee);
_burnDebt(_repayToken, _account, _repayAmount);
// Settle token transfers
_safeTransferFrom(_repayToken, msg.sender, _repayAmount);
_mintSupply(supplyToken, msg.sender, supplyOutput);
emit Liquidation(_account, _repayToken, supplyToken, _repayAmount, supplyOutput);
}
function accountHealth(address _account) public view returns(uint) {
if (debtOf[tokenA][_account] == 0 && debtOf[tokenB][_account] == 0) {
return controller.LIQ_MIN_HEALTH();
}
uint totalAccountSupply = _supplyCredit(_account, tokenA, tokenA) + _supplyCredit(_account, tokenB, tokenA);
uint totalAccountBorrow = _borrowBalance(_account, tokenA, tokenA) + _borrowBalance(_account, tokenB, tokenA);
return totalAccountSupply * 1e18 / totalAccountBorrow;
}
// Get borow balance converted to the units of _returnToken
function borrowBalance(
address _account,
address _borrowedToken,
address _returnToken
) external view returns(uint) {
_validateToken(_borrowedToken);
_validateToken(_returnToken);
return _borrowBalance(_account, _borrowedToken, _returnToken);
}
function supplyBalance(
address _account,
address _suppliedToken,
address _returnToken
) external view returns(uint) {
_validateToken(_suppliedToken);
_validateToken(_returnToken);
return _supplyBalance(_account, _suppliedToken, _returnToken);
}
function supplyRatePerBlock(address _token) external view returns(uint) {
_validateToken(_token);
return controller.interestRateModel().supplyRatePerBlock(ILendingPair(address(this)), _token);
}
function borrowRatePerBlock(address _token) external view returns(uint) {
_validateToken(_token);
return _borrowRatePerBlock(_token);
}
function pendingSupplyInterest(address _token, address _account) external view returns(uint) {
_validateToken(_token);
uint newInterest = _newInterest(lpToken[_token].balanceOf(_account), _token, _account);
return newInterest * _lpRate(_token) / 100e18;
}
function pendingBorrowInterest(address _token, address _account) external view returns(uint) {
_validateToken(_token);
return _pendingBorrowInterest(_token, _account);
}
function feeRecipient() public view returns(address) {
return controller.feeRecipient();
}
function checkAccountHealth(address _account) public view {
uint health = accountHealth(_account);
require(health >= controller.LIQ_MIN_HEALTH(), "LendingPair: insufficient accountHealth");
}
function convertTokenValues(
address _fromToken,
address _toToken,
uint _inputAmount
) external view returns(uint) {
_validateToken(_fromToken);
_validateToken(_toToken);
return _convertTokenValues(_fromToken, _toToken, _inputAmount);
}
function _depositRepay(address _account, address _token, uint _amount) internal {
uint debt = debtOf[_token][_account];
uint repayAmount = debt > _amount ? _amount : debt;
if (repayAmount > 0) {
_repay(_account, _token, repayAmount);
}
uint depositAmount = _amount - repayAmount;
if (depositAmount > 0) {
_deposit(_account, _token, depositAmount);
}
}
function _withdrawBorrow(address _token, uint _amount) internal {
uint supplyAmount = lpToken[_token].balanceOf(msg.sender);
uint withdrawAmount = supplyAmount > _amount ? _amount : supplyAmount;
if (withdrawAmount > 0) {
_withdraw(_token, withdrawAmount);
}
uint borrowAmount = _amount - withdrawAmount;
if (borrowAmount > 0) {
_borrow(_token, borrowAmount);
}
}
function _distributeReward(address _account) internal {
IRewardDistribution rewardDistribution = controller.rewardDistribution();
if (
address(rewardDistribution) != address(0) &&
_account != feeRecipient()
) {
rewardDistribution.distributeReward(_account, tokenA);
rewardDistribution.distributeReward(_account, tokenB);
}
}
function _mintSupply(address _token, address _account, uint _amount) internal {
if (_amount > 0) {
lpToken[_token].mint(_account, _amount);
}
}
function _burnSupply(address _token, address _account, uint _amount) internal {
if (_amount > 0) {
lpToken[_token].burn(_account, _amount);
}
}
function _mintDebt(address _token, address _account, uint _amount) internal {
debtOf[_token][_account] += _amount;
totalDebt[_token] += _amount;
}
// Origination fee is earned entirely by the protocol and is not split with the LPs
// The goal is to prevent free flash loans
function _mintDebtWithOriginFee(address _token, address _account, uint _amount) internal {
uint originFee = _originationFee(_token, _amount);
_mintSupply(_token, feeRecipient(), originFee);
_mintDebt(_token, _account, _amount + originFee);
}
function _burnDebt(address _token, address _account, uint _amount) internal {
debtOf[_token][_account] -= _amount;
totalDebt[_token] -= _amount;
}
function _accrueAccountInterest(address _account) internal {
uint lpBalanceA = lpToken[tokenA].balanceOf(_account);
uint lpBalanceB = lpToken[tokenB].balanceOf(_account);
_accrueAccountSupply(tokenA, lpBalanceA, _account);
_accrueAccountSupply(tokenB, lpBalanceB, _account);
_accrueAccountDebt(tokenA, _account);
_accrueAccountDebt(tokenB, _account);
accountInterestSnapshot[tokenA][_account] = cumulativeInterestRate[tokenA];
accountInterestSnapshot[tokenB][_account] = cumulativeInterestRate[tokenB];
}
function _accrueAccountSupply(address _token, uint _amount, address _account) internal {
if (_amount > 0) {
uint supplyInterest = _newInterest(_amount, _token, _account);
uint newSupplyAccount = supplyInterest * _lpRate(_token) / 100e18;
uint newSupplySystem = supplyInterest * _systemRate(_token) / 100e18;
_mintSupply(_token, _account, newSupplyAccount);
_mintSupply(_token, feeRecipient(), newSupplySystem);
}
}
function _accrueAccountDebt(address _token, address _account) internal {
if (debtOf[_token][_account] > 0) {
uint newDebt = _pendingBorrowInterest(_token, _account);
_mintDebt(_token, _account, newDebt);
}
}
function _withdraw(address _token, uint _amount) internal {
lpToken[_token].burn(msg.sender, _amount);
checkAccountHealth(msg.sender);
emit Withdraw(_token, _amount);
}
function _borrow(address _token, uint _amount) internal {
require(lpToken[_token].balanceOf(msg.sender) == 0, "LendingPair: cannot borrow supplied token");
_mintDebtWithOriginFee(_token, msg.sender, _amount);
_checkBorrowLimits(_token, msg.sender);
checkAccountHealth(msg.sender);
emit Borrow(_token, _amount);
}
function _repay(address _account, address _token, uint _amount) internal {
_burnDebt(_token, _account, _amount);
emit Repay(_account, _token, _amount);
}
function _deposit(address _account, address _token, uint _amount) internal {
_checkOracleSupport(tokenA);
_checkOracleSupport(tokenB);
require(debtOf[_token][_account] == 0, "LendingPair: cannot deposit borrowed token");
_mintSupply(_token, _account, _amount);
_checkDepositLimit(_token);
emit Deposit(_account, _token, _amount);
}
function _accrueInterest(address _token) internal {
cumulativeInterestRate[_token] += _pendingInterestRate(_token);
}
function _pendingInterestRate(address _token) internal view returns(uint) {
uint blocksElapsed = block.number - lastBlockAccrued;
return _borrowRatePerBlock(_token) * blocksElapsed;
}
function _createLpToken(address _lpTokenMaster) internal returns(IERC20) {
ILPTokenMaster newLPToken = ILPTokenMaster(_lpTokenMaster.clone());
newLPToken.initialize();
return IERC20(newLPToken);
}
function _safeTransfer(address _token, address _recipient, uint _amount) internal override {
TransferHelper._safeTransfer(_token, _recipient, _amount);
_checkMinReserve(address(_token));
}
function _wethWithdrawTo(address _to, uint _amount) internal override {
TransferHelper._wethWithdrawTo(_to, _amount);
_checkMinReserve(address(WETH));
}
function _borrowRatePerBlock(address _token) internal view returns(uint) {
return controller.interestRateModel().borrowRatePerBlock(ILendingPair(address(this)), _token);
}
function _pendingBorrowInterest(address _token, address _account) internal view returns(uint) {
return _newInterest(debtOf[_token][_account], _token, _account);
}
function _borrowBalance(
address _account,
address _borrowedToken,
address _returnToken
) internal view returns(uint) {
return _convertTokenValues(_borrowedToken, _returnToken, debtOf[_borrowedToken][_account]);
}
// Get supply balance converted to the units of _returnToken
function _supplyBalance(
address _account,
address _suppliedToken,
address _returnToken
) internal view returns(uint) {
return _convertTokenValues(_suppliedToken, _returnToken, lpToken[_suppliedToken].balanceOf(_account));
}
function _supplyCredit(
address _account,
address _suppliedToken,
address _returnToken
) internal view returns(uint) {
return _supplyBalance(_account, _suppliedToken, _returnToken) * controller.colFactor(_suppliedToken) / 100e18;
}
function _convertTokenValues(
address _fromToken,
address _toToken,
uint _inputAmount
) internal view returns(uint) {
uint priceFrom = controller.tokenPrice(_fromToken) * 1e18 / 10 ** IERC20(_fromToken).decimals();
uint priceTo = controller.tokenPrice(_toToken) * 1e18 / 10 ** IERC20(_toToken).decimals();
return _inputAmount * priceFrom / priceTo;
}
function _validateToken(address _token) internal view {
require(_token == tokenA || _token == tokenB, "LendingPair: invalid token");
}
function _checkOracleSupport(address _token) internal view {
require(controller.tokenSupported(_token), "LendingPair: token not supported");
}
function _checkMinReserve(address _token) internal view {
require(IERC20(_token).balanceOf(address(this)) >= MIN_RESERVE, "LendingPair: below MIN_RESERVE");
}
function _checkDepositLimit(address _token) internal view {
require(controller.depositsEnabled(), "LendingPair: deposits disabled");
uint depositLimit = controller.depositLimit(address(this), _token);
if (depositLimit > 0) {
require((lpToken[_token].totalSupply()) <= depositLimit, "LendingPair: deposit limit reached");
}
}
function _checkBorrowLimits(address _token, address _account) internal view {
require(controller.borrowingEnabled(), "LendingPair: borrowing disabled");
uint accountBorrowUSD = debtOf[_token][_account] * controller.tokenPrice(_token) / 1e18;
require(accountBorrowUSD >= controller.minBorrowUSD(), "LendingPair: borrow amount below minimum");
uint borrowLimit = controller.borrowLimit(address(this), _token);
if (borrowLimit > 0) {
require(totalDebt[_token] <= borrowLimit, "LendingPair: borrow limit reached");
}
}
function _originationFee(address _token, uint _amount) internal view returns(uint) {
return _amount * controller.originFee(_token) / 100e18;
}
function _systemRate(address _token) internal view returns(uint) {
return controller.interestRateModel().systemRate(ILendingPair(address(this)), _token);
}
function _lpRate(address _token) internal view returns(uint) {
return 100e18 - _systemRate(_token);
}
function _newInterest(uint _balance, address _token, address _account) internal view returns(uint) {
uint currentCumulativeRate = cumulativeInterestRate[_token] + _pendingInterestRate(_token);
return _balance * (currentCumulativeRate - accountInterestSnapshot[_token][_account]) / 100e18;
}
// Used in repayAll and repayAllETH to prevent front-running
// Potential attack:
// Recipient account watches the mempool and takes out a large loan just before someone calls repayAll.
// As a result, paying account would end up paying much more than anticipated
function _requireAccountNotAccrued(address _token, address _account) internal view {
if (lastBlockAccrued == block.number && cumulativeInterestRate[_token] > 0) {
require(
cumulativeInterestRate[_token] > accountInterestSnapshot[_token][_account],
"LendingPair: account already accrued"
);
}
}
} | _supplyBalance | function _supplyBalance(
address _account,
address _suppliedToken,
address _returnToken
) internal view returns(uint) {
return _convertTokenValues(_suppliedToken, _returnToken, lpToken[_suppliedToken].balanceOf(_account));
}
| // Get supply balance converted to the units of _returnToken | LineComment | v0.8.6+commit.11564f7e | None | ipfs://4d03a265a12ba81c0f5a175a2642e8e9fa5be73fda205ebdaf6e808e4fd675db | {
"func_code_index": [
16113,
16368
]
} | 3,665 |
||
PairFactory | PairFactory.sol | 0x23b74796b72f995e14a5e3ff2156dad9653256cf | Solidity | LendingPair | contract LendingPair is TransferHelper, ReentrancyGuard {
// Prevents division by zero and other undesirable behaviour
uint private constant MIN_RESERVE = 1000;
using Address for address;
using Clones for address;
mapping (address => mapping (address => uint)) public debtOf;
mapping (address => mapping (address => uint)) public accountInterestSnapshot;
mapping (address => uint) public cumulativeInterestRate; // 100e18 = 100%
mapping (address => uint) public totalDebt;
mapping (address => IERC20) public lpToken;
IController public controller;
address public tokenA;
address public tokenB;
uint public lastBlockAccrued;
event Liquidation(
address indexed account,
address indexed repayToken,
address indexed supplyToken,
uint repayAmount,
uint supplyAmount
);
event Deposit(address indexed account, address indexed token, uint amount);
event Withdraw(address indexed token, uint amount);
event Borrow(address indexed token, uint amount);
event Repay(address indexed account, address indexed token, uint amount);
receive() external payable {}
function initialize(
address _lpTokenMaster,
address _controller,
IERC20 _tokenA,
IERC20 _tokenB
) external {
require(address(tokenA) == address(0), "LendingPair: already initialized");
require(address(_tokenA) != address(0) && address(_tokenB) != address(0), "LendingPair: cannot be ZERO address");
controller = IController(_controller);
tokenA = address(_tokenA);
tokenB = address(_tokenB);
lastBlockAccrued = block.number;
lpToken[tokenA] = _createLpToken(_lpTokenMaster);
lpToken[tokenB] = _createLpToken(_lpTokenMaster);
}
function depositRepay(address _account, address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(_account);
_depositRepay(_account, _token, _amount);
_safeTransferFrom(_token, msg.sender, _amount);
}
function depositRepayETH(address _account) external payable nonReentrant {
_validateToken(address(WETH));
accrueAccount(_account);
_depositRepay(_account, address(WETH), msg.value);
_depositWeth();
}
function deposit(address _account, address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(_account);
_deposit(_account, _token, _amount);
_safeTransferFrom(_token, msg.sender, _amount);
}
function withdrawBorrow(address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(msg.sender);
_withdrawBorrow(_token, _amount);
_safeTransfer(_token, msg.sender, _amount);
}
function withdrawBorrowETH(uint _amount) external nonReentrant {
_validateToken(address(WETH));
accrueAccount(msg.sender);
_withdrawBorrow(address(WETH), _amount);
_wethWithdrawTo(msg.sender, _amount);
}
function withdraw(address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(msg.sender);
_withdraw(_token, _amount);
_safeTransfer(_token, msg.sender, _amount);
}
function withdrawAll(address _token) external nonReentrant {
_validateToken(_token);
accrueAccount(msg.sender);
uint amount = lpToken[_token].balanceOf(msg.sender);
_withdraw(_token, amount);
_safeTransfer(_token, msg.sender, amount);
}
function withdrawAllETH() external nonReentrant {
_validateToken(address(WETH));
accrueAccount(msg.sender);
uint amount = lpToken[address(WETH)].balanceOf(msg.sender);
_withdraw(address(WETH), amount);
_wethWithdrawTo(msg.sender, amount);
}
function borrow(address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(msg.sender);
_borrow(_token, _amount);
_safeTransfer(_token, msg.sender, _amount);
}
function repayAll(address _account, address _token) external nonReentrant {
_validateToken(_token);
_requireAccountNotAccrued(_token, _account);
accrueAccount(_account);
uint amount = debtOf[_token][_account];
_repay(_account, _token, amount);
_safeTransferFrom(_token, msg.sender, amount);
}
function repayAllETH(address _account) external payable nonReentrant {
_validateToken(address(WETH));
_requireAccountNotAccrued(address(WETH), _account);
accrueAccount(_account);
uint amount = debtOf[address(WETH)][_account];
require(msg.value >= amount, "LendingPair: insufficient ETH deposit");
_depositWeth();
_repay(_account, address(WETH), amount);
uint refundAmount = msg.value > amount ? (msg.value - amount) : 0;
if (refundAmount > 0) {
_wethWithdrawTo(msg.sender, refundAmount);
}
}
function repay(address _account, address _token, uint _amount) external nonReentrant {
_validateToken(_token);
accrueAccount(_account);
_repay(_account, _token, _amount);
_safeTransferFrom(_token, msg.sender, _amount);
}
function accrue() public {
if (lastBlockAccrued < block.number) {
_accrueInterest(tokenA);
_accrueInterest(tokenB);
lastBlockAccrued = block.number;
}
}
function accrueAccount(address _account) public {
_distributeReward(_account);
accrue();
_accrueAccountInterest(_account);
if (_account != feeRecipient()) {
_accrueAccountInterest(feeRecipient());
}
}
// Sell collateral to reduce debt and increase accountHealth
// Set _repayAmount to uint(-1) to repay all debt, inc. pending interest
function liquidateAccount(
address _account,
address _repayToken,
uint _repayAmount,
uint _minSupplyOutput
) external nonReentrant {
// Input validation and adjustments
_validateToken(_repayToken);
address supplyToken = _repayToken == tokenA ? tokenB : tokenA;
// Check account is underwater after interest
accrueAccount(_account);
uint health = accountHealth(_account);
require(health < controller.LIQ_MIN_HEALTH(), "LendingPair: account health < LIQ_MIN_HEALTH");
// Calculate balance adjustments
_repayAmount = Math.min(_repayAmount, debtOf[_repayToken][_account]);
uint supplyDebt = _convertTokenValues(_repayToken, supplyToken, _repayAmount);
uint callerFee = supplyDebt * controller.liqFeeCaller(_repayToken) / 100e18;
uint systemFee = supplyDebt * controller.liqFeeSystem(_repayToken) / 100e18;
uint supplyBurn = supplyDebt + callerFee + systemFee;
uint supplyOutput = supplyDebt + callerFee;
require(supplyOutput >= _minSupplyOutput, "LendingPair: supplyOutput >= _minSupplyOutput");
// Adjust balances
_burnSupply(supplyToken, _account, supplyBurn);
_mintSupply(supplyToken, feeRecipient(), systemFee);
_burnDebt(_repayToken, _account, _repayAmount);
// Settle token transfers
_safeTransferFrom(_repayToken, msg.sender, _repayAmount);
_mintSupply(supplyToken, msg.sender, supplyOutput);
emit Liquidation(_account, _repayToken, supplyToken, _repayAmount, supplyOutput);
}
function accountHealth(address _account) public view returns(uint) {
if (debtOf[tokenA][_account] == 0 && debtOf[tokenB][_account] == 0) {
return controller.LIQ_MIN_HEALTH();
}
uint totalAccountSupply = _supplyCredit(_account, tokenA, tokenA) + _supplyCredit(_account, tokenB, tokenA);
uint totalAccountBorrow = _borrowBalance(_account, tokenA, tokenA) + _borrowBalance(_account, tokenB, tokenA);
return totalAccountSupply * 1e18 / totalAccountBorrow;
}
// Get borow balance converted to the units of _returnToken
function borrowBalance(
address _account,
address _borrowedToken,
address _returnToken
) external view returns(uint) {
_validateToken(_borrowedToken);
_validateToken(_returnToken);
return _borrowBalance(_account, _borrowedToken, _returnToken);
}
function supplyBalance(
address _account,
address _suppliedToken,
address _returnToken
) external view returns(uint) {
_validateToken(_suppliedToken);
_validateToken(_returnToken);
return _supplyBalance(_account, _suppliedToken, _returnToken);
}
function supplyRatePerBlock(address _token) external view returns(uint) {
_validateToken(_token);
return controller.interestRateModel().supplyRatePerBlock(ILendingPair(address(this)), _token);
}
function borrowRatePerBlock(address _token) external view returns(uint) {
_validateToken(_token);
return _borrowRatePerBlock(_token);
}
function pendingSupplyInterest(address _token, address _account) external view returns(uint) {
_validateToken(_token);
uint newInterest = _newInterest(lpToken[_token].balanceOf(_account), _token, _account);
return newInterest * _lpRate(_token) / 100e18;
}
function pendingBorrowInterest(address _token, address _account) external view returns(uint) {
_validateToken(_token);
return _pendingBorrowInterest(_token, _account);
}
function feeRecipient() public view returns(address) {
return controller.feeRecipient();
}
function checkAccountHealth(address _account) public view {
uint health = accountHealth(_account);
require(health >= controller.LIQ_MIN_HEALTH(), "LendingPair: insufficient accountHealth");
}
function convertTokenValues(
address _fromToken,
address _toToken,
uint _inputAmount
) external view returns(uint) {
_validateToken(_fromToken);
_validateToken(_toToken);
return _convertTokenValues(_fromToken, _toToken, _inputAmount);
}
function _depositRepay(address _account, address _token, uint _amount) internal {
uint debt = debtOf[_token][_account];
uint repayAmount = debt > _amount ? _amount : debt;
if (repayAmount > 0) {
_repay(_account, _token, repayAmount);
}
uint depositAmount = _amount - repayAmount;
if (depositAmount > 0) {
_deposit(_account, _token, depositAmount);
}
}
function _withdrawBorrow(address _token, uint _amount) internal {
uint supplyAmount = lpToken[_token].balanceOf(msg.sender);
uint withdrawAmount = supplyAmount > _amount ? _amount : supplyAmount;
if (withdrawAmount > 0) {
_withdraw(_token, withdrawAmount);
}
uint borrowAmount = _amount - withdrawAmount;
if (borrowAmount > 0) {
_borrow(_token, borrowAmount);
}
}
function _distributeReward(address _account) internal {
IRewardDistribution rewardDistribution = controller.rewardDistribution();
if (
address(rewardDistribution) != address(0) &&
_account != feeRecipient()
) {
rewardDistribution.distributeReward(_account, tokenA);
rewardDistribution.distributeReward(_account, tokenB);
}
}
function _mintSupply(address _token, address _account, uint _amount) internal {
if (_amount > 0) {
lpToken[_token].mint(_account, _amount);
}
}
function _burnSupply(address _token, address _account, uint _amount) internal {
if (_amount > 0) {
lpToken[_token].burn(_account, _amount);
}
}
function _mintDebt(address _token, address _account, uint _amount) internal {
debtOf[_token][_account] += _amount;
totalDebt[_token] += _amount;
}
// Origination fee is earned entirely by the protocol and is not split with the LPs
// The goal is to prevent free flash loans
function _mintDebtWithOriginFee(address _token, address _account, uint _amount) internal {
uint originFee = _originationFee(_token, _amount);
_mintSupply(_token, feeRecipient(), originFee);
_mintDebt(_token, _account, _amount + originFee);
}
function _burnDebt(address _token, address _account, uint _amount) internal {
debtOf[_token][_account] -= _amount;
totalDebt[_token] -= _amount;
}
function _accrueAccountInterest(address _account) internal {
uint lpBalanceA = lpToken[tokenA].balanceOf(_account);
uint lpBalanceB = lpToken[tokenB].balanceOf(_account);
_accrueAccountSupply(tokenA, lpBalanceA, _account);
_accrueAccountSupply(tokenB, lpBalanceB, _account);
_accrueAccountDebt(tokenA, _account);
_accrueAccountDebt(tokenB, _account);
accountInterestSnapshot[tokenA][_account] = cumulativeInterestRate[tokenA];
accountInterestSnapshot[tokenB][_account] = cumulativeInterestRate[tokenB];
}
function _accrueAccountSupply(address _token, uint _amount, address _account) internal {
if (_amount > 0) {
uint supplyInterest = _newInterest(_amount, _token, _account);
uint newSupplyAccount = supplyInterest * _lpRate(_token) / 100e18;
uint newSupplySystem = supplyInterest * _systemRate(_token) / 100e18;
_mintSupply(_token, _account, newSupplyAccount);
_mintSupply(_token, feeRecipient(), newSupplySystem);
}
}
function _accrueAccountDebt(address _token, address _account) internal {
if (debtOf[_token][_account] > 0) {
uint newDebt = _pendingBorrowInterest(_token, _account);
_mintDebt(_token, _account, newDebt);
}
}
function _withdraw(address _token, uint _amount) internal {
lpToken[_token].burn(msg.sender, _amount);
checkAccountHealth(msg.sender);
emit Withdraw(_token, _amount);
}
function _borrow(address _token, uint _amount) internal {
require(lpToken[_token].balanceOf(msg.sender) == 0, "LendingPair: cannot borrow supplied token");
_mintDebtWithOriginFee(_token, msg.sender, _amount);
_checkBorrowLimits(_token, msg.sender);
checkAccountHealth(msg.sender);
emit Borrow(_token, _amount);
}
function _repay(address _account, address _token, uint _amount) internal {
_burnDebt(_token, _account, _amount);
emit Repay(_account, _token, _amount);
}
function _deposit(address _account, address _token, uint _amount) internal {
_checkOracleSupport(tokenA);
_checkOracleSupport(tokenB);
require(debtOf[_token][_account] == 0, "LendingPair: cannot deposit borrowed token");
_mintSupply(_token, _account, _amount);
_checkDepositLimit(_token);
emit Deposit(_account, _token, _amount);
}
function _accrueInterest(address _token) internal {
cumulativeInterestRate[_token] += _pendingInterestRate(_token);
}
function _pendingInterestRate(address _token) internal view returns(uint) {
uint blocksElapsed = block.number - lastBlockAccrued;
return _borrowRatePerBlock(_token) * blocksElapsed;
}
function _createLpToken(address _lpTokenMaster) internal returns(IERC20) {
ILPTokenMaster newLPToken = ILPTokenMaster(_lpTokenMaster.clone());
newLPToken.initialize();
return IERC20(newLPToken);
}
function _safeTransfer(address _token, address _recipient, uint _amount) internal override {
TransferHelper._safeTransfer(_token, _recipient, _amount);
_checkMinReserve(address(_token));
}
function _wethWithdrawTo(address _to, uint _amount) internal override {
TransferHelper._wethWithdrawTo(_to, _amount);
_checkMinReserve(address(WETH));
}
function _borrowRatePerBlock(address _token) internal view returns(uint) {
return controller.interestRateModel().borrowRatePerBlock(ILendingPair(address(this)), _token);
}
function _pendingBorrowInterest(address _token, address _account) internal view returns(uint) {
return _newInterest(debtOf[_token][_account], _token, _account);
}
function _borrowBalance(
address _account,
address _borrowedToken,
address _returnToken
) internal view returns(uint) {
return _convertTokenValues(_borrowedToken, _returnToken, debtOf[_borrowedToken][_account]);
}
// Get supply balance converted to the units of _returnToken
function _supplyBalance(
address _account,
address _suppliedToken,
address _returnToken
) internal view returns(uint) {
return _convertTokenValues(_suppliedToken, _returnToken, lpToken[_suppliedToken].balanceOf(_account));
}
function _supplyCredit(
address _account,
address _suppliedToken,
address _returnToken
) internal view returns(uint) {
return _supplyBalance(_account, _suppliedToken, _returnToken) * controller.colFactor(_suppliedToken) / 100e18;
}
function _convertTokenValues(
address _fromToken,
address _toToken,
uint _inputAmount
) internal view returns(uint) {
uint priceFrom = controller.tokenPrice(_fromToken) * 1e18 / 10 ** IERC20(_fromToken).decimals();
uint priceTo = controller.tokenPrice(_toToken) * 1e18 / 10 ** IERC20(_toToken).decimals();
return _inputAmount * priceFrom / priceTo;
}
function _validateToken(address _token) internal view {
require(_token == tokenA || _token == tokenB, "LendingPair: invalid token");
}
function _checkOracleSupport(address _token) internal view {
require(controller.tokenSupported(_token), "LendingPair: token not supported");
}
function _checkMinReserve(address _token) internal view {
require(IERC20(_token).balanceOf(address(this)) >= MIN_RESERVE, "LendingPair: below MIN_RESERVE");
}
function _checkDepositLimit(address _token) internal view {
require(controller.depositsEnabled(), "LendingPair: deposits disabled");
uint depositLimit = controller.depositLimit(address(this), _token);
if (depositLimit > 0) {
require((lpToken[_token].totalSupply()) <= depositLimit, "LendingPair: deposit limit reached");
}
}
function _checkBorrowLimits(address _token, address _account) internal view {
require(controller.borrowingEnabled(), "LendingPair: borrowing disabled");
uint accountBorrowUSD = debtOf[_token][_account] * controller.tokenPrice(_token) / 1e18;
require(accountBorrowUSD >= controller.minBorrowUSD(), "LendingPair: borrow amount below minimum");
uint borrowLimit = controller.borrowLimit(address(this), _token);
if (borrowLimit > 0) {
require(totalDebt[_token] <= borrowLimit, "LendingPair: borrow limit reached");
}
}
function _originationFee(address _token, uint _amount) internal view returns(uint) {
return _amount * controller.originFee(_token) / 100e18;
}
function _systemRate(address _token) internal view returns(uint) {
return controller.interestRateModel().systemRate(ILendingPair(address(this)), _token);
}
function _lpRate(address _token) internal view returns(uint) {
return 100e18 - _systemRate(_token);
}
function _newInterest(uint _balance, address _token, address _account) internal view returns(uint) {
uint currentCumulativeRate = cumulativeInterestRate[_token] + _pendingInterestRate(_token);
return _balance * (currentCumulativeRate - accountInterestSnapshot[_token][_account]) / 100e18;
}
// Used in repayAll and repayAllETH to prevent front-running
// Potential attack:
// Recipient account watches the mempool and takes out a large loan just before someone calls repayAll.
// As a result, paying account would end up paying much more than anticipated
function _requireAccountNotAccrued(address _token, address _account) internal view {
if (lastBlockAccrued == block.number && cumulativeInterestRate[_token] > 0) {
require(
cumulativeInterestRate[_token] > accountInterestSnapshot[_token][_account],
"LendingPair: account already accrued"
);
}
}
} | _requireAccountNotAccrued | function _requireAccountNotAccrued(address _token, address _account) internal view {
if (lastBlockAccrued == block.number && cumulativeInterestRate[_token] > 0) {
require(
cumulativeInterestRate[_token] > accountInterestSnapshot[_token][_account],
"LendingPair: account already accrued"
);
}
}
| // Used in repayAll and repayAllETH to prevent front-running
// Potential attack:
// Recipient account watches the mempool and takes out a large loan just before someone calls repayAll.
// As a result, paying account would end up paying much more than anticipated | LineComment | v0.8.6+commit.11564f7e | None | ipfs://4d03a265a12ba81c0f5a175a2642e8e9fa5be73fda205ebdaf6e808e4fd675db | {
"func_code_index": [
19470,
19811
]
} | 3,666 |
||
SakeVoterCalc | contracts/SakeVoterCalc.sol | 0x44d84a9da47fd8f4a06ad66b197d1441fca53f92 | Solidity | SakeVoterCalc | contract SakeVoterCalc {
using SafeMath for uint256;
ItMap public voteLpPoolMap; //Voter LP Address
// Apply library functions to the data type.
using IterableMapping for ItMap;
IERC20 public sake;
SakeBar public bar;
STokenMaster public stoken;
SakeMaster public masterV1;
SakeMasterV2 public masterV2;
IERC20 public lpSakeEth = IERC20(0xAC10f17627Cd6bc22719CeEBf1fc524C9Cfdc255); //SAKE-ETH
address public owner;
uint256 public lpPow = 2;
uint256 public balancePow = 1;
uint256 public stakePow = 1;
bool public sqrtEnable = true;
modifier onlyOwner() {
require(owner == msg.sender, "Not Owner");
_;
}
constructor(
address _tokenAddr,
address _barAddr,
address _stoken,
address _masterAddr,
address _masterV2Addr
) public {
sake = IERC20(_tokenAddr);
bar = SakeBar(_barAddr);
stoken = STokenMaster(_stoken);
masterV1 = SakeMaster(_masterAddr);
masterV2 = SakeMasterV2(_masterV2Addr);
owner = msg.sender;
voteLpPoolMap.insert(voteLpPoolMap.size, 0xAC10f17627Cd6bc22719CeEBf1fc524C9Cfdc255); //SAKE-ETH
voteLpPoolMap.insert(voteLpPoolMap.size, 0x5B255e213bCcE0FA8Ad2948E3D7A6F6E76472db8); //SAKE-USDT
voteLpPoolMap.insert(voteLpPoolMap.size, 0xEc694c829CC192667cDAA6C7639Ef362f3cbF575); //SAKE-USDC
voteLpPoolMap.insert(voteLpPoolMap.size, 0x838ce8f4Da8b49EA72378427485CF827c08a0abf); //SAKE-DAI
voteLpPoolMap.insert(voteLpPoolMap.size, 0x49DE2D202fB703999c4D6a7e2dAA2F3700588f40); //SAKE-SUSHI
voteLpPoolMap.insert(voteLpPoolMap.size, 0x83970b5570E4cb5FC5e21eF9B9F3c4F8A129c2f2); //SAKE-UNI
}
function sqrt(uint256 x) public pure returns (uint256 y) {
uint256 z = x.add(1).div(2);
y = x;
while (z < y) {
y = z;
z = x.div(z).add(z).div(2);
}
}
function totalSupply() external view returns (uint256) {
uint256 voterTotal = 0;
uint256 _vCtSakes = 0;
uint256 totalBarSakes = 0;
address _vLpToken;
totalBarSakes = sake.balanceOf(address(bar));
for (
uint256 i = voteLpPoolMap.iterateStart();
voteLpPoolMap.iterateValid(i);
i = voteLpPoolMap.iterateNext(i)
) {
//count lp contract sakenums
(, _vLpToken) = voteLpPoolMap.iterateGet(i);
_vCtSakes = _vCtSakes.add(sake.balanceOf(_vLpToken));
}
voterTotal =
sake.totalSupply().sub(totalBarSakes).sub(_vCtSakes).mul(balancePow) +
_vCtSakes.mul(lpPow) +
totalBarSakes.mul(stakePow);
if (sqrtEnable == true) {
return sqrt(voterTotal);
}
return voterTotal;
}
function _getUserLpSakes(address _voter, address _vLpTokenAddr) internal view returns (uint256) {
IERC20 _vtmpLpToken;
IERC20 _vLpToken;
uint256 _vUserLp = 0;
uint256 _vtmpUserLp = 0;
uint256 _vCtSakeNum = 0;
uint256 _vUserSakeNum = 0;
ISakeSwapPair _vPair;
if (sake.balanceOf(_vLpTokenAddr) == 0) {
return 0;
}
_vLpToken = IERC20(_vLpTokenAddr);
//v1 pool
for (uint256 j = 0; j < masterV1.poolLength(); j++) {
(_vtmpLpToken, , , ) = masterV1.poolInfo(j);
if (_vtmpLpToken == _vLpToken) {
(_vtmpUserLp, ) = masterV1.userInfo(j, _voter);
_vUserLp = _vUserLp.add(_vtmpUserLp);
break;
}
}
//v2 pool
for (uint256 j = 0; j < masterV2.poolLength(); j++) {
(_vtmpLpToken, , , , , , ) = masterV2.poolInfo(j);
if (_vtmpLpToken == _vLpToken) {
(, , _vtmpUserLp, , , ) = masterV2.userInfo(j, _voter);
_vUserLp = _vUserLp.add(_vtmpUserLp);
break;
}
}
//stokenmaster pool
if (lpSakeEth == _vLpToken) {
(, , _vtmpUserLp, ) = stoken.userInfo(0, _voter);
_vUserLp = _vUserLp.add(_vtmpUserLp);
}
//user balance lp
_vPair = ISakeSwapPair(_vLpTokenAddr);
_vUserLp = _vUserLp.add(_vPair.balanceOf(_voter));
//user deposit sakenum = user_lptoken*contract_sakenum/contract_lptokens
_vCtSakeNum = sake.balanceOf(address(_vLpToken));
_vUserSakeNum = _vUserLp.mul(_vCtSakeNum).div(_vPair.totalSupply());
return _vUserSakeNum;
}
//sum user deposit sakenum
function balanceOf(address _voter) external view returns (uint256) {
uint256 _votes = 0;
uint256 _vCtSakeNum = 0;
uint256 _vBarSakeNum = 0;
address _vLpTokenAddr;
for (
uint256 i = voteLpPoolMap.iterateStart();
voteLpPoolMap.iterateValid(i);
i = voteLpPoolMap.iterateNext(i)
) {
(, _vLpTokenAddr) = voteLpPoolMap.iterateGet(i);
_vCtSakeNum = _vCtSakeNum.add(_getUserLpSakes(_voter, _vLpTokenAddr));
}
_vBarSakeNum = bar.balanceOf(_voter).mul(sake.balanceOf(address(bar))).div(bar.totalSupply());
_votes = _vCtSakeNum.mul(lpPow) + sake.balanceOf(_voter).mul(balancePow) + _vBarSakeNum.mul(stakePow);
if (sqrtEnable == true) {
return sqrt(_votes);
}
return _votes;
}
function addVotePool(address newLpAddr) public onlyOwner {
address _vTmpLpAddr;
uint256 key = 0;
for (
uint256 i = voteLpPoolMap.iterateStart();
voteLpPoolMap.iterateValid(i);
i = voteLpPoolMap.iterateNext(i)
) {
(, _vTmpLpAddr) = voteLpPoolMap.iterateGet(i);
require(_vTmpLpAddr != newLpAddr, "newLpAddr already exist");
}
for (key = 0; voteLpPoolMap.iterateValid(key); key++) {
if (voteLpPoolMap.contains(key) == false) {
break;
}
}
voteLpPoolMap.insert(key, newLpAddr);
}
function delVotePool(address newLpAddr) public onlyOwner {
uint256 key = 0;
address _vTmpLpAddr;
for (
uint256 i = voteLpPoolMap.iterateStart();
voteLpPoolMap.iterateValid(i);
i = voteLpPoolMap.iterateNext(i)
) {
(key, _vTmpLpAddr) = voteLpPoolMap.iterateGet(i);
if (_vTmpLpAddr == newLpAddr) {
voteLpPoolMap.remove(key);
return;
}
}
}
function getVotePool(address newLpAddr) external view returns (uint256) {
address _vTmpLpAddr;
uint256 key = 0;
for (
uint256 i = voteLpPoolMap.iterateStart();
voteLpPoolMap.iterateValid(i);
i = voteLpPoolMap.iterateNext(i)
) {
(key, _vTmpLpAddr) = voteLpPoolMap.iterateGet(i);
if (_vTmpLpAddr == newLpAddr) {
return key;
}
}
return 0;
}
function setSqrtEnable(bool enable) public onlyOwner {
if (sqrtEnable != enable) {
sqrtEnable = enable;
}
}
function setPow(
uint256 lPow,
uint256 bPow,
uint256 sPow
) public onlyOwner {
//no need to check pow ?= 0
if (lPow != lpPow) {
lpPow = lPow;
}
if (bPow != balancePow) {
balancePow = bPow;
}
if (sPow != stakePow) {
stakePow = sPow;
}
}
} | balanceOf | function balanceOf(address _voter) external view returns (uint256) {
uint256 _votes = 0;
uint256 _vCtSakeNum = 0;
uint256 _vBarSakeNum = 0;
address _vLpTokenAddr;
for (
uint256 i = voteLpPoolMap.iterateStart();
voteLpPoolMap.iterateValid(i);
i = voteLpPoolMap.iterateNext(i)
) {
(, _vLpTokenAddr) = voteLpPoolMap.iterateGet(i);
_vCtSakeNum = _vCtSakeNum.add(_getUserLpSakes(_voter, _vLpTokenAddr));
}
_vBarSakeNum = bar.balanceOf(_voter).mul(sake.balanceOf(address(bar))).div(bar.totalSupply());
_votes = _vCtSakeNum.mul(lpPow) + sake.balanceOf(_voter).mul(balancePow) + _vBarSakeNum.mul(stakePow);
if (sqrtEnable == true) {
return sqrt(_votes);
}
return _votes;
}
| //sum user deposit sakenum | LineComment | v0.6.12+commit.27d51765 | None | ipfs://5d4700996a40376e16d7d09f63c9d6b8ef633b28dd8203c5297833f9286dce20 | {
"func_code_index": [
4707,
5571
]
} | 3,667 |
||
TimeLockRegistry | contracts/lib/AddressArrayUtils.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | AddressArrayUtils | library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns (bool) {
require(A.length > 0, 'A is empty');
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a) internal pure returns (address[] memory) {
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert('Address not in array.');
} else {
(address[] memory _A, ) = pop(A, index);
return _A;
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) {
uint256 length = A.length;
require(index < A.length, 'Index must be < A length');
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
} | /**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*/ | NatSpecMultiLine | indexOf | function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
| /**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | {
"func_code_index": [
276,
579
]
} | 3,668 |
||
TimeLockRegistry | contracts/lib/AddressArrayUtils.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | AddressArrayUtils | library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns (bool) {
require(A.length > 0, 'A is empty');
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a) internal pure returns (address[] memory) {
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert('Address not in array.');
} else {
(address[] memory _A, ) = pop(A, index);
return _A;
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) {
uint256 length = A.length;
require(index < A.length, 'Index must be < A length');
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
} | /**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*/ | NatSpecMultiLine | contains | function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
| /**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | {
"func_code_index": [
830,
979
]
} | 3,669 |
||
TimeLockRegistry | contracts/lib/AddressArrayUtils.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | AddressArrayUtils | library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns (bool) {
require(A.length > 0, 'A is empty');
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a) internal pure returns (address[] memory) {
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert('Address not in array.');
} else {
(address[] memory _A, ) = pop(A, index);
return _A;
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) {
uint256 length = A.length;
require(index < A.length, 'Index must be < A length');
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
} | /**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*/ | NatSpecMultiLine | hasDuplicate | function hasDuplicate(address[] memory A) internal pure returns (bool) {
require(A.length > 0, 'A is empty');
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
| /**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | {
"func_code_index": [
1184,
1594
]
} | 3,670 |
||
TimeLockRegistry | contracts/lib/AddressArrayUtils.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | AddressArrayUtils | library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns (bool) {
require(A.length > 0, 'A is empty');
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a) internal pure returns (address[] memory) {
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert('Address not in array.');
} else {
(address[] memory _A, ) = pop(A, index);
return _A;
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) {
uint256 length = A.length;
require(index < A.length, 'Index must be < A length');
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
} | /**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*/ | NatSpecMultiLine | remove | function remove(address[] memory A, address a) internal pure returns (address[] memory) {
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert('Address not in array.');
} else {
(address[] memory _A, ) = pop(A, index);
return _A;
}
}
| /**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | {
"func_code_index": [
1750,
2070
]
} | 3,671 |
||
TimeLockRegistry | contracts/lib/AddressArrayUtils.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | AddressArrayUtils | library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns (bool) {
require(A.length > 0, 'A is empty');
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a) internal pure returns (address[] memory) {
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert('Address not in array.');
} else {
(address[] memory _A, ) = pop(A, index);
return _A;
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) {
uint256 length = A.length;
require(index < A.length, 'Index must be < A length');
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
} | /**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*/ | NatSpecMultiLine | pop | function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) {
uint256 length = A.length;
require(index < A.length, 'Index must be < A length');
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
| /**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | {
"func_code_index": [
2271,
2783
]
} | 3,672 |
||
TimeLockRegistry | contracts/lib/AddressArrayUtils.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | AddressArrayUtils | library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns (bool) {
require(A.length > 0, 'A is empty');
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a) internal pure returns (address[] memory) {
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert('Address not in array.');
} else {
(address[] memory _A, ) = pop(A, index);
return _A;
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) {
uint256 length = A.length;
require(index < A.length, 'Index must be < A length');
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
} | /**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*/ | NatSpecMultiLine | extend | function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
| /**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | {
"func_code_index": [
2954,
3435
]
} | 3,673 |
||
GermanBakery | /contracts/GermanBakery.sol | 0x5721be2b7b1403daaea264daa26c29c51398bc2f | Solidity | GermanBakery | contract GermanBakery is Ownable, ERC721Holder, ReentrancyGuard {
Brotchain public brotchain;
constructor(address _brotchain) {
brotchain = Brotchain(_brotchain);
}
/**
* @dev Remaining allocation for addresses.
*/
mapping(address => int256) public allocRemaining;
/**
* @dev Received by changeAllocation() in lieu of a mapping.
*/
struct AllocationDelta {
address addr;
int80 value;
}
/**
* @dev Changes the remaining allocation for the specified addresses.
*/
function changeAllocations(AllocationDelta[] memory deltas) external onlyOwner {
for (uint256 i = 0; i < deltas.length; i++) {
allocRemaining[deltas[i].addr] += deltas[i].value;
}
}
/**
* @dev Calls Brotchain.safeMint() and transfers the token to the sender.
*
* This correctly implements early-access limiting by decrementing the
* sender's allocation instead of comparing the balance to the allocation as
* the Brotchain contract does. This was vulnerable to tokens be transferred
* before minting again.
*/
function safeMint() external payable nonReentrant {
// CHECKS
require(allocRemaining[msg.sender] > 0, "Address allocation exhausted");
// EFFECTS
allocRemaining[msg.sender]--;
brotchain.safeMint{value: msg.value}();
// INTERACTIONS
// As the token is immediately transferred, it will always be index 0.
address self = address(this);
uint256 tokenId = brotchain.tokenOfOwnerByIndex(self, 0);
brotchain.safeTransferFrom(self, msg.sender, tokenId);
}
} | /**
* @dev German bakeries make brot.
*
* After deployment we discoverd a bug in the Brotchain early-access allocator
* that exposed a loophole if someone transferred their Brot after minting, thus
* allowing for unlimited mints. This contract is the fix and acts as a proxy
* minter with correct allocation limiting. The entire Brotchain supply is thus
* allocated to this contract.
*/ | NatSpecMultiLine | changeAllocations | function changeAllocations(AllocationDelta[] memory deltas) external onlyOwner {
for (uint256 i = 0; i < deltas.length; i++) {
allocRemaining[deltas[i].addr] += deltas[i].value;
}
}
| /**
* @dev Changes the remaining allocation for the specified addresses.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | {
"func_code_index": [
560,
777
]
} | 3,674 |
||
GermanBakery | /contracts/GermanBakery.sol | 0x5721be2b7b1403daaea264daa26c29c51398bc2f | Solidity | GermanBakery | contract GermanBakery is Ownable, ERC721Holder, ReentrancyGuard {
Brotchain public brotchain;
constructor(address _brotchain) {
brotchain = Brotchain(_brotchain);
}
/**
* @dev Remaining allocation for addresses.
*/
mapping(address => int256) public allocRemaining;
/**
* @dev Received by changeAllocation() in lieu of a mapping.
*/
struct AllocationDelta {
address addr;
int80 value;
}
/**
* @dev Changes the remaining allocation for the specified addresses.
*/
function changeAllocations(AllocationDelta[] memory deltas) external onlyOwner {
for (uint256 i = 0; i < deltas.length; i++) {
allocRemaining[deltas[i].addr] += deltas[i].value;
}
}
/**
* @dev Calls Brotchain.safeMint() and transfers the token to the sender.
*
* This correctly implements early-access limiting by decrementing the
* sender's allocation instead of comparing the balance to the allocation as
* the Brotchain contract does. This was vulnerable to tokens be transferred
* before minting again.
*/
function safeMint() external payable nonReentrant {
// CHECKS
require(allocRemaining[msg.sender] > 0, "Address allocation exhausted");
// EFFECTS
allocRemaining[msg.sender]--;
brotchain.safeMint{value: msg.value}();
// INTERACTIONS
// As the token is immediately transferred, it will always be index 0.
address self = address(this);
uint256 tokenId = brotchain.tokenOfOwnerByIndex(self, 0);
brotchain.safeTransferFrom(self, msg.sender, tokenId);
}
} | /**
* @dev German bakeries make brot.
*
* After deployment we discoverd a bug in the Brotchain early-access allocator
* that exposed a loophole if someone transferred their Brot after minting, thus
* allowing for unlimited mints. This contract is the fix and acts as a proxy
* minter with correct allocation limiting. The entire Brotchain supply is thus
* allocated to this contract.
*/ | NatSpecMultiLine | safeMint | function safeMint() external payable nonReentrant {
// CHECKS
require(allocRemaining[msg.sender] > 0, "Address allocation exhausted");
// EFFECTS
allocRemaining[msg.sender]--;
brotchain.safeMint{value: msg.value}();
// INTERACTIONS
// As the token is immediately transferred, it will always be index 0.
address self = address(this);
uint256 tokenId = brotchain.tokenOfOwnerByIndex(self, 0);
brotchain.safeTransferFrom(self, msg.sender, tokenId);
}
| /**
* @dev Calls Brotchain.safeMint() and transfers the token to the sender.
*
* This correctly implements early-access limiting by decrementing the
* sender's allocation instead of comparing the balance to the allocation as
* the Brotchain contract does. This was vulnerable to tokens be transferred
* before minting again.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | {
"func_code_index": [
1146,
1683
]
} | 3,675 |
||
MultiSend | MultiSend.sol | 0xb76a20d5d42c041593df95d7d72b74b2543824f9 | Solidity | Ownable | contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | renounceOwnership | function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
| /**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://137bf962082d8be697f92afd65582eaa64bdc2a74417dd537adfd766b6e8f074 | {
"func_code_index": [
815,
932
]
} | 3,676 |
|
MultiSend | MultiSend.sol | 0xb76a20d5d42c041593df95d7d72b74b2543824f9 | Solidity | Ownable | contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | transferOwnership | function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
| /**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://137bf962082d8be697f92afd65582eaa64bdc2a74417dd537adfd766b6e8f074 | {
"func_code_index": [
1097,
1205
]
} | 3,677 |
|
MultiSend | MultiSend.sol | 0xb76a20d5d42c041593df95d7d72b74b2543824f9 | Solidity | Ownable | contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
} | /**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/ | NatSpecMultiLine | _transferOwnership | function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
| /**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/ | NatSpecMultiLine | v0.4.24+commit.e67f0147 | bzzr://137bf962082d8be697f92afd65582eaa64bdc2a74417dd537adfd766b6e8f074 | {
"func_code_index": [
1343,
1521
]
} | 3,678 |
|
GermanBakery | /contracts/BMP.sol | 0x5721be2b7b1403daaea264daa26c29c51398bc2f | Solidity | BMP | contract BMP {
using Base64 for string;
/**
* @dev Returns an 8-bit grayscale palette for bitmap images.
*/
function grayscale() public pure returns (bytes memory) {
bytes memory palette = new bytes(768);
// TODO: investigate a way around using ++ += or + on a bytes1 without
// having to use a placeholder int8 for incrementing!
uint8 j;
bytes1 b;
for (uint16 i = 0; i < 768; i += 3) {
b = bytes1(j);
palette[i ] = b;
palette[i+1] = b;
palette[i+2] = b;
// The last increment would revert if checked.
unchecked { j++; }
}
return palette;
}
/**
* @dev Returns an 8-bit BMP encoding of the pixels.
*
* Spec: https://www.digicamsoft.com/bmp/bmp.html
*
* Layout description with offsets:
* http://www.ece.ualberta.ca/~elliott/ee552/studentAppNotes/2003_w/misc/bmp_file_format/bmp_file_format.htm
*
* N.B. Everything is little-endian, hence the assembly for masking and
* shifting.
*/
function bmp(bytes memory pixels, uint32 width, uint32 height, bytes memory palette) public pure returns (bytes memory) {
require(width * height == pixels.length, "Invalid dimensions");
require(palette.length == 768, "256 colours required");
// 14 bytes for BITMAPFILEHEADER + 40 for BITMAPINFOHEADER + 1024 for palette
bytes memory buf = new bytes(1078);
// BITMAPFILEHEADER
buf[0] = 0x42; buf[1] = 0x4d; // bfType = BM
uint32 size = 1078 + uint32(pixels.length);
// bfSize; bytes in the entire buffer
uint32 b;
for (uint i = 2; i < 6; i++) {
assembly {
b := and(size, 0xff)
size := shr(8, size)
}
buf[i] = bytes1(uint8(b));
}
// Next 4 bytes are bfReserved1 & 2; both = 0 = initial value
// bfOffBits; bytes from beginning of file to pixels = 14 + 40 + 1024
// (see size above)
buf[0x0a] = 0x36;
buf[0x0b] = 0x04;
// BITMAPINFOHEADER
// biSize; bytes in this struct = 40
buf[0x0e] = 0x28;
// biWidth / biHeight
for (uint i = 0x12; i < 0x16; i++) {
assembly {
b := and(width, 0xff)
width := shr(8, width)
}
buf[i] = bytes1(uint8(b));
}
for (uint i = 0x16; i < 0x1a; i++) {
assembly {
b := and(height, 0xff)
height := shr(8, height)
}
buf[i] = bytes1(uint8(b));
}
// biPlanes
buf[0x1a] = 0x01;
// biBitCount
buf[0x1c] = 0x08;
// I've decided to use raw pixels instead of run-length encoding for
// compression as these aren't being stored. It's therefore simpler to
// avoid the extra computation. Therefore biSize can be 0. Similarly
// there's no point checking exactly which colours are used, so
// biClrUsed and biClrImportant can be 0 to indicate all colours. This
// is therefore the end of BITMAPINFOHEADER. Simples.
uint j = 54;
for (uint i = 0; i < 768; i += 3) {
// RGBQUAD is in reverse order and the 4th byte is unused.
buf[j ] = palette[i+2];
buf[j+1] = palette[i+1];
buf[j+2] = palette[i ];
j += 4;
}
return abi.encodePacked(buf, pixels);
}
/**
* @dev Returns the buffer, presumably from bmp(), as a base64 data URI.
*/
function bmpDataURI(bytes memory bmpBuf) public pure returns (string memory) {
return string(abi.encodePacked(
'data:image/bmp;base64,',
Base64.encode(bmpBuf)
));
}
/**
* @dev Scale pixels by repetition along both axes.
*/
function scalePixels(bytes memory pixels, uint32 width, uint32 height, uint32 scale) public pure returns (bytes memory) {
require(width * height == pixels.length, "Invalid dimensions");
bytes memory scaled = new bytes(pixels.length * scale * scale);
// Indices in each of the original and scaled buffers, respectively. The
// scaled-buffer index is always incremented. The original index is
// incremented only after scaling x-wise by scale times, then reversed
// at the end of the width to allow for y-wise scaling.
uint32 origIdx;
uint32 scaleIdx;
for (uint32 y = 0; y < height; y++) {
for (uint32 yScale = 0; yScale < scale; yScale++) {
for (uint32 x = 0; x < width; x++) {
for (uint32 xScale = 0; xScale < scale; xScale++) {
scaled[scaleIdx] = pixels[origIdx];
scaleIdx++;
}
origIdx++;
}
// Rewind to copy the row again.
origIdx -= width;
}
// Don't just copy the first row.
origIdx += width;
}
return scaled;
}
} | /**
* @dev 8-bit BMP encoding with arbitrary colour palettes.
*/ | NatSpecMultiLine | grayscale | function grayscale() public pure returns (bytes memory) {
bytes memory palette = new bytes(768);
// TODO: investigate a way around using ++ += or + on a bytes1 without
// having to use a placeholder int8 for incrementing!
uint8 j;
bytes1 b;
for (uint16 i = 0; i < 768; i += 3) {
b = bytes1(j);
palette[i ] = b;
palette[i+1] = b;
palette[i+2] = b;
// The last increment would revert if checked.
unchecked { j++; }
}
return palette;
}
| /**
* @dev Returns an 8-bit grayscale palette for bitmap images.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | {
"func_code_index": [
127,
704
]
} | 3,679 |
||
GermanBakery | /contracts/BMP.sol | 0x5721be2b7b1403daaea264daa26c29c51398bc2f | Solidity | BMP | contract BMP {
using Base64 for string;
/**
* @dev Returns an 8-bit grayscale palette for bitmap images.
*/
function grayscale() public pure returns (bytes memory) {
bytes memory palette = new bytes(768);
// TODO: investigate a way around using ++ += or + on a bytes1 without
// having to use a placeholder int8 for incrementing!
uint8 j;
bytes1 b;
for (uint16 i = 0; i < 768; i += 3) {
b = bytes1(j);
palette[i ] = b;
palette[i+1] = b;
palette[i+2] = b;
// The last increment would revert if checked.
unchecked { j++; }
}
return palette;
}
/**
* @dev Returns an 8-bit BMP encoding of the pixels.
*
* Spec: https://www.digicamsoft.com/bmp/bmp.html
*
* Layout description with offsets:
* http://www.ece.ualberta.ca/~elliott/ee552/studentAppNotes/2003_w/misc/bmp_file_format/bmp_file_format.htm
*
* N.B. Everything is little-endian, hence the assembly for masking and
* shifting.
*/
function bmp(bytes memory pixels, uint32 width, uint32 height, bytes memory palette) public pure returns (bytes memory) {
require(width * height == pixels.length, "Invalid dimensions");
require(palette.length == 768, "256 colours required");
// 14 bytes for BITMAPFILEHEADER + 40 for BITMAPINFOHEADER + 1024 for palette
bytes memory buf = new bytes(1078);
// BITMAPFILEHEADER
buf[0] = 0x42; buf[1] = 0x4d; // bfType = BM
uint32 size = 1078 + uint32(pixels.length);
// bfSize; bytes in the entire buffer
uint32 b;
for (uint i = 2; i < 6; i++) {
assembly {
b := and(size, 0xff)
size := shr(8, size)
}
buf[i] = bytes1(uint8(b));
}
// Next 4 bytes are bfReserved1 & 2; both = 0 = initial value
// bfOffBits; bytes from beginning of file to pixels = 14 + 40 + 1024
// (see size above)
buf[0x0a] = 0x36;
buf[0x0b] = 0x04;
// BITMAPINFOHEADER
// biSize; bytes in this struct = 40
buf[0x0e] = 0x28;
// biWidth / biHeight
for (uint i = 0x12; i < 0x16; i++) {
assembly {
b := and(width, 0xff)
width := shr(8, width)
}
buf[i] = bytes1(uint8(b));
}
for (uint i = 0x16; i < 0x1a; i++) {
assembly {
b := and(height, 0xff)
height := shr(8, height)
}
buf[i] = bytes1(uint8(b));
}
// biPlanes
buf[0x1a] = 0x01;
// biBitCount
buf[0x1c] = 0x08;
// I've decided to use raw pixels instead of run-length encoding for
// compression as these aren't being stored. It's therefore simpler to
// avoid the extra computation. Therefore biSize can be 0. Similarly
// there's no point checking exactly which colours are used, so
// biClrUsed and biClrImportant can be 0 to indicate all colours. This
// is therefore the end of BITMAPINFOHEADER. Simples.
uint j = 54;
for (uint i = 0; i < 768; i += 3) {
// RGBQUAD is in reverse order and the 4th byte is unused.
buf[j ] = palette[i+2];
buf[j+1] = palette[i+1];
buf[j+2] = palette[i ];
j += 4;
}
return abi.encodePacked(buf, pixels);
}
/**
* @dev Returns the buffer, presumably from bmp(), as a base64 data URI.
*/
function bmpDataURI(bytes memory bmpBuf) public pure returns (string memory) {
return string(abi.encodePacked(
'data:image/bmp;base64,',
Base64.encode(bmpBuf)
));
}
/**
* @dev Scale pixels by repetition along both axes.
*/
function scalePixels(bytes memory pixels, uint32 width, uint32 height, uint32 scale) public pure returns (bytes memory) {
require(width * height == pixels.length, "Invalid dimensions");
bytes memory scaled = new bytes(pixels.length * scale * scale);
// Indices in each of the original and scaled buffers, respectively. The
// scaled-buffer index is always incremented. The original index is
// incremented only after scaling x-wise by scale times, then reversed
// at the end of the width to allow for y-wise scaling.
uint32 origIdx;
uint32 scaleIdx;
for (uint32 y = 0; y < height; y++) {
for (uint32 yScale = 0; yScale < scale; yScale++) {
for (uint32 x = 0; x < width; x++) {
for (uint32 xScale = 0; xScale < scale; xScale++) {
scaled[scaleIdx] = pixels[origIdx];
scaleIdx++;
}
origIdx++;
}
// Rewind to copy the row again.
origIdx -= width;
}
// Don't just copy the first row.
origIdx += width;
}
return scaled;
}
} | /**
* @dev 8-bit BMP encoding with arbitrary colour palettes.
*/ | NatSpecMultiLine | bmp | function bmp(bytes memory pixels, uint32 width, uint32 height, bytes memory palette) public pure returns (bytes memory) {
require(width * height == pixels.length, "Invalid dimensions");
require(palette.length == 768, "256 colours required");
// 14 bytes for BITMAPFILEHEADER + 40 for BITMAPINFOHEADER + 1024 for palette
bytes memory buf = new bytes(1078);
// BITMAPFILEHEADER
buf[0] = 0x42; buf[1] = 0x4d; // bfType = BM
uint32 size = 1078 + uint32(pixels.length);
// bfSize; bytes in the entire buffer
uint32 b;
for (uint i = 2; i < 6; i++) {
assembly {
b := and(size, 0xff)
size := shr(8, size)
}
buf[i] = bytes1(uint8(b));
}
// Next 4 bytes are bfReserved1 & 2; both = 0 = initial value
// bfOffBits; bytes from beginning of file to pixels = 14 + 40 + 1024
// (see size above)
buf[0x0a] = 0x36;
buf[0x0b] = 0x04;
// BITMAPINFOHEADER
// biSize; bytes in this struct = 40
buf[0x0e] = 0x28;
// biWidth / biHeight
for (uint i = 0x12; i < 0x16; i++) {
assembly {
b := and(width, 0xff)
width := shr(8, width)
}
buf[i] = bytes1(uint8(b));
}
for (uint i = 0x16; i < 0x1a; i++) {
assembly {
b := and(height, 0xff)
height := shr(8, height)
}
buf[i] = bytes1(uint8(b));
}
// biPlanes
buf[0x1a] = 0x01;
// biBitCount
buf[0x1c] = 0x08;
// I've decided to use raw pixels instead of run-length encoding for
// compression as these aren't being stored. It's therefore simpler to
// avoid the extra computation. Therefore biSize can be 0. Similarly
// there's no point checking exactly which colours are used, so
// biClrUsed and biClrImportant can be 0 to indicate all colours. This
// is therefore the end of BITMAPINFOHEADER. Simples.
uint j = 54;
for (uint i = 0; i < 768; i += 3) {
// RGBQUAD is in reverse order and the 4th byte is unused.
buf[j ] = palette[i+2];
buf[j+1] = palette[i+1];
buf[j+2] = palette[i ];
j += 4;
}
return abi.encodePacked(buf, pixels);
}
| /**
* @dev Returns an 8-bit BMP encoding of the pixels.
*
* Spec: https://www.digicamsoft.com/bmp/bmp.html
*
* Layout description with offsets:
* http://www.ece.ualberta.ca/~elliott/ee552/studentAppNotes/2003_w/misc/bmp_file_format/bmp_file_format.htm
*
* N.B. Everything is little-endian, hence the assembly for masking and
* shifting.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | {
"func_code_index": [
1100,
3551
]
} | 3,680 |
||
GermanBakery | /contracts/BMP.sol | 0x5721be2b7b1403daaea264daa26c29c51398bc2f | Solidity | BMP | contract BMP {
using Base64 for string;
/**
* @dev Returns an 8-bit grayscale palette for bitmap images.
*/
function grayscale() public pure returns (bytes memory) {
bytes memory palette = new bytes(768);
// TODO: investigate a way around using ++ += or + on a bytes1 without
// having to use a placeholder int8 for incrementing!
uint8 j;
bytes1 b;
for (uint16 i = 0; i < 768; i += 3) {
b = bytes1(j);
palette[i ] = b;
palette[i+1] = b;
palette[i+2] = b;
// The last increment would revert if checked.
unchecked { j++; }
}
return palette;
}
/**
* @dev Returns an 8-bit BMP encoding of the pixels.
*
* Spec: https://www.digicamsoft.com/bmp/bmp.html
*
* Layout description with offsets:
* http://www.ece.ualberta.ca/~elliott/ee552/studentAppNotes/2003_w/misc/bmp_file_format/bmp_file_format.htm
*
* N.B. Everything is little-endian, hence the assembly for masking and
* shifting.
*/
function bmp(bytes memory pixels, uint32 width, uint32 height, bytes memory palette) public pure returns (bytes memory) {
require(width * height == pixels.length, "Invalid dimensions");
require(palette.length == 768, "256 colours required");
// 14 bytes for BITMAPFILEHEADER + 40 for BITMAPINFOHEADER + 1024 for palette
bytes memory buf = new bytes(1078);
// BITMAPFILEHEADER
buf[0] = 0x42; buf[1] = 0x4d; // bfType = BM
uint32 size = 1078 + uint32(pixels.length);
// bfSize; bytes in the entire buffer
uint32 b;
for (uint i = 2; i < 6; i++) {
assembly {
b := and(size, 0xff)
size := shr(8, size)
}
buf[i] = bytes1(uint8(b));
}
// Next 4 bytes are bfReserved1 & 2; both = 0 = initial value
// bfOffBits; bytes from beginning of file to pixels = 14 + 40 + 1024
// (see size above)
buf[0x0a] = 0x36;
buf[0x0b] = 0x04;
// BITMAPINFOHEADER
// biSize; bytes in this struct = 40
buf[0x0e] = 0x28;
// biWidth / biHeight
for (uint i = 0x12; i < 0x16; i++) {
assembly {
b := and(width, 0xff)
width := shr(8, width)
}
buf[i] = bytes1(uint8(b));
}
for (uint i = 0x16; i < 0x1a; i++) {
assembly {
b := and(height, 0xff)
height := shr(8, height)
}
buf[i] = bytes1(uint8(b));
}
// biPlanes
buf[0x1a] = 0x01;
// biBitCount
buf[0x1c] = 0x08;
// I've decided to use raw pixels instead of run-length encoding for
// compression as these aren't being stored. It's therefore simpler to
// avoid the extra computation. Therefore biSize can be 0. Similarly
// there's no point checking exactly which colours are used, so
// biClrUsed and biClrImportant can be 0 to indicate all colours. This
// is therefore the end of BITMAPINFOHEADER. Simples.
uint j = 54;
for (uint i = 0; i < 768; i += 3) {
// RGBQUAD is in reverse order and the 4th byte is unused.
buf[j ] = palette[i+2];
buf[j+1] = palette[i+1];
buf[j+2] = palette[i ];
j += 4;
}
return abi.encodePacked(buf, pixels);
}
/**
* @dev Returns the buffer, presumably from bmp(), as a base64 data URI.
*/
function bmpDataURI(bytes memory bmpBuf) public pure returns (string memory) {
return string(abi.encodePacked(
'data:image/bmp;base64,',
Base64.encode(bmpBuf)
));
}
/**
* @dev Scale pixels by repetition along both axes.
*/
function scalePixels(bytes memory pixels, uint32 width, uint32 height, uint32 scale) public pure returns (bytes memory) {
require(width * height == pixels.length, "Invalid dimensions");
bytes memory scaled = new bytes(pixels.length * scale * scale);
// Indices in each of the original and scaled buffers, respectively. The
// scaled-buffer index is always incremented. The original index is
// incremented only after scaling x-wise by scale times, then reversed
// at the end of the width to allow for y-wise scaling.
uint32 origIdx;
uint32 scaleIdx;
for (uint32 y = 0; y < height; y++) {
for (uint32 yScale = 0; yScale < scale; yScale++) {
for (uint32 x = 0; x < width; x++) {
for (uint32 xScale = 0; xScale < scale; xScale++) {
scaled[scaleIdx] = pixels[origIdx];
scaleIdx++;
}
origIdx++;
}
// Rewind to copy the row again.
origIdx -= width;
}
// Don't just copy the first row.
origIdx += width;
}
return scaled;
}
} | /**
* @dev 8-bit BMP encoding with arbitrary colour palettes.
*/ | NatSpecMultiLine | bmpDataURI | function bmpDataURI(bytes memory bmpBuf) public pure returns (string memory) {
return string(abi.encodePacked(
'data:image/bmp;base64,',
Base64.encode(bmpBuf)
));
}
| /**
* @dev Returns the buffer, presumably from bmp(), as a base64 data URI.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | {
"func_code_index": [
3646,
3858
]
} | 3,681 |
||
GermanBakery | /contracts/BMP.sol | 0x5721be2b7b1403daaea264daa26c29c51398bc2f | Solidity | BMP | contract BMP {
using Base64 for string;
/**
* @dev Returns an 8-bit grayscale palette for bitmap images.
*/
function grayscale() public pure returns (bytes memory) {
bytes memory palette = new bytes(768);
// TODO: investigate a way around using ++ += or + on a bytes1 without
// having to use a placeholder int8 for incrementing!
uint8 j;
bytes1 b;
for (uint16 i = 0; i < 768; i += 3) {
b = bytes1(j);
palette[i ] = b;
palette[i+1] = b;
palette[i+2] = b;
// The last increment would revert if checked.
unchecked { j++; }
}
return palette;
}
/**
* @dev Returns an 8-bit BMP encoding of the pixels.
*
* Spec: https://www.digicamsoft.com/bmp/bmp.html
*
* Layout description with offsets:
* http://www.ece.ualberta.ca/~elliott/ee552/studentAppNotes/2003_w/misc/bmp_file_format/bmp_file_format.htm
*
* N.B. Everything is little-endian, hence the assembly for masking and
* shifting.
*/
function bmp(bytes memory pixels, uint32 width, uint32 height, bytes memory palette) public pure returns (bytes memory) {
require(width * height == pixels.length, "Invalid dimensions");
require(palette.length == 768, "256 colours required");
// 14 bytes for BITMAPFILEHEADER + 40 for BITMAPINFOHEADER + 1024 for palette
bytes memory buf = new bytes(1078);
// BITMAPFILEHEADER
buf[0] = 0x42; buf[1] = 0x4d; // bfType = BM
uint32 size = 1078 + uint32(pixels.length);
// bfSize; bytes in the entire buffer
uint32 b;
for (uint i = 2; i < 6; i++) {
assembly {
b := and(size, 0xff)
size := shr(8, size)
}
buf[i] = bytes1(uint8(b));
}
// Next 4 bytes are bfReserved1 & 2; both = 0 = initial value
// bfOffBits; bytes from beginning of file to pixels = 14 + 40 + 1024
// (see size above)
buf[0x0a] = 0x36;
buf[0x0b] = 0x04;
// BITMAPINFOHEADER
// biSize; bytes in this struct = 40
buf[0x0e] = 0x28;
// biWidth / biHeight
for (uint i = 0x12; i < 0x16; i++) {
assembly {
b := and(width, 0xff)
width := shr(8, width)
}
buf[i] = bytes1(uint8(b));
}
for (uint i = 0x16; i < 0x1a; i++) {
assembly {
b := and(height, 0xff)
height := shr(8, height)
}
buf[i] = bytes1(uint8(b));
}
// biPlanes
buf[0x1a] = 0x01;
// biBitCount
buf[0x1c] = 0x08;
// I've decided to use raw pixels instead of run-length encoding for
// compression as these aren't being stored. It's therefore simpler to
// avoid the extra computation. Therefore biSize can be 0. Similarly
// there's no point checking exactly which colours are used, so
// biClrUsed and biClrImportant can be 0 to indicate all colours. This
// is therefore the end of BITMAPINFOHEADER. Simples.
uint j = 54;
for (uint i = 0; i < 768; i += 3) {
// RGBQUAD is in reverse order and the 4th byte is unused.
buf[j ] = palette[i+2];
buf[j+1] = palette[i+1];
buf[j+2] = palette[i ];
j += 4;
}
return abi.encodePacked(buf, pixels);
}
/**
* @dev Returns the buffer, presumably from bmp(), as a base64 data URI.
*/
function bmpDataURI(bytes memory bmpBuf) public pure returns (string memory) {
return string(abi.encodePacked(
'data:image/bmp;base64,',
Base64.encode(bmpBuf)
));
}
/**
* @dev Scale pixels by repetition along both axes.
*/
function scalePixels(bytes memory pixels, uint32 width, uint32 height, uint32 scale) public pure returns (bytes memory) {
require(width * height == pixels.length, "Invalid dimensions");
bytes memory scaled = new bytes(pixels.length * scale * scale);
// Indices in each of the original and scaled buffers, respectively. The
// scaled-buffer index is always incremented. The original index is
// incremented only after scaling x-wise by scale times, then reversed
// at the end of the width to allow for y-wise scaling.
uint32 origIdx;
uint32 scaleIdx;
for (uint32 y = 0; y < height; y++) {
for (uint32 yScale = 0; yScale < scale; yScale++) {
for (uint32 x = 0; x < width; x++) {
for (uint32 xScale = 0; xScale < scale; xScale++) {
scaled[scaleIdx] = pixels[origIdx];
scaleIdx++;
}
origIdx++;
}
// Rewind to copy the row again.
origIdx -= width;
}
// Don't just copy the first row.
origIdx += width;
}
return scaled;
}
} | /**
* @dev 8-bit BMP encoding with arbitrary colour palettes.
*/ | NatSpecMultiLine | scalePixels | function scalePixels(bytes memory pixels, uint32 width, uint32 height, uint32 scale) public pure returns (bytes memory) {
require(width * height == pixels.length, "Invalid dimensions");
bytes memory scaled = new bytes(pixels.length * scale * scale);
// Indices in each of the original and scaled buffers, respectively. The
// scaled-buffer index is always incremented. The original index is
// incremented only after scaling x-wise by scale times, then reversed
// at the end of the width to allow for y-wise scaling.
uint32 origIdx;
uint32 scaleIdx;
for (uint32 y = 0; y < height; y++) {
for (uint32 yScale = 0; yScale < scale; yScale++) {
for (uint32 x = 0; x < width; x++) {
for (uint32 xScale = 0; xScale < scale; xScale++) {
scaled[scaleIdx] = pixels[origIdx];
scaleIdx++;
}
origIdx++;
}
// Rewind to copy the row again.
origIdx -= width;
}
// Don't just copy the first row.
origIdx += width;
}
return scaled;
}
| /**
* @dev Scale pixels by repetition along both axes.
*/ | NatSpecMultiLine | v0.8.7+commit.e28d00a7 | {
"func_code_index": [
3932,
5166
]
} | 3,682 |
||
TimeLockRegistry | contracts/token/TimeLockRegistry.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | TimeLockRegistry | contract TimeLockRegistry is Ownable {
using LowGasSafeMath for uint256;
using Address for address;
using AddressArrayUtils for address[];
/* ============ Events ============ */
event Register(address receiver, uint256 distribution);
event Cancel(address receiver, uint256 distribution);
event Claim(address account, uint256 distribution);
/* ============ Modifiers ============ */
modifier onlyBABLToken() {
require(msg.sender == address(token), 'only BABL Token');
_;
}
/* ============ State Variables ============ */
// time locked token
TimeLockedToken public token;
/**
* @notice The profile of each token owner under vesting conditions and its special conditions
* @param receiver Account being registered
* @param investorType Indicates whether or not is a Team member (true = team member / advisor, false = private investor)
* @param vestingStarting Date When the vesting begins for such token owner
* @param distribution Tokens amount that receiver is due to get
*/
struct Registration {
address receiver;
uint256 distribution;
bool investorType;
uint256 vestingStartingDate;
}
/**
* @notice The profile of each token owner under vesting conditions and its special conditions
* @param team Indicates whether or not is a Team member (true = team member / advisor, false = private investor)
* @param vestingBegin When the vesting begins for such token owner
* @param vestingEnd When the vesting ends for such token owner
* @param lastClaim When the last claim was done
*/
struct TokenVested {
bool team;
bool cliff;
uint256 vestingBegin;
uint256 vestingEnd;
uint256 lastClaim;
}
/// @notice A record of token owners under vesting conditions for each account, by index
mapping(address => TokenVested) public tokenVested;
// mapping from token owners under vesting conditions to BABL due amount (e.g. SAFT addresses, team members, advisors)
mapping(address => uint256) public registeredDistributions;
// array of all registrations
address[] public registrations;
// total amount of tokens registered
uint256 public totalTokens;
// vesting for Team Members
uint256 private constant teamVesting = 365 days * 4;
// vesting for Investors and Advisors
uint256 private constant investorVesting = 365 days * 3;
/* ============ Functions ============ */
/* ============ Constructor ============ */
/**
* @notice Construct a new Time Lock Registry and gives ownership to sender
* @param _token TimeLockedToken contract to use in this registry
*/
constructor(TimeLockedToken _token) {
token = _token;
}
/* ============ External Functions ============ */
/* ============ External Getter Functions ============ */
/**
* Gets registrations
*
* @return address[] Returns list of registrations
*/
function getRegistrations() external view returns (address[] memory) {
return registrations;
}
/* =========== Token related Gov Functions ====== */
/**
* PRIVILEGED GOVERNANCE FUNCTION
*
* @notice Register multiple investors/team in a batch
* @param _registrations Registrations to process
*/
function registerBatch(Registration[] memory _registrations) external onlyOwner {
for (uint256 i = 0; i < _registrations.length; i++) {
register(
_registrations[i].receiver,
_registrations[i].distribution,
_registrations[i].investorType,
_registrations[i].vestingStartingDate
);
}
}
/**
* PRIVILEGED GOVERNANCE FUNCTION
*
* @notice Register new account under vesting conditions (Team, Advisors, Investors e.g. SAFT purchaser)
* @param receiver Address belonging vesting conditions
* @param distribution Tokens amount that receiver is due to get
*/
function register(
address receiver,
uint256 distribution,
bool investorType,
uint256 vestingStartingDate
) public onlyOwner {
require(receiver != address(0), 'TimeLockRegistry::register: cannot register the zero address');
require(
receiver != address(this),
'TimeLockRegistry::register: Time Lock Registry contract cannot be an investor'
);
require(distribution != 0, 'TimeLockRegistry::register: Distribution = 0');
require(
registeredDistributions[receiver] == 0,
'TimeLockRegistry::register:Distribution for this address is already registered'
);
require(block.timestamp >= 1614553200, 'Cannot register earlier than March 2021'); // 1614553200 is UNIX TIME of 2021 March the 1st
require(totalTokens.add(distribution) <= IERC20(token).balanceOf(address(this)), 'Not enough tokens');
totalTokens = totalTokens.add(distribution);
// register distribution
registeredDistributions[receiver] = distribution;
registrations.push(receiver);
// register token vested conditions
TokenVested storage newTokenVested = tokenVested[receiver];
newTokenVested.team = investorType;
newTokenVested.vestingBegin = vestingStartingDate;
if (newTokenVested.team == true) {
newTokenVested.vestingEnd = vestingStartingDate.add(teamVesting);
} else {
newTokenVested.vestingEnd = vestingStartingDate.add(investorVesting);
}
newTokenVested.lastClaim = vestingStartingDate;
tokenVested[receiver] = newTokenVested;
// emit register event
emit Register(receiver, distribution);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Cancel distribution registration in case of mistake and before a claim is done
*
* @notice Cancel distribution registration
* @dev A claim has not to be done earlier
* @param receiver Address that should have it's distribution removed
* @return Whether or not it succeeded
*/
function cancelRegistration(address receiver) external onlyOwner returns (bool) {
require(registeredDistributions[receiver] != 0, 'Not registered');
// get amount from distributions
uint256 amount = registeredDistributions[receiver];
// set distribution mapping to 0
delete registeredDistributions[receiver];
// set tokenVested mapping to 0
delete tokenVested[receiver];
// remove from the list of all registrations
registrations.remove(receiver);
// decrease total tokens
totalTokens = totalTokens.sub(amount);
// emit cancel event
emit Cancel(receiver, amount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Cancel distribution registration in case of mistake and before a claim is done
*
* @notice Cancel already delivered tokens. It might only apply when non-completion of vesting period of Team members or Advisors
* @dev An automatic override allowance is granted during the claim process
* @param account Address that should have it's distribution removed
* @return Whether or not it succeeded
*/
function cancelDeliveredTokens(address account) external onlyOwner returns (bool) {
uint256 loosingAmount = token.cancelVestedTokens(account);
// emit cancel event
emit Cancel(account, loosingAmount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Recover tokens in Time Lock Registry smartcontract address by the owner
*
* @notice Send tokens from smartcontract address to the owner.
* It might only apply after a cancellation of vested tokens
* @param amount Amount to be recovered by the owner of the Time Lock Registry smartcontract from its balance
* @return Whether or not it succeeded
*/
function transferToOwner(uint256 amount) external onlyOwner returns (bool) {
SafeERC20.safeTransfer(token, msg.sender, amount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Claim locked tokens by the registered account
*
* @notice Claim tokens due amount.
* @dev Claim is done by the user in the TimeLocked contract and the contract is the only allowed to call
* this function on behalf of the user to make the claim
* @return The amount of tokens registered and delivered after the claim
*/
function claim(address _receiver) external onlyBABLToken returns (uint256) {
require(registeredDistributions[_receiver] != 0, 'Not registered');
// get amount from distributions
uint256 amount = registeredDistributions[_receiver];
TokenVested storage claimTokenVested = tokenVested[_receiver];
claimTokenVested.lastClaim = block.timestamp;
// set distribution mapping to 0
delete registeredDistributions[_receiver];
// decrease total tokens
totalTokens = totalTokens.sub(amount);
// register lockup in TimeLockedToken
// this will transfer funds from this contract and lock them for sender
token.registerLockup(
_receiver,
amount,
claimTokenVested.team,
claimTokenVested.vestingBegin,
claimTokenVested.vestingEnd,
claimTokenVested.lastClaim
);
// set tokenVested mapping to 0
delete tokenVested[_receiver];
// emit claim event
emit Claim(_receiver, amount);
return amount;
}
/* ============ Getter Functions ============ */
function checkVesting(address address_)
external
view
returns (
bool team,
uint256 start,
uint256 end,
uint256 last
)
{
TokenVested storage checkTokenVested = tokenVested[address_];
return (
checkTokenVested.team,
checkTokenVested.vestingBegin,
checkTokenVested.vestingEnd,
checkTokenVested.lastClaim
);
}
function checkRegisteredDistribution(address address_) external view returns (uint256 amount) {
return registeredDistributions[address_];
}
} | /**
* @title TimeLockRegistry
* @notice Register Lockups for TimeLocked ERC20 Token BABL (e.g. vesting)
* @author Babylon Finance
* @dev This contract allows owner to register distributions for a TimeLockedToken
*
* To register a distribution, register method should be called by the owner.
* claim() should be called only by the BABL Token smartcontract (modifier onlyBABLToken)
* when any account registered to receive tokens make its own claim
* If case of a mistake, owner can cancel registration before the claim is done by the account
*
* Note this contract address must be setup in the TimeLockedToken's contract pointing
* to interact with (e.g. setTimeLockRegistry() function)
*/ | NatSpecMultiLine | getRegistrations | function getRegistrations() external view returns (address[] memory) {
return registrations;
}
| /**
* Gets registrations
*
* @return address[] Returns list of registrations
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | {
"func_code_index": [
3063,
3173
]
} | 3,683 |
||
TimeLockRegistry | contracts/token/TimeLockRegistry.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | TimeLockRegistry | contract TimeLockRegistry is Ownable {
using LowGasSafeMath for uint256;
using Address for address;
using AddressArrayUtils for address[];
/* ============ Events ============ */
event Register(address receiver, uint256 distribution);
event Cancel(address receiver, uint256 distribution);
event Claim(address account, uint256 distribution);
/* ============ Modifiers ============ */
modifier onlyBABLToken() {
require(msg.sender == address(token), 'only BABL Token');
_;
}
/* ============ State Variables ============ */
// time locked token
TimeLockedToken public token;
/**
* @notice The profile of each token owner under vesting conditions and its special conditions
* @param receiver Account being registered
* @param investorType Indicates whether or not is a Team member (true = team member / advisor, false = private investor)
* @param vestingStarting Date When the vesting begins for such token owner
* @param distribution Tokens amount that receiver is due to get
*/
struct Registration {
address receiver;
uint256 distribution;
bool investorType;
uint256 vestingStartingDate;
}
/**
* @notice The profile of each token owner under vesting conditions and its special conditions
* @param team Indicates whether or not is a Team member (true = team member / advisor, false = private investor)
* @param vestingBegin When the vesting begins for such token owner
* @param vestingEnd When the vesting ends for such token owner
* @param lastClaim When the last claim was done
*/
struct TokenVested {
bool team;
bool cliff;
uint256 vestingBegin;
uint256 vestingEnd;
uint256 lastClaim;
}
/// @notice A record of token owners under vesting conditions for each account, by index
mapping(address => TokenVested) public tokenVested;
// mapping from token owners under vesting conditions to BABL due amount (e.g. SAFT addresses, team members, advisors)
mapping(address => uint256) public registeredDistributions;
// array of all registrations
address[] public registrations;
// total amount of tokens registered
uint256 public totalTokens;
// vesting for Team Members
uint256 private constant teamVesting = 365 days * 4;
// vesting for Investors and Advisors
uint256 private constant investorVesting = 365 days * 3;
/* ============ Functions ============ */
/* ============ Constructor ============ */
/**
* @notice Construct a new Time Lock Registry and gives ownership to sender
* @param _token TimeLockedToken contract to use in this registry
*/
constructor(TimeLockedToken _token) {
token = _token;
}
/* ============ External Functions ============ */
/* ============ External Getter Functions ============ */
/**
* Gets registrations
*
* @return address[] Returns list of registrations
*/
function getRegistrations() external view returns (address[] memory) {
return registrations;
}
/* =========== Token related Gov Functions ====== */
/**
* PRIVILEGED GOVERNANCE FUNCTION
*
* @notice Register multiple investors/team in a batch
* @param _registrations Registrations to process
*/
function registerBatch(Registration[] memory _registrations) external onlyOwner {
for (uint256 i = 0; i < _registrations.length; i++) {
register(
_registrations[i].receiver,
_registrations[i].distribution,
_registrations[i].investorType,
_registrations[i].vestingStartingDate
);
}
}
/**
* PRIVILEGED GOVERNANCE FUNCTION
*
* @notice Register new account under vesting conditions (Team, Advisors, Investors e.g. SAFT purchaser)
* @param receiver Address belonging vesting conditions
* @param distribution Tokens amount that receiver is due to get
*/
function register(
address receiver,
uint256 distribution,
bool investorType,
uint256 vestingStartingDate
) public onlyOwner {
require(receiver != address(0), 'TimeLockRegistry::register: cannot register the zero address');
require(
receiver != address(this),
'TimeLockRegistry::register: Time Lock Registry contract cannot be an investor'
);
require(distribution != 0, 'TimeLockRegistry::register: Distribution = 0');
require(
registeredDistributions[receiver] == 0,
'TimeLockRegistry::register:Distribution for this address is already registered'
);
require(block.timestamp >= 1614553200, 'Cannot register earlier than March 2021'); // 1614553200 is UNIX TIME of 2021 March the 1st
require(totalTokens.add(distribution) <= IERC20(token).balanceOf(address(this)), 'Not enough tokens');
totalTokens = totalTokens.add(distribution);
// register distribution
registeredDistributions[receiver] = distribution;
registrations.push(receiver);
// register token vested conditions
TokenVested storage newTokenVested = tokenVested[receiver];
newTokenVested.team = investorType;
newTokenVested.vestingBegin = vestingStartingDate;
if (newTokenVested.team == true) {
newTokenVested.vestingEnd = vestingStartingDate.add(teamVesting);
} else {
newTokenVested.vestingEnd = vestingStartingDate.add(investorVesting);
}
newTokenVested.lastClaim = vestingStartingDate;
tokenVested[receiver] = newTokenVested;
// emit register event
emit Register(receiver, distribution);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Cancel distribution registration in case of mistake and before a claim is done
*
* @notice Cancel distribution registration
* @dev A claim has not to be done earlier
* @param receiver Address that should have it's distribution removed
* @return Whether or not it succeeded
*/
function cancelRegistration(address receiver) external onlyOwner returns (bool) {
require(registeredDistributions[receiver] != 0, 'Not registered');
// get amount from distributions
uint256 amount = registeredDistributions[receiver];
// set distribution mapping to 0
delete registeredDistributions[receiver];
// set tokenVested mapping to 0
delete tokenVested[receiver];
// remove from the list of all registrations
registrations.remove(receiver);
// decrease total tokens
totalTokens = totalTokens.sub(amount);
// emit cancel event
emit Cancel(receiver, amount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Cancel distribution registration in case of mistake and before a claim is done
*
* @notice Cancel already delivered tokens. It might only apply when non-completion of vesting period of Team members or Advisors
* @dev An automatic override allowance is granted during the claim process
* @param account Address that should have it's distribution removed
* @return Whether or not it succeeded
*/
function cancelDeliveredTokens(address account) external onlyOwner returns (bool) {
uint256 loosingAmount = token.cancelVestedTokens(account);
// emit cancel event
emit Cancel(account, loosingAmount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Recover tokens in Time Lock Registry smartcontract address by the owner
*
* @notice Send tokens from smartcontract address to the owner.
* It might only apply after a cancellation of vested tokens
* @param amount Amount to be recovered by the owner of the Time Lock Registry smartcontract from its balance
* @return Whether or not it succeeded
*/
function transferToOwner(uint256 amount) external onlyOwner returns (bool) {
SafeERC20.safeTransfer(token, msg.sender, amount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Claim locked tokens by the registered account
*
* @notice Claim tokens due amount.
* @dev Claim is done by the user in the TimeLocked contract and the contract is the only allowed to call
* this function on behalf of the user to make the claim
* @return The amount of tokens registered and delivered after the claim
*/
function claim(address _receiver) external onlyBABLToken returns (uint256) {
require(registeredDistributions[_receiver] != 0, 'Not registered');
// get amount from distributions
uint256 amount = registeredDistributions[_receiver];
TokenVested storage claimTokenVested = tokenVested[_receiver];
claimTokenVested.lastClaim = block.timestamp;
// set distribution mapping to 0
delete registeredDistributions[_receiver];
// decrease total tokens
totalTokens = totalTokens.sub(amount);
// register lockup in TimeLockedToken
// this will transfer funds from this contract and lock them for sender
token.registerLockup(
_receiver,
amount,
claimTokenVested.team,
claimTokenVested.vestingBegin,
claimTokenVested.vestingEnd,
claimTokenVested.lastClaim
);
// set tokenVested mapping to 0
delete tokenVested[_receiver];
// emit claim event
emit Claim(_receiver, amount);
return amount;
}
/* ============ Getter Functions ============ */
function checkVesting(address address_)
external
view
returns (
bool team,
uint256 start,
uint256 end,
uint256 last
)
{
TokenVested storage checkTokenVested = tokenVested[address_];
return (
checkTokenVested.team,
checkTokenVested.vestingBegin,
checkTokenVested.vestingEnd,
checkTokenVested.lastClaim
);
}
function checkRegisteredDistribution(address address_) external view returns (uint256 amount) {
return registeredDistributions[address_];
}
} | /**
* @title TimeLockRegistry
* @notice Register Lockups for TimeLocked ERC20 Token BABL (e.g. vesting)
* @author Babylon Finance
* @dev This contract allows owner to register distributions for a TimeLockedToken
*
* To register a distribution, register method should be called by the owner.
* claim() should be called only by the BABL Token smartcontract (modifier onlyBABLToken)
* when any account registered to receive tokens make its own claim
* If case of a mistake, owner can cancel registration before the claim is done by the account
*
* Note this contract address must be setup in the TimeLockedToken's contract pointing
* to interact with (e.g. setTimeLockRegistry() function)
*/ | NatSpecMultiLine | registerBatch | function registerBatch(Registration[] memory _registrations) external onlyOwner {
for (uint256 i = 0; i < _registrations.length; i++) {
register(
_registrations[i].receiver,
_registrations[i].distribution,
_registrations[i].investorType,
_registrations[i].vestingStartingDate
);
}
}
| /**
* PRIVILEGED GOVERNANCE FUNCTION
*
* @notice Register multiple investors/team in a batch
* @param _registrations Registrations to process
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | {
"func_code_index": [
3408,
3802
]
} | 3,684 |
||
TimeLockRegistry | contracts/token/TimeLockRegistry.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | TimeLockRegistry | contract TimeLockRegistry is Ownable {
using LowGasSafeMath for uint256;
using Address for address;
using AddressArrayUtils for address[];
/* ============ Events ============ */
event Register(address receiver, uint256 distribution);
event Cancel(address receiver, uint256 distribution);
event Claim(address account, uint256 distribution);
/* ============ Modifiers ============ */
modifier onlyBABLToken() {
require(msg.sender == address(token), 'only BABL Token');
_;
}
/* ============ State Variables ============ */
// time locked token
TimeLockedToken public token;
/**
* @notice The profile of each token owner under vesting conditions and its special conditions
* @param receiver Account being registered
* @param investorType Indicates whether or not is a Team member (true = team member / advisor, false = private investor)
* @param vestingStarting Date When the vesting begins for such token owner
* @param distribution Tokens amount that receiver is due to get
*/
struct Registration {
address receiver;
uint256 distribution;
bool investorType;
uint256 vestingStartingDate;
}
/**
* @notice The profile of each token owner under vesting conditions and its special conditions
* @param team Indicates whether or not is a Team member (true = team member / advisor, false = private investor)
* @param vestingBegin When the vesting begins for such token owner
* @param vestingEnd When the vesting ends for such token owner
* @param lastClaim When the last claim was done
*/
struct TokenVested {
bool team;
bool cliff;
uint256 vestingBegin;
uint256 vestingEnd;
uint256 lastClaim;
}
/// @notice A record of token owners under vesting conditions for each account, by index
mapping(address => TokenVested) public tokenVested;
// mapping from token owners under vesting conditions to BABL due amount (e.g. SAFT addresses, team members, advisors)
mapping(address => uint256) public registeredDistributions;
// array of all registrations
address[] public registrations;
// total amount of tokens registered
uint256 public totalTokens;
// vesting for Team Members
uint256 private constant teamVesting = 365 days * 4;
// vesting for Investors and Advisors
uint256 private constant investorVesting = 365 days * 3;
/* ============ Functions ============ */
/* ============ Constructor ============ */
/**
* @notice Construct a new Time Lock Registry and gives ownership to sender
* @param _token TimeLockedToken contract to use in this registry
*/
constructor(TimeLockedToken _token) {
token = _token;
}
/* ============ External Functions ============ */
/* ============ External Getter Functions ============ */
/**
* Gets registrations
*
* @return address[] Returns list of registrations
*/
function getRegistrations() external view returns (address[] memory) {
return registrations;
}
/* =========== Token related Gov Functions ====== */
/**
* PRIVILEGED GOVERNANCE FUNCTION
*
* @notice Register multiple investors/team in a batch
* @param _registrations Registrations to process
*/
function registerBatch(Registration[] memory _registrations) external onlyOwner {
for (uint256 i = 0; i < _registrations.length; i++) {
register(
_registrations[i].receiver,
_registrations[i].distribution,
_registrations[i].investorType,
_registrations[i].vestingStartingDate
);
}
}
/**
* PRIVILEGED GOVERNANCE FUNCTION
*
* @notice Register new account under vesting conditions (Team, Advisors, Investors e.g. SAFT purchaser)
* @param receiver Address belonging vesting conditions
* @param distribution Tokens amount that receiver is due to get
*/
function register(
address receiver,
uint256 distribution,
bool investorType,
uint256 vestingStartingDate
) public onlyOwner {
require(receiver != address(0), 'TimeLockRegistry::register: cannot register the zero address');
require(
receiver != address(this),
'TimeLockRegistry::register: Time Lock Registry contract cannot be an investor'
);
require(distribution != 0, 'TimeLockRegistry::register: Distribution = 0');
require(
registeredDistributions[receiver] == 0,
'TimeLockRegistry::register:Distribution for this address is already registered'
);
require(block.timestamp >= 1614553200, 'Cannot register earlier than March 2021'); // 1614553200 is UNIX TIME of 2021 March the 1st
require(totalTokens.add(distribution) <= IERC20(token).balanceOf(address(this)), 'Not enough tokens');
totalTokens = totalTokens.add(distribution);
// register distribution
registeredDistributions[receiver] = distribution;
registrations.push(receiver);
// register token vested conditions
TokenVested storage newTokenVested = tokenVested[receiver];
newTokenVested.team = investorType;
newTokenVested.vestingBegin = vestingStartingDate;
if (newTokenVested.team == true) {
newTokenVested.vestingEnd = vestingStartingDate.add(teamVesting);
} else {
newTokenVested.vestingEnd = vestingStartingDate.add(investorVesting);
}
newTokenVested.lastClaim = vestingStartingDate;
tokenVested[receiver] = newTokenVested;
// emit register event
emit Register(receiver, distribution);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Cancel distribution registration in case of mistake and before a claim is done
*
* @notice Cancel distribution registration
* @dev A claim has not to be done earlier
* @param receiver Address that should have it's distribution removed
* @return Whether or not it succeeded
*/
function cancelRegistration(address receiver) external onlyOwner returns (bool) {
require(registeredDistributions[receiver] != 0, 'Not registered');
// get amount from distributions
uint256 amount = registeredDistributions[receiver];
// set distribution mapping to 0
delete registeredDistributions[receiver];
// set tokenVested mapping to 0
delete tokenVested[receiver];
// remove from the list of all registrations
registrations.remove(receiver);
// decrease total tokens
totalTokens = totalTokens.sub(amount);
// emit cancel event
emit Cancel(receiver, amount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Cancel distribution registration in case of mistake and before a claim is done
*
* @notice Cancel already delivered tokens. It might only apply when non-completion of vesting period of Team members or Advisors
* @dev An automatic override allowance is granted during the claim process
* @param account Address that should have it's distribution removed
* @return Whether or not it succeeded
*/
function cancelDeliveredTokens(address account) external onlyOwner returns (bool) {
uint256 loosingAmount = token.cancelVestedTokens(account);
// emit cancel event
emit Cancel(account, loosingAmount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Recover tokens in Time Lock Registry smartcontract address by the owner
*
* @notice Send tokens from smartcontract address to the owner.
* It might only apply after a cancellation of vested tokens
* @param amount Amount to be recovered by the owner of the Time Lock Registry smartcontract from its balance
* @return Whether or not it succeeded
*/
function transferToOwner(uint256 amount) external onlyOwner returns (bool) {
SafeERC20.safeTransfer(token, msg.sender, amount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Claim locked tokens by the registered account
*
* @notice Claim tokens due amount.
* @dev Claim is done by the user in the TimeLocked contract and the contract is the only allowed to call
* this function on behalf of the user to make the claim
* @return The amount of tokens registered and delivered after the claim
*/
function claim(address _receiver) external onlyBABLToken returns (uint256) {
require(registeredDistributions[_receiver] != 0, 'Not registered');
// get amount from distributions
uint256 amount = registeredDistributions[_receiver];
TokenVested storage claimTokenVested = tokenVested[_receiver];
claimTokenVested.lastClaim = block.timestamp;
// set distribution mapping to 0
delete registeredDistributions[_receiver];
// decrease total tokens
totalTokens = totalTokens.sub(amount);
// register lockup in TimeLockedToken
// this will transfer funds from this contract and lock them for sender
token.registerLockup(
_receiver,
amount,
claimTokenVested.team,
claimTokenVested.vestingBegin,
claimTokenVested.vestingEnd,
claimTokenVested.lastClaim
);
// set tokenVested mapping to 0
delete tokenVested[_receiver];
// emit claim event
emit Claim(_receiver, amount);
return amount;
}
/* ============ Getter Functions ============ */
function checkVesting(address address_)
external
view
returns (
bool team,
uint256 start,
uint256 end,
uint256 last
)
{
TokenVested storage checkTokenVested = tokenVested[address_];
return (
checkTokenVested.team,
checkTokenVested.vestingBegin,
checkTokenVested.vestingEnd,
checkTokenVested.lastClaim
);
}
function checkRegisteredDistribution(address address_) external view returns (uint256 amount) {
return registeredDistributions[address_];
}
} | /**
* @title TimeLockRegistry
* @notice Register Lockups for TimeLocked ERC20 Token BABL (e.g. vesting)
* @author Babylon Finance
* @dev This contract allows owner to register distributions for a TimeLockedToken
*
* To register a distribution, register method should be called by the owner.
* claim() should be called only by the BABL Token smartcontract (modifier onlyBABLToken)
* when any account registered to receive tokens make its own claim
* If case of a mistake, owner can cancel registration before the claim is done by the account
*
* Note this contract address must be setup in the TimeLockedToken's contract pointing
* to interact with (e.g. setTimeLockRegistry() function)
*/ | NatSpecMultiLine | register | function register(
address receiver,
uint256 distribution,
bool investorType,
uint256 vestingStartingDate
) public onlyOwner {
require(receiver != address(0), 'TimeLockRegistry::register: cannot register the zero address');
require(
receiver != address(this),
'TimeLockRegistry::register: Time Lock Registry contract cannot be an investor'
);
require(distribution != 0, 'TimeLockRegistry::register: Distribution = 0');
require(
registeredDistributions[receiver] == 0,
'TimeLockRegistry::register:Distribution for this address is already registered'
);
require(block.timestamp >= 1614553200, 'Cannot register earlier than March 2021'); // 1614553200 is UNIX TIME of 2021 March the 1st
require(totalTokens.add(distribution) <= IERC20(token).balanceOf(address(this)), 'Not enough tokens');
totalTokens = totalTokens.add(distribution);
// register distribution
registeredDistributions[receiver] = distribution;
registrations.push(receiver);
// register token vested conditions
TokenVested storage newTokenVested = tokenVested[receiver];
newTokenVested.team = investorType;
newTokenVested.vestingBegin = vestingStartingDate;
if (newTokenVested.team == true) {
newTokenVested.vestingEnd = vestingStartingDate.add(teamVesting);
} else {
newTokenVested.vestingEnd = vestingStartingDate.add(investorVesting);
}
newTokenVested.lastClaim = vestingStartingDate;
tokenVested[receiver] = newTokenVested;
// emit register event
emit Register(receiver, distribution);
}
| /**
* PRIVILEGED GOVERNANCE FUNCTION
*
* @notice Register new account under vesting conditions (Team, Advisors, Investors e.g. SAFT purchaser)
* @param receiver Address belonging vesting conditions
* @param distribution Tokens amount that receiver is due to get
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | {
"func_code_index": [
4103,
5861
]
} | 3,685 |
||
TimeLockRegistry | contracts/token/TimeLockRegistry.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | TimeLockRegistry | contract TimeLockRegistry is Ownable {
using LowGasSafeMath for uint256;
using Address for address;
using AddressArrayUtils for address[];
/* ============ Events ============ */
event Register(address receiver, uint256 distribution);
event Cancel(address receiver, uint256 distribution);
event Claim(address account, uint256 distribution);
/* ============ Modifiers ============ */
modifier onlyBABLToken() {
require(msg.sender == address(token), 'only BABL Token');
_;
}
/* ============ State Variables ============ */
// time locked token
TimeLockedToken public token;
/**
* @notice The profile of each token owner under vesting conditions and its special conditions
* @param receiver Account being registered
* @param investorType Indicates whether or not is a Team member (true = team member / advisor, false = private investor)
* @param vestingStarting Date When the vesting begins for such token owner
* @param distribution Tokens amount that receiver is due to get
*/
struct Registration {
address receiver;
uint256 distribution;
bool investorType;
uint256 vestingStartingDate;
}
/**
* @notice The profile of each token owner under vesting conditions and its special conditions
* @param team Indicates whether or not is a Team member (true = team member / advisor, false = private investor)
* @param vestingBegin When the vesting begins for such token owner
* @param vestingEnd When the vesting ends for such token owner
* @param lastClaim When the last claim was done
*/
struct TokenVested {
bool team;
bool cliff;
uint256 vestingBegin;
uint256 vestingEnd;
uint256 lastClaim;
}
/// @notice A record of token owners under vesting conditions for each account, by index
mapping(address => TokenVested) public tokenVested;
// mapping from token owners under vesting conditions to BABL due amount (e.g. SAFT addresses, team members, advisors)
mapping(address => uint256) public registeredDistributions;
// array of all registrations
address[] public registrations;
// total amount of tokens registered
uint256 public totalTokens;
// vesting for Team Members
uint256 private constant teamVesting = 365 days * 4;
// vesting for Investors and Advisors
uint256 private constant investorVesting = 365 days * 3;
/* ============ Functions ============ */
/* ============ Constructor ============ */
/**
* @notice Construct a new Time Lock Registry and gives ownership to sender
* @param _token TimeLockedToken contract to use in this registry
*/
constructor(TimeLockedToken _token) {
token = _token;
}
/* ============ External Functions ============ */
/* ============ External Getter Functions ============ */
/**
* Gets registrations
*
* @return address[] Returns list of registrations
*/
function getRegistrations() external view returns (address[] memory) {
return registrations;
}
/* =========== Token related Gov Functions ====== */
/**
* PRIVILEGED GOVERNANCE FUNCTION
*
* @notice Register multiple investors/team in a batch
* @param _registrations Registrations to process
*/
function registerBatch(Registration[] memory _registrations) external onlyOwner {
for (uint256 i = 0; i < _registrations.length; i++) {
register(
_registrations[i].receiver,
_registrations[i].distribution,
_registrations[i].investorType,
_registrations[i].vestingStartingDate
);
}
}
/**
* PRIVILEGED GOVERNANCE FUNCTION
*
* @notice Register new account under vesting conditions (Team, Advisors, Investors e.g. SAFT purchaser)
* @param receiver Address belonging vesting conditions
* @param distribution Tokens amount that receiver is due to get
*/
function register(
address receiver,
uint256 distribution,
bool investorType,
uint256 vestingStartingDate
) public onlyOwner {
require(receiver != address(0), 'TimeLockRegistry::register: cannot register the zero address');
require(
receiver != address(this),
'TimeLockRegistry::register: Time Lock Registry contract cannot be an investor'
);
require(distribution != 0, 'TimeLockRegistry::register: Distribution = 0');
require(
registeredDistributions[receiver] == 0,
'TimeLockRegistry::register:Distribution for this address is already registered'
);
require(block.timestamp >= 1614553200, 'Cannot register earlier than March 2021'); // 1614553200 is UNIX TIME of 2021 March the 1st
require(totalTokens.add(distribution) <= IERC20(token).balanceOf(address(this)), 'Not enough tokens');
totalTokens = totalTokens.add(distribution);
// register distribution
registeredDistributions[receiver] = distribution;
registrations.push(receiver);
// register token vested conditions
TokenVested storage newTokenVested = tokenVested[receiver];
newTokenVested.team = investorType;
newTokenVested.vestingBegin = vestingStartingDate;
if (newTokenVested.team == true) {
newTokenVested.vestingEnd = vestingStartingDate.add(teamVesting);
} else {
newTokenVested.vestingEnd = vestingStartingDate.add(investorVesting);
}
newTokenVested.lastClaim = vestingStartingDate;
tokenVested[receiver] = newTokenVested;
// emit register event
emit Register(receiver, distribution);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Cancel distribution registration in case of mistake and before a claim is done
*
* @notice Cancel distribution registration
* @dev A claim has not to be done earlier
* @param receiver Address that should have it's distribution removed
* @return Whether or not it succeeded
*/
function cancelRegistration(address receiver) external onlyOwner returns (bool) {
require(registeredDistributions[receiver] != 0, 'Not registered');
// get amount from distributions
uint256 amount = registeredDistributions[receiver];
// set distribution mapping to 0
delete registeredDistributions[receiver];
// set tokenVested mapping to 0
delete tokenVested[receiver];
// remove from the list of all registrations
registrations.remove(receiver);
// decrease total tokens
totalTokens = totalTokens.sub(amount);
// emit cancel event
emit Cancel(receiver, amount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Cancel distribution registration in case of mistake and before a claim is done
*
* @notice Cancel already delivered tokens. It might only apply when non-completion of vesting period of Team members or Advisors
* @dev An automatic override allowance is granted during the claim process
* @param account Address that should have it's distribution removed
* @return Whether or not it succeeded
*/
function cancelDeliveredTokens(address account) external onlyOwner returns (bool) {
uint256 loosingAmount = token.cancelVestedTokens(account);
// emit cancel event
emit Cancel(account, loosingAmount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Recover tokens in Time Lock Registry smartcontract address by the owner
*
* @notice Send tokens from smartcontract address to the owner.
* It might only apply after a cancellation of vested tokens
* @param amount Amount to be recovered by the owner of the Time Lock Registry smartcontract from its balance
* @return Whether or not it succeeded
*/
function transferToOwner(uint256 amount) external onlyOwner returns (bool) {
SafeERC20.safeTransfer(token, msg.sender, amount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Claim locked tokens by the registered account
*
* @notice Claim tokens due amount.
* @dev Claim is done by the user in the TimeLocked contract and the contract is the only allowed to call
* this function on behalf of the user to make the claim
* @return The amount of tokens registered and delivered after the claim
*/
function claim(address _receiver) external onlyBABLToken returns (uint256) {
require(registeredDistributions[_receiver] != 0, 'Not registered');
// get amount from distributions
uint256 amount = registeredDistributions[_receiver];
TokenVested storage claimTokenVested = tokenVested[_receiver];
claimTokenVested.lastClaim = block.timestamp;
// set distribution mapping to 0
delete registeredDistributions[_receiver];
// decrease total tokens
totalTokens = totalTokens.sub(amount);
// register lockup in TimeLockedToken
// this will transfer funds from this contract and lock them for sender
token.registerLockup(
_receiver,
amount,
claimTokenVested.team,
claimTokenVested.vestingBegin,
claimTokenVested.vestingEnd,
claimTokenVested.lastClaim
);
// set tokenVested mapping to 0
delete tokenVested[_receiver];
// emit claim event
emit Claim(_receiver, amount);
return amount;
}
/* ============ Getter Functions ============ */
function checkVesting(address address_)
external
view
returns (
bool team,
uint256 start,
uint256 end,
uint256 last
)
{
TokenVested storage checkTokenVested = tokenVested[address_];
return (
checkTokenVested.team,
checkTokenVested.vestingBegin,
checkTokenVested.vestingEnd,
checkTokenVested.lastClaim
);
}
function checkRegisteredDistribution(address address_) external view returns (uint256 amount) {
return registeredDistributions[address_];
}
} | /**
* @title TimeLockRegistry
* @notice Register Lockups for TimeLocked ERC20 Token BABL (e.g. vesting)
* @author Babylon Finance
* @dev This contract allows owner to register distributions for a TimeLockedToken
*
* To register a distribution, register method should be called by the owner.
* claim() should be called only by the BABL Token smartcontract (modifier onlyBABLToken)
* when any account registered to receive tokens make its own claim
* If case of a mistake, owner can cancel registration before the claim is done by the account
*
* Note this contract address must be setup in the TimeLockedToken's contract pointing
* to interact with (e.g. setTimeLockRegistry() function)
*/ | NatSpecMultiLine | cancelRegistration | function cancelRegistration(address receiver) external onlyOwner returns (bool) {
require(registeredDistributions[receiver] != 0, 'Not registered');
// get amount from distributions
uint256 amount = registeredDistributions[receiver];
// set distribution mapping to 0
delete registeredDistributions[receiver];
// set tokenVested mapping to 0
delete tokenVested[receiver];
// remove from the list of all registrations
registrations.remove(receiver);
// decrease total tokens
totalTokens = totalTokens.sub(amount);
// emit cancel event
emit Cancel(receiver, amount);
return true;
}
| /**
* PRIVILEGED GOVERNANCE FUNCTION. Cancel distribution registration in case of mistake and before a claim is done
*
* @notice Cancel distribution registration
* @dev A claim has not to be done earlier
* @param receiver Address that should have it's distribution removed
* @return Whether or not it succeeded
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | {
"func_code_index": [
6216,
6921
]
} | 3,686 |
||
TimeLockRegistry | contracts/token/TimeLockRegistry.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | TimeLockRegistry | contract TimeLockRegistry is Ownable {
using LowGasSafeMath for uint256;
using Address for address;
using AddressArrayUtils for address[];
/* ============ Events ============ */
event Register(address receiver, uint256 distribution);
event Cancel(address receiver, uint256 distribution);
event Claim(address account, uint256 distribution);
/* ============ Modifiers ============ */
modifier onlyBABLToken() {
require(msg.sender == address(token), 'only BABL Token');
_;
}
/* ============ State Variables ============ */
// time locked token
TimeLockedToken public token;
/**
* @notice The profile of each token owner under vesting conditions and its special conditions
* @param receiver Account being registered
* @param investorType Indicates whether or not is a Team member (true = team member / advisor, false = private investor)
* @param vestingStarting Date When the vesting begins for such token owner
* @param distribution Tokens amount that receiver is due to get
*/
struct Registration {
address receiver;
uint256 distribution;
bool investorType;
uint256 vestingStartingDate;
}
/**
* @notice The profile of each token owner under vesting conditions and its special conditions
* @param team Indicates whether or not is a Team member (true = team member / advisor, false = private investor)
* @param vestingBegin When the vesting begins for such token owner
* @param vestingEnd When the vesting ends for such token owner
* @param lastClaim When the last claim was done
*/
struct TokenVested {
bool team;
bool cliff;
uint256 vestingBegin;
uint256 vestingEnd;
uint256 lastClaim;
}
/// @notice A record of token owners under vesting conditions for each account, by index
mapping(address => TokenVested) public tokenVested;
// mapping from token owners under vesting conditions to BABL due amount (e.g. SAFT addresses, team members, advisors)
mapping(address => uint256) public registeredDistributions;
// array of all registrations
address[] public registrations;
// total amount of tokens registered
uint256 public totalTokens;
// vesting for Team Members
uint256 private constant teamVesting = 365 days * 4;
// vesting for Investors and Advisors
uint256 private constant investorVesting = 365 days * 3;
/* ============ Functions ============ */
/* ============ Constructor ============ */
/**
* @notice Construct a new Time Lock Registry and gives ownership to sender
* @param _token TimeLockedToken contract to use in this registry
*/
constructor(TimeLockedToken _token) {
token = _token;
}
/* ============ External Functions ============ */
/* ============ External Getter Functions ============ */
/**
* Gets registrations
*
* @return address[] Returns list of registrations
*/
function getRegistrations() external view returns (address[] memory) {
return registrations;
}
/* =========== Token related Gov Functions ====== */
/**
* PRIVILEGED GOVERNANCE FUNCTION
*
* @notice Register multiple investors/team in a batch
* @param _registrations Registrations to process
*/
function registerBatch(Registration[] memory _registrations) external onlyOwner {
for (uint256 i = 0; i < _registrations.length; i++) {
register(
_registrations[i].receiver,
_registrations[i].distribution,
_registrations[i].investorType,
_registrations[i].vestingStartingDate
);
}
}
/**
* PRIVILEGED GOVERNANCE FUNCTION
*
* @notice Register new account under vesting conditions (Team, Advisors, Investors e.g. SAFT purchaser)
* @param receiver Address belonging vesting conditions
* @param distribution Tokens amount that receiver is due to get
*/
function register(
address receiver,
uint256 distribution,
bool investorType,
uint256 vestingStartingDate
) public onlyOwner {
require(receiver != address(0), 'TimeLockRegistry::register: cannot register the zero address');
require(
receiver != address(this),
'TimeLockRegistry::register: Time Lock Registry contract cannot be an investor'
);
require(distribution != 0, 'TimeLockRegistry::register: Distribution = 0');
require(
registeredDistributions[receiver] == 0,
'TimeLockRegistry::register:Distribution for this address is already registered'
);
require(block.timestamp >= 1614553200, 'Cannot register earlier than March 2021'); // 1614553200 is UNIX TIME of 2021 March the 1st
require(totalTokens.add(distribution) <= IERC20(token).balanceOf(address(this)), 'Not enough tokens');
totalTokens = totalTokens.add(distribution);
// register distribution
registeredDistributions[receiver] = distribution;
registrations.push(receiver);
// register token vested conditions
TokenVested storage newTokenVested = tokenVested[receiver];
newTokenVested.team = investorType;
newTokenVested.vestingBegin = vestingStartingDate;
if (newTokenVested.team == true) {
newTokenVested.vestingEnd = vestingStartingDate.add(teamVesting);
} else {
newTokenVested.vestingEnd = vestingStartingDate.add(investorVesting);
}
newTokenVested.lastClaim = vestingStartingDate;
tokenVested[receiver] = newTokenVested;
// emit register event
emit Register(receiver, distribution);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Cancel distribution registration in case of mistake and before a claim is done
*
* @notice Cancel distribution registration
* @dev A claim has not to be done earlier
* @param receiver Address that should have it's distribution removed
* @return Whether or not it succeeded
*/
function cancelRegistration(address receiver) external onlyOwner returns (bool) {
require(registeredDistributions[receiver] != 0, 'Not registered');
// get amount from distributions
uint256 amount = registeredDistributions[receiver];
// set distribution mapping to 0
delete registeredDistributions[receiver];
// set tokenVested mapping to 0
delete tokenVested[receiver];
// remove from the list of all registrations
registrations.remove(receiver);
// decrease total tokens
totalTokens = totalTokens.sub(amount);
// emit cancel event
emit Cancel(receiver, amount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Cancel distribution registration in case of mistake and before a claim is done
*
* @notice Cancel already delivered tokens. It might only apply when non-completion of vesting period of Team members or Advisors
* @dev An automatic override allowance is granted during the claim process
* @param account Address that should have it's distribution removed
* @return Whether or not it succeeded
*/
function cancelDeliveredTokens(address account) external onlyOwner returns (bool) {
uint256 loosingAmount = token.cancelVestedTokens(account);
// emit cancel event
emit Cancel(account, loosingAmount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Recover tokens in Time Lock Registry smartcontract address by the owner
*
* @notice Send tokens from smartcontract address to the owner.
* It might only apply after a cancellation of vested tokens
* @param amount Amount to be recovered by the owner of the Time Lock Registry smartcontract from its balance
* @return Whether or not it succeeded
*/
function transferToOwner(uint256 amount) external onlyOwner returns (bool) {
SafeERC20.safeTransfer(token, msg.sender, amount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Claim locked tokens by the registered account
*
* @notice Claim tokens due amount.
* @dev Claim is done by the user in the TimeLocked contract and the contract is the only allowed to call
* this function on behalf of the user to make the claim
* @return The amount of tokens registered and delivered after the claim
*/
function claim(address _receiver) external onlyBABLToken returns (uint256) {
require(registeredDistributions[_receiver] != 0, 'Not registered');
// get amount from distributions
uint256 amount = registeredDistributions[_receiver];
TokenVested storage claimTokenVested = tokenVested[_receiver];
claimTokenVested.lastClaim = block.timestamp;
// set distribution mapping to 0
delete registeredDistributions[_receiver];
// decrease total tokens
totalTokens = totalTokens.sub(amount);
// register lockup in TimeLockedToken
// this will transfer funds from this contract and lock them for sender
token.registerLockup(
_receiver,
amount,
claimTokenVested.team,
claimTokenVested.vestingBegin,
claimTokenVested.vestingEnd,
claimTokenVested.lastClaim
);
// set tokenVested mapping to 0
delete tokenVested[_receiver];
// emit claim event
emit Claim(_receiver, amount);
return amount;
}
/* ============ Getter Functions ============ */
function checkVesting(address address_)
external
view
returns (
bool team,
uint256 start,
uint256 end,
uint256 last
)
{
TokenVested storage checkTokenVested = tokenVested[address_];
return (
checkTokenVested.team,
checkTokenVested.vestingBegin,
checkTokenVested.vestingEnd,
checkTokenVested.lastClaim
);
}
function checkRegisteredDistribution(address address_) external view returns (uint256 amount) {
return registeredDistributions[address_];
}
} | /**
* @title TimeLockRegistry
* @notice Register Lockups for TimeLocked ERC20 Token BABL (e.g. vesting)
* @author Babylon Finance
* @dev This contract allows owner to register distributions for a TimeLockedToken
*
* To register a distribution, register method should be called by the owner.
* claim() should be called only by the BABL Token smartcontract (modifier onlyBABLToken)
* when any account registered to receive tokens make its own claim
* If case of a mistake, owner can cancel registration before the claim is done by the account
*
* Note this contract address must be setup in the TimeLockedToken's contract pointing
* to interact with (e.g. setTimeLockRegistry() function)
*/ | NatSpecMultiLine | cancelDeliveredTokens | function cancelDeliveredTokens(address account) external onlyOwner returns (bool) {
uint256 loosingAmount = token.cancelVestedTokens(account);
// emit cancel event
emit Cancel(account, loosingAmount);
return true;
}
| /**
* PRIVILEGED GOVERNANCE FUNCTION. Cancel distribution registration in case of mistake and before a claim is done
*
* @notice Cancel already delivered tokens. It might only apply when non-completion of vesting period of Team members or Advisors
* @dev An automatic override allowance is granted during the claim process
* @param account Address that should have it's distribution removed
* @return Whether or not it succeeded
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | {
"func_code_index": [
7394,
7650
]
} | 3,687 |
||
TimeLockRegistry | contracts/token/TimeLockRegistry.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | TimeLockRegistry | contract TimeLockRegistry is Ownable {
using LowGasSafeMath for uint256;
using Address for address;
using AddressArrayUtils for address[];
/* ============ Events ============ */
event Register(address receiver, uint256 distribution);
event Cancel(address receiver, uint256 distribution);
event Claim(address account, uint256 distribution);
/* ============ Modifiers ============ */
modifier onlyBABLToken() {
require(msg.sender == address(token), 'only BABL Token');
_;
}
/* ============ State Variables ============ */
// time locked token
TimeLockedToken public token;
/**
* @notice The profile of each token owner under vesting conditions and its special conditions
* @param receiver Account being registered
* @param investorType Indicates whether or not is a Team member (true = team member / advisor, false = private investor)
* @param vestingStarting Date When the vesting begins for such token owner
* @param distribution Tokens amount that receiver is due to get
*/
struct Registration {
address receiver;
uint256 distribution;
bool investorType;
uint256 vestingStartingDate;
}
/**
* @notice The profile of each token owner under vesting conditions and its special conditions
* @param team Indicates whether or not is a Team member (true = team member / advisor, false = private investor)
* @param vestingBegin When the vesting begins for such token owner
* @param vestingEnd When the vesting ends for such token owner
* @param lastClaim When the last claim was done
*/
struct TokenVested {
bool team;
bool cliff;
uint256 vestingBegin;
uint256 vestingEnd;
uint256 lastClaim;
}
/// @notice A record of token owners under vesting conditions for each account, by index
mapping(address => TokenVested) public tokenVested;
// mapping from token owners under vesting conditions to BABL due amount (e.g. SAFT addresses, team members, advisors)
mapping(address => uint256) public registeredDistributions;
// array of all registrations
address[] public registrations;
// total amount of tokens registered
uint256 public totalTokens;
// vesting for Team Members
uint256 private constant teamVesting = 365 days * 4;
// vesting for Investors and Advisors
uint256 private constant investorVesting = 365 days * 3;
/* ============ Functions ============ */
/* ============ Constructor ============ */
/**
* @notice Construct a new Time Lock Registry and gives ownership to sender
* @param _token TimeLockedToken contract to use in this registry
*/
constructor(TimeLockedToken _token) {
token = _token;
}
/* ============ External Functions ============ */
/* ============ External Getter Functions ============ */
/**
* Gets registrations
*
* @return address[] Returns list of registrations
*/
function getRegistrations() external view returns (address[] memory) {
return registrations;
}
/* =========== Token related Gov Functions ====== */
/**
* PRIVILEGED GOVERNANCE FUNCTION
*
* @notice Register multiple investors/team in a batch
* @param _registrations Registrations to process
*/
function registerBatch(Registration[] memory _registrations) external onlyOwner {
for (uint256 i = 0; i < _registrations.length; i++) {
register(
_registrations[i].receiver,
_registrations[i].distribution,
_registrations[i].investorType,
_registrations[i].vestingStartingDate
);
}
}
/**
* PRIVILEGED GOVERNANCE FUNCTION
*
* @notice Register new account under vesting conditions (Team, Advisors, Investors e.g. SAFT purchaser)
* @param receiver Address belonging vesting conditions
* @param distribution Tokens amount that receiver is due to get
*/
function register(
address receiver,
uint256 distribution,
bool investorType,
uint256 vestingStartingDate
) public onlyOwner {
require(receiver != address(0), 'TimeLockRegistry::register: cannot register the zero address');
require(
receiver != address(this),
'TimeLockRegistry::register: Time Lock Registry contract cannot be an investor'
);
require(distribution != 0, 'TimeLockRegistry::register: Distribution = 0');
require(
registeredDistributions[receiver] == 0,
'TimeLockRegistry::register:Distribution for this address is already registered'
);
require(block.timestamp >= 1614553200, 'Cannot register earlier than March 2021'); // 1614553200 is UNIX TIME of 2021 March the 1st
require(totalTokens.add(distribution) <= IERC20(token).balanceOf(address(this)), 'Not enough tokens');
totalTokens = totalTokens.add(distribution);
// register distribution
registeredDistributions[receiver] = distribution;
registrations.push(receiver);
// register token vested conditions
TokenVested storage newTokenVested = tokenVested[receiver];
newTokenVested.team = investorType;
newTokenVested.vestingBegin = vestingStartingDate;
if (newTokenVested.team == true) {
newTokenVested.vestingEnd = vestingStartingDate.add(teamVesting);
} else {
newTokenVested.vestingEnd = vestingStartingDate.add(investorVesting);
}
newTokenVested.lastClaim = vestingStartingDate;
tokenVested[receiver] = newTokenVested;
// emit register event
emit Register(receiver, distribution);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Cancel distribution registration in case of mistake and before a claim is done
*
* @notice Cancel distribution registration
* @dev A claim has not to be done earlier
* @param receiver Address that should have it's distribution removed
* @return Whether or not it succeeded
*/
function cancelRegistration(address receiver) external onlyOwner returns (bool) {
require(registeredDistributions[receiver] != 0, 'Not registered');
// get amount from distributions
uint256 amount = registeredDistributions[receiver];
// set distribution mapping to 0
delete registeredDistributions[receiver];
// set tokenVested mapping to 0
delete tokenVested[receiver];
// remove from the list of all registrations
registrations.remove(receiver);
// decrease total tokens
totalTokens = totalTokens.sub(amount);
// emit cancel event
emit Cancel(receiver, amount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Cancel distribution registration in case of mistake and before a claim is done
*
* @notice Cancel already delivered tokens. It might only apply when non-completion of vesting period of Team members or Advisors
* @dev An automatic override allowance is granted during the claim process
* @param account Address that should have it's distribution removed
* @return Whether or not it succeeded
*/
function cancelDeliveredTokens(address account) external onlyOwner returns (bool) {
uint256 loosingAmount = token.cancelVestedTokens(account);
// emit cancel event
emit Cancel(account, loosingAmount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Recover tokens in Time Lock Registry smartcontract address by the owner
*
* @notice Send tokens from smartcontract address to the owner.
* It might only apply after a cancellation of vested tokens
* @param amount Amount to be recovered by the owner of the Time Lock Registry smartcontract from its balance
* @return Whether or not it succeeded
*/
function transferToOwner(uint256 amount) external onlyOwner returns (bool) {
SafeERC20.safeTransfer(token, msg.sender, amount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Claim locked tokens by the registered account
*
* @notice Claim tokens due amount.
* @dev Claim is done by the user in the TimeLocked contract and the contract is the only allowed to call
* this function on behalf of the user to make the claim
* @return The amount of tokens registered and delivered after the claim
*/
function claim(address _receiver) external onlyBABLToken returns (uint256) {
require(registeredDistributions[_receiver] != 0, 'Not registered');
// get amount from distributions
uint256 amount = registeredDistributions[_receiver];
TokenVested storage claimTokenVested = tokenVested[_receiver];
claimTokenVested.lastClaim = block.timestamp;
// set distribution mapping to 0
delete registeredDistributions[_receiver];
// decrease total tokens
totalTokens = totalTokens.sub(amount);
// register lockup in TimeLockedToken
// this will transfer funds from this contract and lock them for sender
token.registerLockup(
_receiver,
amount,
claimTokenVested.team,
claimTokenVested.vestingBegin,
claimTokenVested.vestingEnd,
claimTokenVested.lastClaim
);
// set tokenVested mapping to 0
delete tokenVested[_receiver];
// emit claim event
emit Claim(_receiver, amount);
return amount;
}
/* ============ Getter Functions ============ */
function checkVesting(address address_)
external
view
returns (
bool team,
uint256 start,
uint256 end,
uint256 last
)
{
TokenVested storage checkTokenVested = tokenVested[address_];
return (
checkTokenVested.team,
checkTokenVested.vestingBegin,
checkTokenVested.vestingEnd,
checkTokenVested.lastClaim
);
}
function checkRegisteredDistribution(address address_) external view returns (uint256 amount) {
return registeredDistributions[address_];
}
} | /**
* @title TimeLockRegistry
* @notice Register Lockups for TimeLocked ERC20 Token BABL (e.g. vesting)
* @author Babylon Finance
* @dev This contract allows owner to register distributions for a TimeLockedToken
*
* To register a distribution, register method should be called by the owner.
* claim() should be called only by the BABL Token smartcontract (modifier onlyBABLToken)
* when any account registered to receive tokens make its own claim
* If case of a mistake, owner can cancel registration before the claim is done by the account
*
* Note this contract address must be setup in the TimeLockedToken's contract pointing
* to interact with (e.g. setTimeLockRegistry() function)
*/ | NatSpecMultiLine | transferToOwner | function transferToOwner(uint256 amount) external onlyOwner returns (bool) {
SafeERC20.safeTransfer(token, msg.sender, amount);
return true;
}
| /**
* PRIVILEGED GOVERNANCE FUNCTION. Recover tokens in Time Lock Registry smartcontract address by the owner
*
* @notice Send tokens from smartcontract address to the owner.
* It might only apply after a cancellation of vested tokens
* @param amount Amount to be recovered by the owner of the Time Lock Registry smartcontract from its balance
* @return Whether or not it succeeded
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | {
"func_code_index": [
8076,
8242
]
} | 3,688 |
||
TimeLockRegistry | contracts/token/TimeLockRegistry.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | TimeLockRegistry | contract TimeLockRegistry is Ownable {
using LowGasSafeMath for uint256;
using Address for address;
using AddressArrayUtils for address[];
/* ============ Events ============ */
event Register(address receiver, uint256 distribution);
event Cancel(address receiver, uint256 distribution);
event Claim(address account, uint256 distribution);
/* ============ Modifiers ============ */
modifier onlyBABLToken() {
require(msg.sender == address(token), 'only BABL Token');
_;
}
/* ============ State Variables ============ */
// time locked token
TimeLockedToken public token;
/**
* @notice The profile of each token owner under vesting conditions and its special conditions
* @param receiver Account being registered
* @param investorType Indicates whether or not is a Team member (true = team member / advisor, false = private investor)
* @param vestingStarting Date When the vesting begins for such token owner
* @param distribution Tokens amount that receiver is due to get
*/
struct Registration {
address receiver;
uint256 distribution;
bool investorType;
uint256 vestingStartingDate;
}
/**
* @notice The profile of each token owner under vesting conditions and its special conditions
* @param team Indicates whether or not is a Team member (true = team member / advisor, false = private investor)
* @param vestingBegin When the vesting begins for such token owner
* @param vestingEnd When the vesting ends for such token owner
* @param lastClaim When the last claim was done
*/
struct TokenVested {
bool team;
bool cliff;
uint256 vestingBegin;
uint256 vestingEnd;
uint256 lastClaim;
}
/// @notice A record of token owners under vesting conditions for each account, by index
mapping(address => TokenVested) public tokenVested;
// mapping from token owners under vesting conditions to BABL due amount (e.g. SAFT addresses, team members, advisors)
mapping(address => uint256) public registeredDistributions;
// array of all registrations
address[] public registrations;
// total amount of tokens registered
uint256 public totalTokens;
// vesting for Team Members
uint256 private constant teamVesting = 365 days * 4;
// vesting for Investors and Advisors
uint256 private constant investorVesting = 365 days * 3;
/* ============ Functions ============ */
/* ============ Constructor ============ */
/**
* @notice Construct a new Time Lock Registry and gives ownership to sender
* @param _token TimeLockedToken contract to use in this registry
*/
constructor(TimeLockedToken _token) {
token = _token;
}
/* ============ External Functions ============ */
/* ============ External Getter Functions ============ */
/**
* Gets registrations
*
* @return address[] Returns list of registrations
*/
function getRegistrations() external view returns (address[] memory) {
return registrations;
}
/* =========== Token related Gov Functions ====== */
/**
* PRIVILEGED GOVERNANCE FUNCTION
*
* @notice Register multiple investors/team in a batch
* @param _registrations Registrations to process
*/
function registerBatch(Registration[] memory _registrations) external onlyOwner {
for (uint256 i = 0; i < _registrations.length; i++) {
register(
_registrations[i].receiver,
_registrations[i].distribution,
_registrations[i].investorType,
_registrations[i].vestingStartingDate
);
}
}
/**
* PRIVILEGED GOVERNANCE FUNCTION
*
* @notice Register new account under vesting conditions (Team, Advisors, Investors e.g. SAFT purchaser)
* @param receiver Address belonging vesting conditions
* @param distribution Tokens amount that receiver is due to get
*/
function register(
address receiver,
uint256 distribution,
bool investorType,
uint256 vestingStartingDate
) public onlyOwner {
require(receiver != address(0), 'TimeLockRegistry::register: cannot register the zero address');
require(
receiver != address(this),
'TimeLockRegistry::register: Time Lock Registry contract cannot be an investor'
);
require(distribution != 0, 'TimeLockRegistry::register: Distribution = 0');
require(
registeredDistributions[receiver] == 0,
'TimeLockRegistry::register:Distribution for this address is already registered'
);
require(block.timestamp >= 1614553200, 'Cannot register earlier than March 2021'); // 1614553200 is UNIX TIME of 2021 March the 1st
require(totalTokens.add(distribution) <= IERC20(token).balanceOf(address(this)), 'Not enough tokens');
totalTokens = totalTokens.add(distribution);
// register distribution
registeredDistributions[receiver] = distribution;
registrations.push(receiver);
// register token vested conditions
TokenVested storage newTokenVested = tokenVested[receiver];
newTokenVested.team = investorType;
newTokenVested.vestingBegin = vestingStartingDate;
if (newTokenVested.team == true) {
newTokenVested.vestingEnd = vestingStartingDate.add(teamVesting);
} else {
newTokenVested.vestingEnd = vestingStartingDate.add(investorVesting);
}
newTokenVested.lastClaim = vestingStartingDate;
tokenVested[receiver] = newTokenVested;
// emit register event
emit Register(receiver, distribution);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Cancel distribution registration in case of mistake and before a claim is done
*
* @notice Cancel distribution registration
* @dev A claim has not to be done earlier
* @param receiver Address that should have it's distribution removed
* @return Whether or not it succeeded
*/
function cancelRegistration(address receiver) external onlyOwner returns (bool) {
require(registeredDistributions[receiver] != 0, 'Not registered');
// get amount from distributions
uint256 amount = registeredDistributions[receiver];
// set distribution mapping to 0
delete registeredDistributions[receiver];
// set tokenVested mapping to 0
delete tokenVested[receiver];
// remove from the list of all registrations
registrations.remove(receiver);
// decrease total tokens
totalTokens = totalTokens.sub(amount);
// emit cancel event
emit Cancel(receiver, amount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Cancel distribution registration in case of mistake and before a claim is done
*
* @notice Cancel already delivered tokens. It might only apply when non-completion of vesting period of Team members or Advisors
* @dev An automatic override allowance is granted during the claim process
* @param account Address that should have it's distribution removed
* @return Whether or not it succeeded
*/
function cancelDeliveredTokens(address account) external onlyOwner returns (bool) {
uint256 loosingAmount = token.cancelVestedTokens(account);
// emit cancel event
emit Cancel(account, loosingAmount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Recover tokens in Time Lock Registry smartcontract address by the owner
*
* @notice Send tokens from smartcontract address to the owner.
* It might only apply after a cancellation of vested tokens
* @param amount Amount to be recovered by the owner of the Time Lock Registry smartcontract from its balance
* @return Whether or not it succeeded
*/
function transferToOwner(uint256 amount) external onlyOwner returns (bool) {
SafeERC20.safeTransfer(token, msg.sender, amount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Claim locked tokens by the registered account
*
* @notice Claim tokens due amount.
* @dev Claim is done by the user in the TimeLocked contract and the contract is the only allowed to call
* this function on behalf of the user to make the claim
* @return The amount of tokens registered and delivered after the claim
*/
function claim(address _receiver) external onlyBABLToken returns (uint256) {
require(registeredDistributions[_receiver] != 0, 'Not registered');
// get amount from distributions
uint256 amount = registeredDistributions[_receiver];
TokenVested storage claimTokenVested = tokenVested[_receiver];
claimTokenVested.lastClaim = block.timestamp;
// set distribution mapping to 0
delete registeredDistributions[_receiver];
// decrease total tokens
totalTokens = totalTokens.sub(amount);
// register lockup in TimeLockedToken
// this will transfer funds from this contract and lock them for sender
token.registerLockup(
_receiver,
amount,
claimTokenVested.team,
claimTokenVested.vestingBegin,
claimTokenVested.vestingEnd,
claimTokenVested.lastClaim
);
// set tokenVested mapping to 0
delete tokenVested[_receiver];
// emit claim event
emit Claim(_receiver, amount);
return amount;
}
/* ============ Getter Functions ============ */
function checkVesting(address address_)
external
view
returns (
bool team,
uint256 start,
uint256 end,
uint256 last
)
{
TokenVested storage checkTokenVested = tokenVested[address_];
return (
checkTokenVested.team,
checkTokenVested.vestingBegin,
checkTokenVested.vestingEnd,
checkTokenVested.lastClaim
);
}
function checkRegisteredDistribution(address address_) external view returns (uint256 amount) {
return registeredDistributions[address_];
}
} | /**
* @title TimeLockRegistry
* @notice Register Lockups for TimeLocked ERC20 Token BABL (e.g. vesting)
* @author Babylon Finance
* @dev This contract allows owner to register distributions for a TimeLockedToken
*
* To register a distribution, register method should be called by the owner.
* claim() should be called only by the BABL Token smartcontract (modifier onlyBABLToken)
* when any account registered to receive tokens make its own claim
* If case of a mistake, owner can cancel registration before the claim is done by the account
*
* Note this contract address must be setup in the TimeLockedToken's contract pointing
* to interact with (e.g. setTimeLockRegistry() function)
*/ | NatSpecMultiLine | claim | function claim(address _receiver) external onlyBABLToken returns (uint256) {
require(registeredDistributions[_receiver] != 0, 'Not registered');
// get amount from distributions
uint256 amount = registeredDistributions[_receiver];
TokenVested storage claimTokenVested = tokenVested[_receiver];
claimTokenVested.lastClaim = block.timestamp;
// set distribution mapping to 0
delete registeredDistributions[_receiver];
// decrease total tokens
totalTokens = totalTokens.sub(amount);
// register lockup in TimeLockedToken
// this will transfer funds from this contract and lock them for sender
token.registerLockup(
_receiver,
amount,
claimTokenVested.team,
claimTokenVested.vestingBegin,
claimTokenVested.vestingEnd,
claimTokenVested.lastClaim
);
// set tokenVested mapping to 0
delete tokenVested[_receiver];
// emit claim event
emit Claim(_receiver, amount);
return amount;
}
| /**
* PRIVILEGED GOVERNANCE FUNCTION. Claim locked tokens by the registered account
*
* @notice Claim tokens due amount.
* @dev Claim is done by the user in the TimeLocked contract and the contract is the only allowed to call
* this function on behalf of the user to make the claim
* @return The amount of tokens registered and delivered after the claim
*/ | NatSpecMultiLine | v0.7.6+commit.7338295f | {
"func_code_index": [
8640,
9746
]
} | 3,689 |
||
TimeLockRegistry | contracts/token/TimeLockRegistry.sol | 0xae171d3e9f8e755bb8547d4165fd79b148be45de | Solidity | TimeLockRegistry | contract TimeLockRegistry is Ownable {
using LowGasSafeMath for uint256;
using Address for address;
using AddressArrayUtils for address[];
/* ============ Events ============ */
event Register(address receiver, uint256 distribution);
event Cancel(address receiver, uint256 distribution);
event Claim(address account, uint256 distribution);
/* ============ Modifiers ============ */
modifier onlyBABLToken() {
require(msg.sender == address(token), 'only BABL Token');
_;
}
/* ============ State Variables ============ */
// time locked token
TimeLockedToken public token;
/**
* @notice The profile of each token owner under vesting conditions and its special conditions
* @param receiver Account being registered
* @param investorType Indicates whether or not is a Team member (true = team member / advisor, false = private investor)
* @param vestingStarting Date When the vesting begins for such token owner
* @param distribution Tokens amount that receiver is due to get
*/
struct Registration {
address receiver;
uint256 distribution;
bool investorType;
uint256 vestingStartingDate;
}
/**
* @notice The profile of each token owner under vesting conditions and its special conditions
* @param team Indicates whether or not is a Team member (true = team member / advisor, false = private investor)
* @param vestingBegin When the vesting begins for such token owner
* @param vestingEnd When the vesting ends for such token owner
* @param lastClaim When the last claim was done
*/
struct TokenVested {
bool team;
bool cliff;
uint256 vestingBegin;
uint256 vestingEnd;
uint256 lastClaim;
}
/// @notice A record of token owners under vesting conditions for each account, by index
mapping(address => TokenVested) public tokenVested;
// mapping from token owners under vesting conditions to BABL due amount (e.g. SAFT addresses, team members, advisors)
mapping(address => uint256) public registeredDistributions;
// array of all registrations
address[] public registrations;
// total amount of tokens registered
uint256 public totalTokens;
// vesting for Team Members
uint256 private constant teamVesting = 365 days * 4;
// vesting for Investors and Advisors
uint256 private constant investorVesting = 365 days * 3;
/* ============ Functions ============ */
/* ============ Constructor ============ */
/**
* @notice Construct a new Time Lock Registry and gives ownership to sender
* @param _token TimeLockedToken contract to use in this registry
*/
constructor(TimeLockedToken _token) {
token = _token;
}
/* ============ External Functions ============ */
/* ============ External Getter Functions ============ */
/**
* Gets registrations
*
* @return address[] Returns list of registrations
*/
function getRegistrations() external view returns (address[] memory) {
return registrations;
}
/* =========== Token related Gov Functions ====== */
/**
* PRIVILEGED GOVERNANCE FUNCTION
*
* @notice Register multiple investors/team in a batch
* @param _registrations Registrations to process
*/
function registerBatch(Registration[] memory _registrations) external onlyOwner {
for (uint256 i = 0; i < _registrations.length; i++) {
register(
_registrations[i].receiver,
_registrations[i].distribution,
_registrations[i].investorType,
_registrations[i].vestingStartingDate
);
}
}
/**
* PRIVILEGED GOVERNANCE FUNCTION
*
* @notice Register new account under vesting conditions (Team, Advisors, Investors e.g. SAFT purchaser)
* @param receiver Address belonging vesting conditions
* @param distribution Tokens amount that receiver is due to get
*/
function register(
address receiver,
uint256 distribution,
bool investorType,
uint256 vestingStartingDate
) public onlyOwner {
require(receiver != address(0), 'TimeLockRegistry::register: cannot register the zero address');
require(
receiver != address(this),
'TimeLockRegistry::register: Time Lock Registry contract cannot be an investor'
);
require(distribution != 0, 'TimeLockRegistry::register: Distribution = 0');
require(
registeredDistributions[receiver] == 0,
'TimeLockRegistry::register:Distribution for this address is already registered'
);
require(block.timestamp >= 1614553200, 'Cannot register earlier than March 2021'); // 1614553200 is UNIX TIME of 2021 March the 1st
require(totalTokens.add(distribution) <= IERC20(token).balanceOf(address(this)), 'Not enough tokens');
totalTokens = totalTokens.add(distribution);
// register distribution
registeredDistributions[receiver] = distribution;
registrations.push(receiver);
// register token vested conditions
TokenVested storage newTokenVested = tokenVested[receiver];
newTokenVested.team = investorType;
newTokenVested.vestingBegin = vestingStartingDate;
if (newTokenVested.team == true) {
newTokenVested.vestingEnd = vestingStartingDate.add(teamVesting);
} else {
newTokenVested.vestingEnd = vestingStartingDate.add(investorVesting);
}
newTokenVested.lastClaim = vestingStartingDate;
tokenVested[receiver] = newTokenVested;
// emit register event
emit Register(receiver, distribution);
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Cancel distribution registration in case of mistake and before a claim is done
*
* @notice Cancel distribution registration
* @dev A claim has not to be done earlier
* @param receiver Address that should have it's distribution removed
* @return Whether or not it succeeded
*/
function cancelRegistration(address receiver) external onlyOwner returns (bool) {
require(registeredDistributions[receiver] != 0, 'Not registered');
// get amount from distributions
uint256 amount = registeredDistributions[receiver];
// set distribution mapping to 0
delete registeredDistributions[receiver];
// set tokenVested mapping to 0
delete tokenVested[receiver];
// remove from the list of all registrations
registrations.remove(receiver);
// decrease total tokens
totalTokens = totalTokens.sub(amount);
// emit cancel event
emit Cancel(receiver, amount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Cancel distribution registration in case of mistake and before a claim is done
*
* @notice Cancel already delivered tokens. It might only apply when non-completion of vesting period of Team members or Advisors
* @dev An automatic override allowance is granted during the claim process
* @param account Address that should have it's distribution removed
* @return Whether or not it succeeded
*/
function cancelDeliveredTokens(address account) external onlyOwner returns (bool) {
uint256 loosingAmount = token.cancelVestedTokens(account);
// emit cancel event
emit Cancel(account, loosingAmount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Recover tokens in Time Lock Registry smartcontract address by the owner
*
* @notice Send tokens from smartcontract address to the owner.
* It might only apply after a cancellation of vested tokens
* @param amount Amount to be recovered by the owner of the Time Lock Registry smartcontract from its balance
* @return Whether or not it succeeded
*/
function transferToOwner(uint256 amount) external onlyOwner returns (bool) {
SafeERC20.safeTransfer(token, msg.sender, amount);
return true;
}
/**
* PRIVILEGED GOVERNANCE FUNCTION. Claim locked tokens by the registered account
*
* @notice Claim tokens due amount.
* @dev Claim is done by the user in the TimeLocked contract and the contract is the only allowed to call
* this function on behalf of the user to make the claim
* @return The amount of tokens registered and delivered after the claim
*/
function claim(address _receiver) external onlyBABLToken returns (uint256) {
require(registeredDistributions[_receiver] != 0, 'Not registered');
// get amount from distributions
uint256 amount = registeredDistributions[_receiver];
TokenVested storage claimTokenVested = tokenVested[_receiver];
claimTokenVested.lastClaim = block.timestamp;
// set distribution mapping to 0
delete registeredDistributions[_receiver];
// decrease total tokens
totalTokens = totalTokens.sub(amount);
// register lockup in TimeLockedToken
// this will transfer funds from this contract and lock them for sender
token.registerLockup(
_receiver,
amount,
claimTokenVested.team,
claimTokenVested.vestingBegin,
claimTokenVested.vestingEnd,
claimTokenVested.lastClaim
);
// set tokenVested mapping to 0
delete tokenVested[_receiver];
// emit claim event
emit Claim(_receiver, amount);
return amount;
}
/* ============ Getter Functions ============ */
function checkVesting(address address_)
external
view
returns (
bool team,
uint256 start,
uint256 end,
uint256 last
)
{
TokenVested storage checkTokenVested = tokenVested[address_];
return (
checkTokenVested.team,
checkTokenVested.vestingBegin,
checkTokenVested.vestingEnd,
checkTokenVested.lastClaim
);
}
function checkRegisteredDistribution(address address_) external view returns (uint256 amount) {
return registeredDistributions[address_];
}
} | /**
* @title TimeLockRegistry
* @notice Register Lockups for TimeLocked ERC20 Token BABL (e.g. vesting)
* @author Babylon Finance
* @dev This contract allows owner to register distributions for a TimeLockedToken
*
* To register a distribution, register method should be called by the owner.
* claim() should be called only by the BABL Token smartcontract (modifier onlyBABLToken)
* when any account registered to receive tokens make its own claim
* If case of a mistake, owner can cancel registration before the claim is done by the account
*
* Note this contract address must be setup in the TimeLockedToken's contract pointing
* to interact with (e.g. setTimeLockRegistry() function)
*/ | NatSpecMultiLine | checkVesting | function checkVesting(address address_)
external
view
returns (
bool team,
uint256 start,
uint256 end,
uint256 last
)
{
TokenVested storage checkTokenVested = tokenVested[address_];
return (
checkTokenVested.team,
checkTokenVested.vestingBegin,
checkTokenVested.vestingEnd,
checkTokenVested.lastClaim
);
}
| /* ============ Getter Functions ============ */ | Comment | v0.7.6+commit.7338295f | {
"func_code_index": [
9802,
10272
]
} | 3,690 |
||
SakeVoterCalc | contracts/SakeMaster.sol | 0x44d84a9da47fd8f4a06ad66b197d1441fca53f92 | Solidity | SakeMaster | contract SakeMaster 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 SAKEs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSakePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSakePerShare` (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. SAKEs to distribute per block.
uint256 lastRewardBlock; // Last block number that SAKEs distribution occurs.
uint256 accSakePerShare; // Accumulated SAKEs per share, times 1e12. See below.
}
// The SAKE TOKEN!
SakeToken public sake;
// Dev address.
address public devaddr;
// Block number when beta test period ends.
uint256 public betaTestEndBlock;
// Block number when bonus SAKE period ends.
uint256 public bonusEndBlock;
// Block number when mint SAKE period ends.
uint256 public mintEndBlock;
// SAKE tokens created per block.
uint256 public sakePerBlock;
// Bonus muliplier for 5~20 days sake makers.
uint256 public constant BONUSONE_MULTIPLIER = 20;
// Bonus muliplier for 20~35 sake makers.
uint256 public constant BONUSTWO_MULTIPLIER = 2;
// beta test block num,about 5 days.
uint256 public constant BETATEST_BLOCKNUM = 35000;
// Bonus block num,about 15 days.
uint256 public constant BONUS_BLOCKNUM = 100000;
// mint end block num,about 30 days.
uint256 public constant MINTEND_BLOCKNUM = 200000;
// 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;
// Record whether the pair has been added.
mapping(address => uint256) public lpTokenPID;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SAKE 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(
SakeToken _sake,
address _devaddr,
uint256 _sakePerBlock,
uint256 _startBlock
) public {
sake = _sake;
devaddr = _devaddr;
sakePerBlock = _sakePerBlock;
startBlock = _startBlock;
betaTestEndBlock = startBlock.add(BETATEST_BLOCKNUM);
bonusEndBlock = startBlock.add(BONUS_BLOCKNUM).add(BETATEST_BLOCKNUM);
mintEndBlock = startBlock.add(MINTEND_BLOCKNUM).add(BETATEST_BLOCKNUM);
}
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();
}
require(lpTokenPID[address(_lpToken)] == 0, "SakeMaster:duplicate add.");
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSakePerShare: 0
})
);
lpTokenPID[address(_lpToken)] = poolInfo.length;
}
// Update the given pool's SAKE 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;
}
// Handover the saketoken mintage right.
function handoverSakeMintage(address newOwner) public onlyOwner {
sake.transferOwnership(newOwner);
}
// 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) {
uint256 _toFinal = _to > mintEndBlock ? mintEndBlock : _to;
if (_toFinal <= betaTestEndBlock) {
return _toFinal.sub(_from);
}else if (_from >= mintEndBlock) {
return 0;
} else if (_toFinal <= bonusEndBlock) {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(_toFinal.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSONE_MULTIPLIER);
}
} else {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(bonusEndBlock.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER)).add(
(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER)));
} else if (betaTestEndBlock <= _from && _from < bonusEndBlock) {
return bonusEndBlock.sub(_from).mul(BONUSONE_MULTIPLIER).add(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSTWO_MULTIPLIER);
}
}
}
// View function to see pending SAKEs on frontend.
function pendingSake(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSakePerShare = pool.accSakePerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSakePerShare = accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSakePerShare).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);
if (multiplier == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sake.mint(devaddr, sakeReward.div(15));
sake.mint(address(this), sakeReward);
pool.accSakePerShare = pool.accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to SakeMaster for SAKE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
if (pending > 0) safeSakeTransfer(msg.sender, pending);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from SakeMaster.
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.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
safeSakeTransfer(msg.sender, pending);
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];
require(user.amount > 0, "emergencyWithdraw: not good");
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Safe sake transfer function, just in case if rounding error causes pool to not have enough SAKEs.
function safeSakeTransfer(address _to, uint256 _amount) internal {
uint256 sakeBal = sake.balanceOf(address(this));
if (_amount > sakeBal) {
sake.transfer(_to, sakeBal);
} else {
sake.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // SakeMaster is the master of Sake. He can make Sake 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 SAKE 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();
}
require(lpTokenPID[address(_lpToken)] == 0, "SakeMaster:duplicate add.");
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSakePerShare: 0
})
);
lpTokenPID[address(_lpToken)] = 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. | LineComment | v0.6.12+commit.27d51765 | None | ipfs://5d4700996a40376e16d7d09f63c9d6b8ef633b28dd8203c5297833f9286dce20 | {
"func_code_index": [
3944,
4647
]
} | 3,691 |
SakeVoterCalc | contracts/SakeMaster.sol | 0x44d84a9da47fd8f4a06ad66b197d1441fca53f92 | Solidity | SakeMaster | contract SakeMaster 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 SAKEs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSakePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSakePerShare` (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. SAKEs to distribute per block.
uint256 lastRewardBlock; // Last block number that SAKEs distribution occurs.
uint256 accSakePerShare; // Accumulated SAKEs per share, times 1e12. See below.
}
// The SAKE TOKEN!
SakeToken public sake;
// Dev address.
address public devaddr;
// Block number when beta test period ends.
uint256 public betaTestEndBlock;
// Block number when bonus SAKE period ends.
uint256 public bonusEndBlock;
// Block number when mint SAKE period ends.
uint256 public mintEndBlock;
// SAKE tokens created per block.
uint256 public sakePerBlock;
// Bonus muliplier for 5~20 days sake makers.
uint256 public constant BONUSONE_MULTIPLIER = 20;
// Bonus muliplier for 20~35 sake makers.
uint256 public constant BONUSTWO_MULTIPLIER = 2;
// beta test block num,about 5 days.
uint256 public constant BETATEST_BLOCKNUM = 35000;
// Bonus block num,about 15 days.
uint256 public constant BONUS_BLOCKNUM = 100000;
// mint end block num,about 30 days.
uint256 public constant MINTEND_BLOCKNUM = 200000;
// 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;
// Record whether the pair has been added.
mapping(address => uint256) public lpTokenPID;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SAKE 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(
SakeToken _sake,
address _devaddr,
uint256 _sakePerBlock,
uint256 _startBlock
) public {
sake = _sake;
devaddr = _devaddr;
sakePerBlock = _sakePerBlock;
startBlock = _startBlock;
betaTestEndBlock = startBlock.add(BETATEST_BLOCKNUM);
bonusEndBlock = startBlock.add(BONUS_BLOCKNUM).add(BETATEST_BLOCKNUM);
mintEndBlock = startBlock.add(MINTEND_BLOCKNUM).add(BETATEST_BLOCKNUM);
}
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();
}
require(lpTokenPID[address(_lpToken)] == 0, "SakeMaster:duplicate add.");
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSakePerShare: 0
})
);
lpTokenPID[address(_lpToken)] = poolInfo.length;
}
// Update the given pool's SAKE 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;
}
// Handover the saketoken mintage right.
function handoverSakeMintage(address newOwner) public onlyOwner {
sake.transferOwnership(newOwner);
}
// 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) {
uint256 _toFinal = _to > mintEndBlock ? mintEndBlock : _to;
if (_toFinal <= betaTestEndBlock) {
return _toFinal.sub(_from);
}else if (_from >= mintEndBlock) {
return 0;
} else if (_toFinal <= bonusEndBlock) {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(_toFinal.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSONE_MULTIPLIER);
}
} else {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(bonusEndBlock.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER)).add(
(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER)));
} else if (betaTestEndBlock <= _from && _from < bonusEndBlock) {
return bonusEndBlock.sub(_from).mul(BONUSONE_MULTIPLIER).add(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSTWO_MULTIPLIER);
}
}
}
// View function to see pending SAKEs on frontend.
function pendingSake(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSakePerShare = pool.accSakePerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSakePerShare = accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSakePerShare).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);
if (multiplier == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sake.mint(devaddr, sakeReward.div(15));
sake.mint(address(this), sakeReward);
pool.accSakePerShare = pool.accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to SakeMaster for SAKE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
if (pending > 0) safeSakeTransfer(msg.sender, pending);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from SakeMaster.
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.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
safeSakeTransfer(msg.sender, pending);
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];
require(user.amount > 0, "emergencyWithdraw: not good");
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Safe sake transfer function, just in case if rounding error causes pool to not have enough SAKEs.
function safeSakeTransfer(address _to, uint256 _amount) internal {
uint256 sakeBal = sake.balanceOf(address(this));
if (_amount > sakeBal) {
sake.transfer(_to, sakeBal);
} else {
sake.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // SakeMaster is the master of Sake. He can make Sake 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 SAKE 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 SAKE allocation point. Can only be called by the owner. | LineComment | v0.6.12+commit.27d51765 | None | ipfs://5d4700996a40376e16d7d09f63c9d6b8ef633b28dd8203c5297833f9286dce20 | {
"func_code_index": [
4738,
5047
]
} | 3,692 |
SakeVoterCalc | contracts/SakeMaster.sol | 0x44d84a9da47fd8f4a06ad66b197d1441fca53f92 | Solidity | SakeMaster | contract SakeMaster 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 SAKEs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSakePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSakePerShare` (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. SAKEs to distribute per block.
uint256 lastRewardBlock; // Last block number that SAKEs distribution occurs.
uint256 accSakePerShare; // Accumulated SAKEs per share, times 1e12. See below.
}
// The SAKE TOKEN!
SakeToken public sake;
// Dev address.
address public devaddr;
// Block number when beta test period ends.
uint256 public betaTestEndBlock;
// Block number when bonus SAKE period ends.
uint256 public bonusEndBlock;
// Block number when mint SAKE period ends.
uint256 public mintEndBlock;
// SAKE tokens created per block.
uint256 public sakePerBlock;
// Bonus muliplier for 5~20 days sake makers.
uint256 public constant BONUSONE_MULTIPLIER = 20;
// Bonus muliplier for 20~35 sake makers.
uint256 public constant BONUSTWO_MULTIPLIER = 2;
// beta test block num,about 5 days.
uint256 public constant BETATEST_BLOCKNUM = 35000;
// Bonus block num,about 15 days.
uint256 public constant BONUS_BLOCKNUM = 100000;
// mint end block num,about 30 days.
uint256 public constant MINTEND_BLOCKNUM = 200000;
// 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;
// Record whether the pair has been added.
mapping(address => uint256) public lpTokenPID;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SAKE 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(
SakeToken _sake,
address _devaddr,
uint256 _sakePerBlock,
uint256 _startBlock
) public {
sake = _sake;
devaddr = _devaddr;
sakePerBlock = _sakePerBlock;
startBlock = _startBlock;
betaTestEndBlock = startBlock.add(BETATEST_BLOCKNUM);
bonusEndBlock = startBlock.add(BONUS_BLOCKNUM).add(BETATEST_BLOCKNUM);
mintEndBlock = startBlock.add(MINTEND_BLOCKNUM).add(BETATEST_BLOCKNUM);
}
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();
}
require(lpTokenPID[address(_lpToken)] == 0, "SakeMaster:duplicate add.");
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSakePerShare: 0
})
);
lpTokenPID[address(_lpToken)] = poolInfo.length;
}
// Update the given pool's SAKE 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;
}
// Handover the saketoken mintage right.
function handoverSakeMintage(address newOwner) public onlyOwner {
sake.transferOwnership(newOwner);
}
// 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) {
uint256 _toFinal = _to > mintEndBlock ? mintEndBlock : _to;
if (_toFinal <= betaTestEndBlock) {
return _toFinal.sub(_from);
}else if (_from >= mintEndBlock) {
return 0;
} else if (_toFinal <= bonusEndBlock) {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(_toFinal.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSONE_MULTIPLIER);
}
} else {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(bonusEndBlock.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER)).add(
(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER)));
} else if (betaTestEndBlock <= _from && _from < bonusEndBlock) {
return bonusEndBlock.sub(_from).mul(BONUSONE_MULTIPLIER).add(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSTWO_MULTIPLIER);
}
}
}
// View function to see pending SAKEs on frontend.
function pendingSake(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSakePerShare = pool.accSakePerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSakePerShare = accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSakePerShare).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);
if (multiplier == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sake.mint(devaddr, sakeReward.div(15));
sake.mint(address(this), sakeReward);
pool.accSakePerShare = pool.accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to SakeMaster for SAKE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
if (pending > 0) safeSakeTransfer(msg.sender, pending);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from SakeMaster.
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.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
safeSakeTransfer(msg.sender, pending);
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];
require(user.amount > 0, "emergencyWithdraw: not good");
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Safe sake transfer function, just in case if rounding error causes pool to not have enough SAKEs.
function safeSakeTransfer(address _to, uint256 _amount) internal {
uint256 sakeBal = sake.balanceOf(address(this));
if (_amount > sakeBal) {
sake.transfer(_to, sakeBal);
} else {
sake.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // SakeMaster is the master of Sake. He can make Sake 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 SAKE 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 | None | ipfs://5d4700996a40376e16d7d09f63c9d6b8ef633b28dd8203c5297833f9286dce20 | {
"func_code_index": [
5118,
5225
]
} | 3,693 |
SakeVoterCalc | contracts/SakeMaster.sol | 0x44d84a9da47fd8f4a06ad66b197d1441fca53f92 | Solidity | SakeMaster | contract SakeMaster 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 SAKEs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSakePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSakePerShare` (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. SAKEs to distribute per block.
uint256 lastRewardBlock; // Last block number that SAKEs distribution occurs.
uint256 accSakePerShare; // Accumulated SAKEs per share, times 1e12. See below.
}
// The SAKE TOKEN!
SakeToken public sake;
// Dev address.
address public devaddr;
// Block number when beta test period ends.
uint256 public betaTestEndBlock;
// Block number when bonus SAKE period ends.
uint256 public bonusEndBlock;
// Block number when mint SAKE period ends.
uint256 public mintEndBlock;
// SAKE tokens created per block.
uint256 public sakePerBlock;
// Bonus muliplier for 5~20 days sake makers.
uint256 public constant BONUSONE_MULTIPLIER = 20;
// Bonus muliplier for 20~35 sake makers.
uint256 public constant BONUSTWO_MULTIPLIER = 2;
// beta test block num,about 5 days.
uint256 public constant BETATEST_BLOCKNUM = 35000;
// Bonus block num,about 15 days.
uint256 public constant BONUS_BLOCKNUM = 100000;
// mint end block num,about 30 days.
uint256 public constant MINTEND_BLOCKNUM = 200000;
// 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;
// Record whether the pair has been added.
mapping(address => uint256) public lpTokenPID;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SAKE 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(
SakeToken _sake,
address _devaddr,
uint256 _sakePerBlock,
uint256 _startBlock
) public {
sake = _sake;
devaddr = _devaddr;
sakePerBlock = _sakePerBlock;
startBlock = _startBlock;
betaTestEndBlock = startBlock.add(BETATEST_BLOCKNUM);
bonusEndBlock = startBlock.add(BONUS_BLOCKNUM).add(BETATEST_BLOCKNUM);
mintEndBlock = startBlock.add(MINTEND_BLOCKNUM).add(BETATEST_BLOCKNUM);
}
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();
}
require(lpTokenPID[address(_lpToken)] == 0, "SakeMaster:duplicate add.");
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSakePerShare: 0
})
);
lpTokenPID[address(_lpToken)] = poolInfo.length;
}
// Update the given pool's SAKE 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;
}
// Handover the saketoken mintage right.
function handoverSakeMintage(address newOwner) public onlyOwner {
sake.transferOwnership(newOwner);
}
// 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) {
uint256 _toFinal = _to > mintEndBlock ? mintEndBlock : _to;
if (_toFinal <= betaTestEndBlock) {
return _toFinal.sub(_from);
}else if (_from >= mintEndBlock) {
return 0;
} else if (_toFinal <= bonusEndBlock) {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(_toFinal.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSONE_MULTIPLIER);
}
} else {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(bonusEndBlock.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER)).add(
(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER)));
} else if (betaTestEndBlock <= _from && _from < bonusEndBlock) {
return bonusEndBlock.sub(_from).mul(BONUSONE_MULTIPLIER).add(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSTWO_MULTIPLIER);
}
}
}
// View function to see pending SAKEs on frontend.
function pendingSake(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSakePerShare = pool.accSakePerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSakePerShare = accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSakePerShare).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);
if (multiplier == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sake.mint(devaddr, sakeReward.div(15));
sake.mint(address(this), sakeReward);
pool.accSakePerShare = pool.accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to SakeMaster for SAKE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
if (pending > 0) safeSakeTransfer(msg.sender, pending);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from SakeMaster.
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.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
safeSakeTransfer(msg.sender, pending);
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];
require(user.amount > 0, "emergencyWithdraw: not good");
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Safe sake transfer function, just in case if rounding error causes pool to not have enough SAKEs.
function safeSakeTransfer(address _to, uint256 _amount) internal {
uint256 sakeBal = sake.balanceOf(address(this));
if (_amount > sakeBal) {
sake.transfer(_to, sakeBal);
} else {
sake.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // SakeMaster is the master of Sake. He can make Sake 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 SAKE is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | handoverSakeMintage | function handoverSakeMintage(address newOwner) public onlyOwner {
sake.transferOwnership(newOwner);
}
| // Handover the saketoken mintage right. | LineComment | v0.6.12+commit.27d51765 | None | ipfs://5d4700996a40376e16d7d09f63c9d6b8ef633b28dd8203c5297833f9286dce20 | {
"func_code_index": [
5274,
5394
]
} | 3,694 |
SakeVoterCalc | contracts/SakeMaster.sol | 0x44d84a9da47fd8f4a06ad66b197d1441fca53f92 | Solidity | SakeMaster | contract SakeMaster 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 SAKEs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSakePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSakePerShare` (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. SAKEs to distribute per block.
uint256 lastRewardBlock; // Last block number that SAKEs distribution occurs.
uint256 accSakePerShare; // Accumulated SAKEs per share, times 1e12. See below.
}
// The SAKE TOKEN!
SakeToken public sake;
// Dev address.
address public devaddr;
// Block number when beta test period ends.
uint256 public betaTestEndBlock;
// Block number when bonus SAKE period ends.
uint256 public bonusEndBlock;
// Block number when mint SAKE period ends.
uint256 public mintEndBlock;
// SAKE tokens created per block.
uint256 public sakePerBlock;
// Bonus muliplier for 5~20 days sake makers.
uint256 public constant BONUSONE_MULTIPLIER = 20;
// Bonus muliplier for 20~35 sake makers.
uint256 public constant BONUSTWO_MULTIPLIER = 2;
// beta test block num,about 5 days.
uint256 public constant BETATEST_BLOCKNUM = 35000;
// Bonus block num,about 15 days.
uint256 public constant BONUS_BLOCKNUM = 100000;
// mint end block num,about 30 days.
uint256 public constant MINTEND_BLOCKNUM = 200000;
// 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;
// Record whether the pair has been added.
mapping(address => uint256) public lpTokenPID;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SAKE 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(
SakeToken _sake,
address _devaddr,
uint256 _sakePerBlock,
uint256 _startBlock
) public {
sake = _sake;
devaddr = _devaddr;
sakePerBlock = _sakePerBlock;
startBlock = _startBlock;
betaTestEndBlock = startBlock.add(BETATEST_BLOCKNUM);
bonusEndBlock = startBlock.add(BONUS_BLOCKNUM).add(BETATEST_BLOCKNUM);
mintEndBlock = startBlock.add(MINTEND_BLOCKNUM).add(BETATEST_BLOCKNUM);
}
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();
}
require(lpTokenPID[address(_lpToken)] == 0, "SakeMaster:duplicate add.");
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSakePerShare: 0
})
);
lpTokenPID[address(_lpToken)] = poolInfo.length;
}
// Update the given pool's SAKE 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;
}
// Handover the saketoken mintage right.
function handoverSakeMintage(address newOwner) public onlyOwner {
sake.transferOwnership(newOwner);
}
// 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) {
uint256 _toFinal = _to > mintEndBlock ? mintEndBlock : _to;
if (_toFinal <= betaTestEndBlock) {
return _toFinal.sub(_from);
}else if (_from >= mintEndBlock) {
return 0;
} else if (_toFinal <= bonusEndBlock) {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(_toFinal.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSONE_MULTIPLIER);
}
} else {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(bonusEndBlock.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER)).add(
(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER)));
} else if (betaTestEndBlock <= _from && _from < bonusEndBlock) {
return bonusEndBlock.sub(_from).mul(BONUSONE_MULTIPLIER).add(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSTWO_MULTIPLIER);
}
}
}
// View function to see pending SAKEs on frontend.
function pendingSake(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSakePerShare = pool.accSakePerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSakePerShare = accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSakePerShare).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);
if (multiplier == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sake.mint(devaddr, sakeReward.div(15));
sake.mint(address(this), sakeReward);
pool.accSakePerShare = pool.accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to SakeMaster for SAKE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
if (pending > 0) safeSakeTransfer(msg.sender, pending);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from SakeMaster.
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.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
safeSakeTransfer(msg.sender, pending);
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];
require(user.amount > 0, "emergencyWithdraw: not good");
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Safe sake transfer function, just in case if rounding error causes pool to not have enough SAKEs.
function safeSakeTransfer(address _to, uint256 _amount) internal {
uint256 sakeBal = sake.balanceOf(address(this));
if (_amount > sakeBal) {
sake.transfer(_to, sakeBal);
} else {
sake.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // SakeMaster is the master of Sake. He can make Sake 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 SAKE 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 | None | ipfs://5d4700996a40376e16d7d09f63c9d6b8ef633b28dd8203c5297833f9286dce20 | {
"func_code_index": [
5512,
6008
]
} | 3,695 |
SakeVoterCalc | contracts/SakeMaster.sol | 0x44d84a9da47fd8f4a06ad66b197d1441fca53f92 | Solidity | SakeMaster | contract SakeMaster 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 SAKEs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSakePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSakePerShare` (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. SAKEs to distribute per block.
uint256 lastRewardBlock; // Last block number that SAKEs distribution occurs.
uint256 accSakePerShare; // Accumulated SAKEs per share, times 1e12. See below.
}
// The SAKE TOKEN!
SakeToken public sake;
// Dev address.
address public devaddr;
// Block number when beta test period ends.
uint256 public betaTestEndBlock;
// Block number when bonus SAKE period ends.
uint256 public bonusEndBlock;
// Block number when mint SAKE period ends.
uint256 public mintEndBlock;
// SAKE tokens created per block.
uint256 public sakePerBlock;
// Bonus muliplier for 5~20 days sake makers.
uint256 public constant BONUSONE_MULTIPLIER = 20;
// Bonus muliplier for 20~35 sake makers.
uint256 public constant BONUSTWO_MULTIPLIER = 2;
// beta test block num,about 5 days.
uint256 public constant BETATEST_BLOCKNUM = 35000;
// Bonus block num,about 15 days.
uint256 public constant BONUS_BLOCKNUM = 100000;
// mint end block num,about 30 days.
uint256 public constant MINTEND_BLOCKNUM = 200000;
// 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;
// Record whether the pair has been added.
mapping(address => uint256) public lpTokenPID;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SAKE 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(
SakeToken _sake,
address _devaddr,
uint256 _sakePerBlock,
uint256 _startBlock
) public {
sake = _sake;
devaddr = _devaddr;
sakePerBlock = _sakePerBlock;
startBlock = _startBlock;
betaTestEndBlock = startBlock.add(BETATEST_BLOCKNUM);
bonusEndBlock = startBlock.add(BONUS_BLOCKNUM).add(BETATEST_BLOCKNUM);
mintEndBlock = startBlock.add(MINTEND_BLOCKNUM).add(BETATEST_BLOCKNUM);
}
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();
}
require(lpTokenPID[address(_lpToken)] == 0, "SakeMaster:duplicate add.");
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSakePerShare: 0
})
);
lpTokenPID[address(_lpToken)] = poolInfo.length;
}
// Update the given pool's SAKE 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;
}
// Handover the saketoken mintage right.
function handoverSakeMintage(address newOwner) public onlyOwner {
sake.transferOwnership(newOwner);
}
// 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) {
uint256 _toFinal = _to > mintEndBlock ? mintEndBlock : _to;
if (_toFinal <= betaTestEndBlock) {
return _toFinal.sub(_from);
}else if (_from >= mintEndBlock) {
return 0;
} else if (_toFinal <= bonusEndBlock) {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(_toFinal.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSONE_MULTIPLIER);
}
} else {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(bonusEndBlock.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER)).add(
(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER)));
} else if (betaTestEndBlock <= _from && _from < bonusEndBlock) {
return bonusEndBlock.sub(_from).mul(BONUSONE_MULTIPLIER).add(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSTWO_MULTIPLIER);
}
}
}
// View function to see pending SAKEs on frontend.
function pendingSake(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSakePerShare = pool.accSakePerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSakePerShare = accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSakePerShare).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);
if (multiplier == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sake.mint(devaddr, sakeReward.div(15));
sake.mint(address(this), sakeReward);
pool.accSakePerShare = pool.accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to SakeMaster for SAKE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
if (pending > 0) safeSakeTransfer(msg.sender, pending);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from SakeMaster.
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.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
safeSakeTransfer(msg.sender, pending);
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];
require(user.amount > 0, "emergencyWithdraw: not good");
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Safe sake transfer function, just in case if rounding error causes pool to not have enough SAKEs.
function safeSakeTransfer(address _to, uint256 _amount) internal {
uint256 sakeBal = sake.balanceOf(address(this));
if (_amount > sakeBal) {
sake.transfer(_to, sakeBal);
} else {
sake.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // SakeMaster is the master of Sake. He can make Sake 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 SAKE 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) {
uint256 _toFinal = _to > mintEndBlock ? mintEndBlock : _to;
if (_toFinal <= betaTestEndBlock) {
return _toFinal.sub(_from);
}else if (_from >= mintEndBlock) {
return 0;
} else if (_toFinal <= bonusEndBlock) {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(_toFinal.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSONE_MULTIPLIER);
}
} else {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(bonusEndBlock.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER)).add(
(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER)));
} else if (betaTestEndBlock <= _from && _from < bonusEndBlock) {
return bonusEndBlock.sub(_from).mul(BONUSONE_MULTIPLIER).add(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSTWO_MULTIPLIER);
}
}
}
| // Return reward multiplier over the given _from to _to block. | LineComment | v0.6.12+commit.27d51765 | None | ipfs://5d4700996a40376e16d7d09f63c9d6b8ef633b28dd8203c5297833f9286dce20 | {
"func_code_index": [
6079,
7305
]
} | 3,696 |
SakeVoterCalc | contracts/SakeMaster.sol | 0x44d84a9da47fd8f4a06ad66b197d1441fca53f92 | Solidity | SakeMaster | contract SakeMaster 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 SAKEs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSakePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSakePerShare` (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. SAKEs to distribute per block.
uint256 lastRewardBlock; // Last block number that SAKEs distribution occurs.
uint256 accSakePerShare; // Accumulated SAKEs per share, times 1e12. See below.
}
// The SAKE TOKEN!
SakeToken public sake;
// Dev address.
address public devaddr;
// Block number when beta test period ends.
uint256 public betaTestEndBlock;
// Block number when bonus SAKE period ends.
uint256 public bonusEndBlock;
// Block number when mint SAKE period ends.
uint256 public mintEndBlock;
// SAKE tokens created per block.
uint256 public sakePerBlock;
// Bonus muliplier for 5~20 days sake makers.
uint256 public constant BONUSONE_MULTIPLIER = 20;
// Bonus muliplier for 20~35 sake makers.
uint256 public constant BONUSTWO_MULTIPLIER = 2;
// beta test block num,about 5 days.
uint256 public constant BETATEST_BLOCKNUM = 35000;
// Bonus block num,about 15 days.
uint256 public constant BONUS_BLOCKNUM = 100000;
// mint end block num,about 30 days.
uint256 public constant MINTEND_BLOCKNUM = 200000;
// 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;
// Record whether the pair has been added.
mapping(address => uint256) public lpTokenPID;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SAKE 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(
SakeToken _sake,
address _devaddr,
uint256 _sakePerBlock,
uint256 _startBlock
) public {
sake = _sake;
devaddr = _devaddr;
sakePerBlock = _sakePerBlock;
startBlock = _startBlock;
betaTestEndBlock = startBlock.add(BETATEST_BLOCKNUM);
bonusEndBlock = startBlock.add(BONUS_BLOCKNUM).add(BETATEST_BLOCKNUM);
mintEndBlock = startBlock.add(MINTEND_BLOCKNUM).add(BETATEST_BLOCKNUM);
}
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();
}
require(lpTokenPID[address(_lpToken)] == 0, "SakeMaster:duplicate add.");
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSakePerShare: 0
})
);
lpTokenPID[address(_lpToken)] = poolInfo.length;
}
// Update the given pool's SAKE 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;
}
// Handover the saketoken mintage right.
function handoverSakeMintage(address newOwner) public onlyOwner {
sake.transferOwnership(newOwner);
}
// 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) {
uint256 _toFinal = _to > mintEndBlock ? mintEndBlock : _to;
if (_toFinal <= betaTestEndBlock) {
return _toFinal.sub(_from);
}else if (_from >= mintEndBlock) {
return 0;
} else if (_toFinal <= bonusEndBlock) {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(_toFinal.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSONE_MULTIPLIER);
}
} else {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(bonusEndBlock.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER)).add(
(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER)));
} else if (betaTestEndBlock <= _from && _from < bonusEndBlock) {
return bonusEndBlock.sub(_from).mul(BONUSONE_MULTIPLIER).add(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSTWO_MULTIPLIER);
}
}
}
// View function to see pending SAKEs on frontend.
function pendingSake(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSakePerShare = pool.accSakePerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSakePerShare = accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSakePerShare).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);
if (multiplier == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sake.mint(devaddr, sakeReward.div(15));
sake.mint(address(this), sakeReward);
pool.accSakePerShare = pool.accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to SakeMaster for SAKE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
if (pending > 0) safeSakeTransfer(msg.sender, pending);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from SakeMaster.
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.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
safeSakeTransfer(msg.sender, pending);
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];
require(user.amount > 0, "emergencyWithdraw: not good");
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Safe sake transfer function, just in case if rounding error causes pool to not have enough SAKEs.
function safeSakeTransfer(address _to, uint256 _amount) internal {
uint256 sakeBal = sake.balanceOf(address(this));
if (_amount > sakeBal) {
sake.transfer(_to, sakeBal);
} else {
sake.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // SakeMaster is the master of Sake. He can make Sake 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 SAKE is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | pendingSake | function pendingSake(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSakePerShare = pool.accSakePerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSakePerShare = accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSakePerShare).div(1e12).sub(user.rewardDebt);
}
| // View function to see pending SAKEs on frontend. | LineComment | v0.6.12+commit.27d51765 | None | ipfs://5d4700996a40376e16d7d09f63c9d6b8ef633b28dd8203c5297833f9286dce20 | {
"func_code_index": [
7364,
8128
]
} | 3,697 |
SakeVoterCalc | contracts/SakeMaster.sol | 0x44d84a9da47fd8f4a06ad66b197d1441fca53f92 | Solidity | SakeMaster | contract SakeMaster 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 SAKEs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSakePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSakePerShare` (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. SAKEs to distribute per block.
uint256 lastRewardBlock; // Last block number that SAKEs distribution occurs.
uint256 accSakePerShare; // Accumulated SAKEs per share, times 1e12. See below.
}
// The SAKE TOKEN!
SakeToken public sake;
// Dev address.
address public devaddr;
// Block number when beta test period ends.
uint256 public betaTestEndBlock;
// Block number when bonus SAKE period ends.
uint256 public bonusEndBlock;
// Block number when mint SAKE period ends.
uint256 public mintEndBlock;
// SAKE tokens created per block.
uint256 public sakePerBlock;
// Bonus muliplier for 5~20 days sake makers.
uint256 public constant BONUSONE_MULTIPLIER = 20;
// Bonus muliplier for 20~35 sake makers.
uint256 public constant BONUSTWO_MULTIPLIER = 2;
// beta test block num,about 5 days.
uint256 public constant BETATEST_BLOCKNUM = 35000;
// Bonus block num,about 15 days.
uint256 public constant BONUS_BLOCKNUM = 100000;
// mint end block num,about 30 days.
uint256 public constant MINTEND_BLOCKNUM = 200000;
// 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;
// Record whether the pair has been added.
mapping(address => uint256) public lpTokenPID;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SAKE 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(
SakeToken _sake,
address _devaddr,
uint256 _sakePerBlock,
uint256 _startBlock
) public {
sake = _sake;
devaddr = _devaddr;
sakePerBlock = _sakePerBlock;
startBlock = _startBlock;
betaTestEndBlock = startBlock.add(BETATEST_BLOCKNUM);
bonusEndBlock = startBlock.add(BONUS_BLOCKNUM).add(BETATEST_BLOCKNUM);
mintEndBlock = startBlock.add(MINTEND_BLOCKNUM).add(BETATEST_BLOCKNUM);
}
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();
}
require(lpTokenPID[address(_lpToken)] == 0, "SakeMaster:duplicate add.");
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSakePerShare: 0
})
);
lpTokenPID[address(_lpToken)] = poolInfo.length;
}
// Update the given pool's SAKE 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;
}
// Handover the saketoken mintage right.
function handoverSakeMintage(address newOwner) public onlyOwner {
sake.transferOwnership(newOwner);
}
// 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) {
uint256 _toFinal = _to > mintEndBlock ? mintEndBlock : _to;
if (_toFinal <= betaTestEndBlock) {
return _toFinal.sub(_from);
}else if (_from >= mintEndBlock) {
return 0;
} else if (_toFinal <= bonusEndBlock) {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(_toFinal.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSONE_MULTIPLIER);
}
} else {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(bonusEndBlock.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER)).add(
(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER)));
} else if (betaTestEndBlock <= _from && _from < bonusEndBlock) {
return bonusEndBlock.sub(_from).mul(BONUSONE_MULTIPLIER).add(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSTWO_MULTIPLIER);
}
}
}
// View function to see pending SAKEs on frontend.
function pendingSake(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSakePerShare = pool.accSakePerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSakePerShare = accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSakePerShare).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);
if (multiplier == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sake.mint(devaddr, sakeReward.div(15));
sake.mint(address(this), sakeReward);
pool.accSakePerShare = pool.accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to SakeMaster for SAKE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
if (pending > 0) safeSakeTransfer(msg.sender, pending);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from SakeMaster.
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.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
safeSakeTransfer(msg.sender, pending);
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];
require(user.amount > 0, "emergencyWithdraw: not good");
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Safe sake transfer function, just in case if rounding error causes pool to not have enough SAKEs.
function safeSakeTransfer(address _to, uint256 _amount) internal {
uint256 sakeBal = sake.balanceOf(address(this));
if (_amount > sakeBal) {
sake.transfer(_to, sakeBal);
} else {
sake.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // SakeMaster is the master of Sake. He can make Sake 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 SAKE 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 | None | ipfs://5d4700996a40376e16d7d09f63c9d6b8ef633b28dd8203c5297833f9286dce20 | {
"func_code_index": [
8206,
8391
]
} | 3,698 |
SakeVoterCalc | contracts/SakeMaster.sol | 0x44d84a9da47fd8f4a06ad66b197d1441fca53f92 | Solidity | SakeMaster | contract SakeMaster 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 SAKEs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSakePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSakePerShare` (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. SAKEs to distribute per block.
uint256 lastRewardBlock; // Last block number that SAKEs distribution occurs.
uint256 accSakePerShare; // Accumulated SAKEs per share, times 1e12. See below.
}
// The SAKE TOKEN!
SakeToken public sake;
// Dev address.
address public devaddr;
// Block number when beta test period ends.
uint256 public betaTestEndBlock;
// Block number when bonus SAKE period ends.
uint256 public bonusEndBlock;
// Block number when mint SAKE period ends.
uint256 public mintEndBlock;
// SAKE tokens created per block.
uint256 public sakePerBlock;
// Bonus muliplier for 5~20 days sake makers.
uint256 public constant BONUSONE_MULTIPLIER = 20;
// Bonus muliplier for 20~35 sake makers.
uint256 public constant BONUSTWO_MULTIPLIER = 2;
// beta test block num,about 5 days.
uint256 public constant BETATEST_BLOCKNUM = 35000;
// Bonus block num,about 15 days.
uint256 public constant BONUS_BLOCKNUM = 100000;
// mint end block num,about 30 days.
uint256 public constant MINTEND_BLOCKNUM = 200000;
// 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;
// Record whether the pair has been added.
mapping(address => uint256) public lpTokenPID;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SAKE 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(
SakeToken _sake,
address _devaddr,
uint256 _sakePerBlock,
uint256 _startBlock
) public {
sake = _sake;
devaddr = _devaddr;
sakePerBlock = _sakePerBlock;
startBlock = _startBlock;
betaTestEndBlock = startBlock.add(BETATEST_BLOCKNUM);
bonusEndBlock = startBlock.add(BONUS_BLOCKNUM).add(BETATEST_BLOCKNUM);
mintEndBlock = startBlock.add(MINTEND_BLOCKNUM).add(BETATEST_BLOCKNUM);
}
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();
}
require(lpTokenPID[address(_lpToken)] == 0, "SakeMaster:duplicate add.");
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSakePerShare: 0
})
);
lpTokenPID[address(_lpToken)] = poolInfo.length;
}
// Update the given pool's SAKE 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;
}
// Handover the saketoken mintage right.
function handoverSakeMintage(address newOwner) public onlyOwner {
sake.transferOwnership(newOwner);
}
// 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) {
uint256 _toFinal = _to > mintEndBlock ? mintEndBlock : _to;
if (_toFinal <= betaTestEndBlock) {
return _toFinal.sub(_from);
}else if (_from >= mintEndBlock) {
return 0;
} else if (_toFinal <= bonusEndBlock) {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(_toFinal.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSONE_MULTIPLIER);
}
} else {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(bonusEndBlock.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER)).add(
(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER)));
} else if (betaTestEndBlock <= _from && _from < bonusEndBlock) {
return bonusEndBlock.sub(_from).mul(BONUSONE_MULTIPLIER).add(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSTWO_MULTIPLIER);
}
}
}
// View function to see pending SAKEs on frontend.
function pendingSake(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSakePerShare = pool.accSakePerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSakePerShare = accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSakePerShare).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);
if (multiplier == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sake.mint(devaddr, sakeReward.div(15));
sake.mint(address(this), sakeReward);
pool.accSakePerShare = pool.accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to SakeMaster for SAKE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
if (pending > 0) safeSakeTransfer(msg.sender, pending);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from SakeMaster.
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.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
safeSakeTransfer(msg.sender, pending);
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];
require(user.amount > 0, "emergencyWithdraw: not good");
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Safe sake transfer function, just in case if rounding error causes pool to not have enough SAKEs.
function safeSakeTransfer(address _to, uint256 _amount) internal {
uint256 sakeBal = sake.balanceOf(address(this));
if (_amount > sakeBal) {
sake.transfer(_to, sakeBal);
} else {
sake.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // SakeMaster is the master of Sake. He can make Sake 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 SAKE 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);
if (multiplier == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sake.mint(devaddr, sakeReward.div(15));
sake.mint(address(this), sakeReward);
pool.accSakePerShare = pool.accSakePerShare.add(sakeReward.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 | None | ipfs://5d4700996a40376e16d7d09f63c9d6b8ef633b28dd8203c5297833f9286dce20 | {
"func_code_index": [
8462,
9362
]
} | 3,699 |
SakeVoterCalc | contracts/SakeMaster.sol | 0x44d84a9da47fd8f4a06ad66b197d1441fca53f92 | Solidity | SakeMaster | contract SakeMaster 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 SAKEs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSakePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSakePerShare` (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. SAKEs to distribute per block.
uint256 lastRewardBlock; // Last block number that SAKEs distribution occurs.
uint256 accSakePerShare; // Accumulated SAKEs per share, times 1e12. See below.
}
// The SAKE TOKEN!
SakeToken public sake;
// Dev address.
address public devaddr;
// Block number when beta test period ends.
uint256 public betaTestEndBlock;
// Block number when bonus SAKE period ends.
uint256 public bonusEndBlock;
// Block number when mint SAKE period ends.
uint256 public mintEndBlock;
// SAKE tokens created per block.
uint256 public sakePerBlock;
// Bonus muliplier for 5~20 days sake makers.
uint256 public constant BONUSONE_MULTIPLIER = 20;
// Bonus muliplier for 20~35 sake makers.
uint256 public constant BONUSTWO_MULTIPLIER = 2;
// beta test block num,about 5 days.
uint256 public constant BETATEST_BLOCKNUM = 35000;
// Bonus block num,about 15 days.
uint256 public constant BONUS_BLOCKNUM = 100000;
// mint end block num,about 30 days.
uint256 public constant MINTEND_BLOCKNUM = 200000;
// 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;
// Record whether the pair has been added.
mapping(address => uint256) public lpTokenPID;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SAKE 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(
SakeToken _sake,
address _devaddr,
uint256 _sakePerBlock,
uint256 _startBlock
) public {
sake = _sake;
devaddr = _devaddr;
sakePerBlock = _sakePerBlock;
startBlock = _startBlock;
betaTestEndBlock = startBlock.add(BETATEST_BLOCKNUM);
bonusEndBlock = startBlock.add(BONUS_BLOCKNUM).add(BETATEST_BLOCKNUM);
mintEndBlock = startBlock.add(MINTEND_BLOCKNUM).add(BETATEST_BLOCKNUM);
}
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();
}
require(lpTokenPID[address(_lpToken)] == 0, "SakeMaster:duplicate add.");
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSakePerShare: 0
})
);
lpTokenPID[address(_lpToken)] = poolInfo.length;
}
// Update the given pool's SAKE 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;
}
// Handover the saketoken mintage right.
function handoverSakeMintage(address newOwner) public onlyOwner {
sake.transferOwnership(newOwner);
}
// 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) {
uint256 _toFinal = _to > mintEndBlock ? mintEndBlock : _to;
if (_toFinal <= betaTestEndBlock) {
return _toFinal.sub(_from);
}else if (_from >= mintEndBlock) {
return 0;
} else if (_toFinal <= bonusEndBlock) {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(_toFinal.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSONE_MULTIPLIER);
}
} else {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(bonusEndBlock.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER)).add(
(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER)));
} else if (betaTestEndBlock <= _from && _from < bonusEndBlock) {
return bonusEndBlock.sub(_from).mul(BONUSONE_MULTIPLIER).add(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSTWO_MULTIPLIER);
}
}
}
// View function to see pending SAKEs on frontend.
function pendingSake(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSakePerShare = pool.accSakePerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSakePerShare = accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSakePerShare).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);
if (multiplier == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sake.mint(devaddr, sakeReward.div(15));
sake.mint(address(this), sakeReward);
pool.accSakePerShare = pool.accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to SakeMaster for SAKE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
if (pending > 0) safeSakeTransfer(msg.sender, pending);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from SakeMaster.
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.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
safeSakeTransfer(msg.sender, pending);
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];
require(user.amount > 0, "emergencyWithdraw: not good");
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Safe sake transfer function, just in case if rounding error causes pool to not have enough SAKEs.
function safeSakeTransfer(address _to, uint256 _amount) internal {
uint256 sakeBal = sake.balanceOf(address(this));
if (_amount > sakeBal) {
sake.transfer(_to, sakeBal);
} else {
sake.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // SakeMaster is the master of Sake. He can make Sake 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 SAKE 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);
uint256 pending = user.amount.mul(pool.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
if (pending > 0) safeSakeTransfer(msg.sender, pending);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
emit Deposit(msg.sender, _pid, _amount);
}
| // Deposit LP tokens to SakeMaster for SAKE allocation. | LineComment | v0.6.12+commit.27d51765 | None | ipfs://5d4700996a40376e16d7d09f63c9d6b8ef633b28dd8203c5297833f9286dce20 | {
"func_code_index": [
9426,
10053
]
} | 3,700 |
SakeVoterCalc | contracts/SakeMaster.sol | 0x44d84a9da47fd8f4a06ad66b197d1441fca53f92 | Solidity | SakeMaster | contract SakeMaster 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 SAKEs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSakePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSakePerShare` (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. SAKEs to distribute per block.
uint256 lastRewardBlock; // Last block number that SAKEs distribution occurs.
uint256 accSakePerShare; // Accumulated SAKEs per share, times 1e12. See below.
}
// The SAKE TOKEN!
SakeToken public sake;
// Dev address.
address public devaddr;
// Block number when beta test period ends.
uint256 public betaTestEndBlock;
// Block number when bonus SAKE period ends.
uint256 public bonusEndBlock;
// Block number when mint SAKE period ends.
uint256 public mintEndBlock;
// SAKE tokens created per block.
uint256 public sakePerBlock;
// Bonus muliplier for 5~20 days sake makers.
uint256 public constant BONUSONE_MULTIPLIER = 20;
// Bonus muliplier for 20~35 sake makers.
uint256 public constant BONUSTWO_MULTIPLIER = 2;
// beta test block num,about 5 days.
uint256 public constant BETATEST_BLOCKNUM = 35000;
// Bonus block num,about 15 days.
uint256 public constant BONUS_BLOCKNUM = 100000;
// mint end block num,about 30 days.
uint256 public constant MINTEND_BLOCKNUM = 200000;
// 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;
// Record whether the pair has been added.
mapping(address => uint256) public lpTokenPID;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SAKE 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(
SakeToken _sake,
address _devaddr,
uint256 _sakePerBlock,
uint256 _startBlock
) public {
sake = _sake;
devaddr = _devaddr;
sakePerBlock = _sakePerBlock;
startBlock = _startBlock;
betaTestEndBlock = startBlock.add(BETATEST_BLOCKNUM);
bonusEndBlock = startBlock.add(BONUS_BLOCKNUM).add(BETATEST_BLOCKNUM);
mintEndBlock = startBlock.add(MINTEND_BLOCKNUM).add(BETATEST_BLOCKNUM);
}
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();
}
require(lpTokenPID[address(_lpToken)] == 0, "SakeMaster:duplicate add.");
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSakePerShare: 0
})
);
lpTokenPID[address(_lpToken)] = poolInfo.length;
}
// Update the given pool's SAKE 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;
}
// Handover the saketoken mintage right.
function handoverSakeMintage(address newOwner) public onlyOwner {
sake.transferOwnership(newOwner);
}
// 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) {
uint256 _toFinal = _to > mintEndBlock ? mintEndBlock : _to;
if (_toFinal <= betaTestEndBlock) {
return _toFinal.sub(_from);
}else if (_from >= mintEndBlock) {
return 0;
} else if (_toFinal <= bonusEndBlock) {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(_toFinal.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSONE_MULTIPLIER);
}
} else {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(bonusEndBlock.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER)).add(
(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER)));
} else if (betaTestEndBlock <= _from && _from < bonusEndBlock) {
return bonusEndBlock.sub(_from).mul(BONUSONE_MULTIPLIER).add(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSTWO_MULTIPLIER);
}
}
}
// View function to see pending SAKEs on frontend.
function pendingSake(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSakePerShare = pool.accSakePerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSakePerShare = accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSakePerShare).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);
if (multiplier == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sake.mint(devaddr, sakeReward.div(15));
sake.mint(address(this), sakeReward);
pool.accSakePerShare = pool.accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to SakeMaster for SAKE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
if (pending > 0) safeSakeTransfer(msg.sender, pending);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from SakeMaster.
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.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
safeSakeTransfer(msg.sender, pending);
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];
require(user.amount > 0, "emergencyWithdraw: not good");
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Safe sake transfer function, just in case if rounding error causes pool to not have enough SAKEs.
function safeSakeTransfer(address _to, uint256 _amount) internal {
uint256 sakeBal = sake.balanceOf(address(this));
if (_amount > sakeBal) {
sake.transfer(_to, sakeBal);
} else {
sake.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // SakeMaster is the master of Sake. He can make Sake 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 SAKE 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.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
safeSakeTransfer(msg.sender, pending);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
| // Withdraw LP tokens from SakeMaster. | LineComment | v0.6.12+commit.27d51765 | None | ipfs://5d4700996a40376e16d7d09f63c9d6b8ef633b28dd8203c5297833f9286dce20 | {
"func_code_index": [
10100,
10757
]
} | 3,701 |
SakeVoterCalc | contracts/SakeMaster.sol | 0x44d84a9da47fd8f4a06ad66b197d1441fca53f92 | Solidity | SakeMaster | contract SakeMaster 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 SAKEs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSakePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSakePerShare` (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. SAKEs to distribute per block.
uint256 lastRewardBlock; // Last block number that SAKEs distribution occurs.
uint256 accSakePerShare; // Accumulated SAKEs per share, times 1e12. See below.
}
// The SAKE TOKEN!
SakeToken public sake;
// Dev address.
address public devaddr;
// Block number when beta test period ends.
uint256 public betaTestEndBlock;
// Block number when bonus SAKE period ends.
uint256 public bonusEndBlock;
// Block number when mint SAKE period ends.
uint256 public mintEndBlock;
// SAKE tokens created per block.
uint256 public sakePerBlock;
// Bonus muliplier for 5~20 days sake makers.
uint256 public constant BONUSONE_MULTIPLIER = 20;
// Bonus muliplier for 20~35 sake makers.
uint256 public constant BONUSTWO_MULTIPLIER = 2;
// beta test block num,about 5 days.
uint256 public constant BETATEST_BLOCKNUM = 35000;
// Bonus block num,about 15 days.
uint256 public constant BONUS_BLOCKNUM = 100000;
// mint end block num,about 30 days.
uint256 public constant MINTEND_BLOCKNUM = 200000;
// 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;
// Record whether the pair has been added.
mapping(address => uint256) public lpTokenPID;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SAKE 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(
SakeToken _sake,
address _devaddr,
uint256 _sakePerBlock,
uint256 _startBlock
) public {
sake = _sake;
devaddr = _devaddr;
sakePerBlock = _sakePerBlock;
startBlock = _startBlock;
betaTestEndBlock = startBlock.add(BETATEST_BLOCKNUM);
bonusEndBlock = startBlock.add(BONUS_BLOCKNUM).add(BETATEST_BLOCKNUM);
mintEndBlock = startBlock.add(MINTEND_BLOCKNUM).add(BETATEST_BLOCKNUM);
}
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();
}
require(lpTokenPID[address(_lpToken)] == 0, "SakeMaster:duplicate add.");
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSakePerShare: 0
})
);
lpTokenPID[address(_lpToken)] = poolInfo.length;
}
// Update the given pool's SAKE 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;
}
// Handover the saketoken mintage right.
function handoverSakeMintage(address newOwner) public onlyOwner {
sake.transferOwnership(newOwner);
}
// 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) {
uint256 _toFinal = _to > mintEndBlock ? mintEndBlock : _to;
if (_toFinal <= betaTestEndBlock) {
return _toFinal.sub(_from);
}else if (_from >= mintEndBlock) {
return 0;
} else if (_toFinal <= bonusEndBlock) {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(_toFinal.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSONE_MULTIPLIER);
}
} else {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(bonusEndBlock.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER)).add(
(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER)));
} else if (betaTestEndBlock <= _from && _from < bonusEndBlock) {
return bonusEndBlock.sub(_from).mul(BONUSONE_MULTIPLIER).add(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSTWO_MULTIPLIER);
}
}
}
// View function to see pending SAKEs on frontend.
function pendingSake(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSakePerShare = pool.accSakePerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSakePerShare = accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSakePerShare).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);
if (multiplier == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sake.mint(devaddr, sakeReward.div(15));
sake.mint(address(this), sakeReward);
pool.accSakePerShare = pool.accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to SakeMaster for SAKE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
if (pending > 0) safeSakeTransfer(msg.sender, pending);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from SakeMaster.
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.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
safeSakeTransfer(msg.sender, pending);
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];
require(user.amount > 0, "emergencyWithdraw: not good");
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Safe sake transfer function, just in case if rounding error causes pool to not have enough SAKEs.
function safeSakeTransfer(address _to, uint256 _amount) internal {
uint256 sakeBal = sake.balanceOf(address(this));
if (_amount > sakeBal) {
sake.transfer(_to, sakeBal);
} else {
sake.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // SakeMaster is the master of Sake. He can make Sake 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 SAKE 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];
require(user.amount > 0, "emergencyWithdraw: not good");
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
| // Withdraw without caring about rewards. EMERGENCY ONLY. | LineComment | v0.6.12+commit.27d51765 | None | ipfs://5d4700996a40376e16d7d09f63c9d6b8ef633b28dd8203c5297833f9286dce20 | {
"func_code_index": [
10823,
11282
]
} | 3,702 |
SakeVoterCalc | contracts/SakeMaster.sol | 0x44d84a9da47fd8f4a06ad66b197d1441fca53f92 | Solidity | SakeMaster | contract SakeMaster 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 SAKEs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSakePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSakePerShare` (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. SAKEs to distribute per block.
uint256 lastRewardBlock; // Last block number that SAKEs distribution occurs.
uint256 accSakePerShare; // Accumulated SAKEs per share, times 1e12. See below.
}
// The SAKE TOKEN!
SakeToken public sake;
// Dev address.
address public devaddr;
// Block number when beta test period ends.
uint256 public betaTestEndBlock;
// Block number when bonus SAKE period ends.
uint256 public bonusEndBlock;
// Block number when mint SAKE period ends.
uint256 public mintEndBlock;
// SAKE tokens created per block.
uint256 public sakePerBlock;
// Bonus muliplier for 5~20 days sake makers.
uint256 public constant BONUSONE_MULTIPLIER = 20;
// Bonus muliplier for 20~35 sake makers.
uint256 public constant BONUSTWO_MULTIPLIER = 2;
// beta test block num,about 5 days.
uint256 public constant BETATEST_BLOCKNUM = 35000;
// Bonus block num,about 15 days.
uint256 public constant BONUS_BLOCKNUM = 100000;
// mint end block num,about 30 days.
uint256 public constant MINTEND_BLOCKNUM = 200000;
// 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;
// Record whether the pair has been added.
mapping(address => uint256) public lpTokenPID;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SAKE 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(
SakeToken _sake,
address _devaddr,
uint256 _sakePerBlock,
uint256 _startBlock
) public {
sake = _sake;
devaddr = _devaddr;
sakePerBlock = _sakePerBlock;
startBlock = _startBlock;
betaTestEndBlock = startBlock.add(BETATEST_BLOCKNUM);
bonusEndBlock = startBlock.add(BONUS_BLOCKNUM).add(BETATEST_BLOCKNUM);
mintEndBlock = startBlock.add(MINTEND_BLOCKNUM).add(BETATEST_BLOCKNUM);
}
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();
}
require(lpTokenPID[address(_lpToken)] == 0, "SakeMaster:duplicate add.");
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSakePerShare: 0
})
);
lpTokenPID[address(_lpToken)] = poolInfo.length;
}
// Update the given pool's SAKE 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;
}
// Handover the saketoken mintage right.
function handoverSakeMintage(address newOwner) public onlyOwner {
sake.transferOwnership(newOwner);
}
// 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) {
uint256 _toFinal = _to > mintEndBlock ? mintEndBlock : _to;
if (_toFinal <= betaTestEndBlock) {
return _toFinal.sub(_from);
}else if (_from >= mintEndBlock) {
return 0;
} else if (_toFinal <= bonusEndBlock) {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(_toFinal.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSONE_MULTIPLIER);
}
} else {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(bonusEndBlock.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER)).add(
(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER)));
} else if (betaTestEndBlock <= _from && _from < bonusEndBlock) {
return bonusEndBlock.sub(_from).mul(BONUSONE_MULTIPLIER).add(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSTWO_MULTIPLIER);
}
}
}
// View function to see pending SAKEs on frontend.
function pendingSake(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSakePerShare = pool.accSakePerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSakePerShare = accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSakePerShare).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);
if (multiplier == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sake.mint(devaddr, sakeReward.div(15));
sake.mint(address(this), sakeReward);
pool.accSakePerShare = pool.accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to SakeMaster for SAKE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
if (pending > 0) safeSakeTransfer(msg.sender, pending);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from SakeMaster.
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.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
safeSakeTransfer(msg.sender, pending);
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];
require(user.amount > 0, "emergencyWithdraw: not good");
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Safe sake transfer function, just in case if rounding error causes pool to not have enough SAKEs.
function safeSakeTransfer(address _to, uint256 _amount) internal {
uint256 sakeBal = sake.balanceOf(address(this));
if (_amount > sakeBal) {
sake.transfer(_to, sakeBal);
} else {
sake.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // SakeMaster is the master of Sake. He can make Sake 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 SAKE is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless. | LineComment | safeSakeTransfer | function safeSakeTransfer(address _to, uint256 _amount) internal {
uint256 sakeBal = sake.balanceOf(address(this));
if (_amount > sakeBal) {
sake.transfer(_to, sakeBal);
} else {
sake.transfer(_to, _amount);
}
}
| // Safe sake transfer function, just in case if rounding error causes pool to not have enough SAKEs. | LineComment | v0.6.12+commit.27d51765 | None | ipfs://5d4700996a40376e16d7d09f63c9d6b8ef633b28dd8203c5297833f9286dce20 | {
"func_code_index": [
11391,
11674
]
} | 3,703 |
SakeVoterCalc | contracts/SakeMaster.sol | 0x44d84a9da47fd8f4a06ad66b197d1441fca53f92 | Solidity | SakeMaster | contract SakeMaster 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 SAKEs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSakePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSakePerShare` (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. SAKEs to distribute per block.
uint256 lastRewardBlock; // Last block number that SAKEs distribution occurs.
uint256 accSakePerShare; // Accumulated SAKEs per share, times 1e12. See below.
}
// The SAKE TOKEN!
SakeToken public sake;
// Dev address.
address public devaddr;
// Block number when beta test period ends.
uint256 public betaTestEndBlock;
// Block number when bonus SAKE period ends.
uint256 public bonusEndBlock;
// Block number when mint SAKE period ends.
uint256 public mintEndBlock;
// SAKE tokens created per block.
uint256 public sakePerBlock;
// Bonus muliplier for 5~20 days sake makers.
uint256 public constant BONUSONE_MULTIPLIER = 20;
// Bonus muliplier for 20~35 sake makers.
uint256 public constant BONUSTWO_MULTIPLIER = 2;
// beta test block num,about 5 days.
uint256 public constant BETATEST_BLOCKNUM = 35000;
// Bonus block num,about 15 days.
uint256 public constant BONUS_BLOCKNUM = 100000;
// mint end block num,about 30 days.
uint256 public constant MINTEND_BLOCKNUM = 200000;
// 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;
// Record whether the pair has been added.
mapping(address => uint256) public lpTokenPID;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SAKE 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(
SakeToken _sake,
address _devaddr,
uint256 _sakePerBlock,
uint256 _startBlock
) public {
sake = _sake;
devaddr = _devaddr;
sakePerBlock = _sakePerBlock;
startBlock = _startBlock;
betaTestEndBlock = startBlock.add(BETATEST_BLOCKNUM);
bonusEndBlock = startBlock.add(BONUS_BLOCKNUM).add(BETATEST_BLOCKNUM);
mintEndBlock = startBlock.add(MINTEND_BLOCKNUM).add(BETATEST_BLOCKNUM);
}
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();
}
require(lpTokenPID[address(_lpToken)] == 0, "SakeMaster:duplicate add.");
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSakePerShare: 0
})
);
lpTokenPID[address(_lpToken)] = poolInfo.length;
}
// Update the given pool's SAKE 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;
}
// Handover the saketoken mintage right.
function handoverSakeMintage(address newOwner) public onlyOwner {
sake.transferOwnership(newOwner);
}
// 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) {
uint256 _toFinal = _to > mintEndBlock ? mintEndBlock : _to;
if (_toFinal <= betaTestEndBlock) {
return _toFinal.sub(_from);
}else if (_from >= mintEndBlock) {
return 0;
} else if (_toFinal <= bonusEndBlock) {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(_toFinal.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSONE_MULTIPLIER);
}
} else {
if (_from < betaTestEndBlock) {
return betaTestEndBlock.sub(_from).add(bonusEndBlock.sub(betaTestEndBlock).mul(BONUSONE_MULTIPLIER)).add(
(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER)));
} else if (betaTestEndBlock <= _from && _from < bonusEndBlock) {
return bonusEndBlock.sub(_from).mul(BONUSONE_MULTIPLIER).add(_toFinal.sub(bonusEndBlock).mul(BONUSTWO_MULTIPLIER));
} else {
return _toFinal.sub(_from).mul(BONUSTWO_MULTIPLIER);
}
}
}
// View function to see pending SAKEs on frontend.
function pendingSake(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSakePerShare = pool.accSakePerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSakePerShare = accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSakePerShare).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);
if (multiplier == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 sakeReward = multiplier.mul(sakePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sake.mint(devaddr, sakeReward.div(15));
sake.mint(address(this), sakeReward);
pool.accSakePerShare = pool.accSakePerShare.add(sakeReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to SakeMaster for SAKE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
if (pending > 0) safeSakeTransfer(msg.sender, pending);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from SakeMaster.
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.accSakePerShare).div(1e12).sub(user.rewardDebt);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSakePerShare).div(1e12);
safeSakeTransfer(msg.sender, pending);
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];
require(user.amount > 0, "emergencyWithdraw: not good");
uint256 _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Safe sake transfer function, just in case if rounding error causes pool to not have enough SAKEs.
function safeSakeTransfer(address _to, uint256 _amount) internal {
uint256 sakeBal = sake.balanceOf(address(this));
if (_amount > sakeBal) {
sake.transfer(_to, sakeBal);
} else {
sake.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
} | // SakeMaster is the master of Sake. He can make Sake 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 SAKE 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 | None | ipfs://5d4700996a40376e16d7d09f63c9d6b8ef633b28dd8203c5297833f9286dce20 | {
"func_code_index": [
11725,
11859
]
} | 3,704 |
Americo | Americo.sol | 0x09eaf7b80ec741fa8a163cd4dde8367fab37e8a0 | Solidity | Americo | contract Americo {
/* Variables públicas del token */
string public standard = 'Token 0.1';
string public name;
string public symbol;
uint8 public decimals;
uint256 public initialSupply;
uint256 public totalSupply;
/* Esto crea una matriz con todos los saldos */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* Inicializa el contrato con los tokens de suministro inicial al creador del contrato */
function Americo() {
initialSupply=160000000;
name="Americo";
decimals=6;
symbol="A";
balanceOf[msg.sender] = initialSupply; // Americo recibe todas las fichas iniciales
totalSupply = initialSupply; // Actualizar la oferta total
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw; // Compruebe si el remitente tiene suficiente
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Verificar desbordamientos
balanceOf[msg.sender] -= _value; // Reste del remitente
balanceOf[_to] += _value; // Agregue lo mismo al destinatario
}
/* Esta función sin nombre se llama cada vez que alguien intenta enviar éter a ella */
function () {
throw; // Evita el envío accidental de éter
}
} | Americo | function Americo() {
initialSupply=160000000;
name="Americo";
decimals=6;
symbol="A";
balanceOf[msg.sender] = initialSupply; // Americo recibe todas las fichas iniciales
totalSupply = initialSupply; // Actualizar la oferta total
}
| /* Inicializa el contrato con los tokens de suministro inicial al creador del contrato */ | Comment | v0.4.19+commit.c4cbbb05 | bzzr://2bb40ed958008e5bbe69da40c3b5da723d2539387782f8a45ee0dd3e5e3eb1b4 | {
"func_code_index": [
530,
912
]
} | 3,705 |
|||
Americo | Americo.sol | 0x09eaf7b80ec741fa8a163cd4dde8367fab37e8a0 | Solidity | Americo | contract Americo {
/* Variables públicas del token */
string public standard = 'Token 0.1';
string public name;
string public symbol;
uint8 public decimals;
uint256 public initialSupply;
uint256 public totalSupply;
/* Esto crea una matriz con todos los saldos */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* Inicializa el contrato con los tokens de suministro inicial al creador del contrato */
function Americo() {
initialSupply=160000000;
name="Americo";
decimals=6;
symbol="A";
balanceOf[msg.sender] = initialSupply; // Americo recibe todas las fichas iniciales
totalSupply = initialSupply; // Actualizar la oferta total
}
/* Send coins */
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw; // Compruebe si el remitente tiene suficiente
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Verificar desbordamientos
balanceOf[msg.sender] -= _value; // Reste del remitente
balanceOf[_to] += _value; // Agregue lo mismo al destinatario
}
/* Esta función sin nombre se llama cada vez que alguien intenta enviar éter a ella */
function () {
throw; // Evita el envío accidental de éter
}
} | transfer | function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw; // Compruebe si el remitente tiene suficiente
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Verificar desbordamientos
balanceOf[msg.sender] -= _value; // Reste del remitente
balanceOf[_to] += _value; // Agregue lo mismo al destinatario
}
| /* Send coins */ | Comment | v0.4.19+commit.c4cbbb05 | bzzr://2bb40ed958008e5bbe69da40c3b5da723d2539387782f8a45ee0dd3e5e3eb1b4 | {
"func_code_index": [
937,
1387
]
} | 3,706 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.