file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
|---|---|---|---|
./partial_match/42/0x0dAAe03aaEe84B5c5BeBD3B0f8ccb539C1A5463E/sources/FeePool.sol
|
Record the reward payment in our recentFeePeriods. periAmount The amount of PERI tokens./ Don't assign to the parameter Start at the oldest period and record the amount, moving to newer periods until we've exhausted the amount. The condition checks for overflow because we're going to 0 with an unsigned int. Take the smaller of the amount left to claim in the period and the amount we need to allocate No need to continue iterating if we've recorded the whole amount; We've exhausted feePeriods to distribute and no rewards remain in last period User last to claim would in this scenario have their remainder slashed due to rounding up of PreciseDecimal
|
function _recordRewardPayment(uint periAmount) internal returns (uint) {
uint remainingToAllocate = periAmount;
uint rewardPaid;
for (uint i = FEE_PERIOD_LENGTH - 1; i < FEE_PERIOD_LENGTH; i--) {
uint toDistribute = _recentFeePeriodsStorage(i).rewardsToDistribute.sub(
_recentFeePeriodsStorage(i).rewardsClaimed
);
if (toDistribute > 0) {
uint amountInPeriod = toDistribute < remainingToAllocate ? toDistribute : remainingToAllocate;
_recentFeePeriodsStorage(i).rewardsClaimed = _recentFeePeriodsStorage(i).rewardsClaimed.add(amountInPeriod);
remainingToAllocate = remainingToAllocate.sub(amountInPeriod);
rewardPaid = rewardPaid.add(amountInPeriod);
if (remainingToAllocate == 0) return rewardPaid;
if (i == 0 && remainingToAllocate > 0) {
remainingToAllocate = 0;
}
}
}
return rewardPaid;
}
| 3,330,604
|
./full_match/3/0x920dBE12da8CF312518E9Fed97241A5Df95286bC/sources/home/arachnid/Dropbox/projects/enssec/contracts/algorithms/EllipticCurve.sol
|
Transform affine coordinates into projective coordinates./
|
function toProjectivePoint(uint x0, uint y0) public pure
returns (uint[3] memory P)
{
P[2] = addmod(0, 1, p);
P[0] = mulmod(x0, P[2], p);
P[1] = mulmod(y0, P[2], p);
}
| 8,182,530
|
/**
*Submitted for verification at Etherscan.io on 2020-11-09
*/
pragma solidity ^0.6.6;
//SPDX-License-Identifier: UNLICENSED
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract Owned {
address public owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
emit OwnershipTransferred(owner, newOwner);
}
}
}
// ----------------------------------------------------------------------------
//Tokenlock trade
// ----------------------------------------------------------------------------
contract Tokenlock is Owned {
uint8 isLocked = 0;
event Freezed();
event UnFreezed();
modifier validLock {
require(isLocked == 0);
_;
}
function freeze() public onlyOwner {
isLocked = 1;
emit Freezed();
}
function unfreeze() public onlyOwner {
isLocked = 0;
emit UnFreezed();
}
mapping(address => bool) blacklist;
event LockUser(address indexed who);
event UnlockUser(address indexed who);
modifier permissionCheck {
require(!blacklist[msg.sender]);
_;
}
function lockUser(address who) public onlyOwner {
blacklist[who] = true;
emit LockUser(who);
}
function unlockUser(address who) public onlyOwner {
blacklist[who] = false;
emit UnlockUser(who);
}
}
contract Timi is Tokenlock {
using SafeMath for uint;
string public name = "Timi Finance";
string public symbol = "Timi";
uint8 public decimals = 18;
uint internal _rate=100;
uint internal _amount;
uint256 public totalSupply;
//bank
mapping(address => uint) bank_balances;
//eth
mapping(address => uint) activeBalances;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Transfer(address indexed _from, address indexed _to, uint256 value);
event Burn(address indexed _from, uint256 value);
// Called when new token are issued
event Issue(uint amount);
// Called when tokens are redeemed
event Redeem(uint amount);
//Called when sent
event Sent(address from, address to, uint amount);
event FallbackCalled(address sent, uint amount);
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
require(!(msg.data.length < size + 4));
_;
}
constructor (uint totalAmount) public{
totalSupply = totalAmount * 10**uint256(decimals);
balances[msg.sender] = totalSupply;
emit Transfer(address(0), msg.sender, totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
/* function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}*/
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOfBank(address tokenOwner) public view returns (uint balance) {
return bank_balances[tokenOwner];
}
function balanceOfReg(address tokenOwner) public view returns (uint balance) {
return activeBalances[tokenOwner];
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Issue a new amount of tokens
// these tokens are deposited into the owner address
// @param _amount Number of tokens to be issued
// ------------------------------------------------------------------------
function issue(uint amount) public onlyOwner {
require(totalSupply + amount > totalSupply);
require(balances[owner] + amount > balances[owner]);
balances[owner] += amount;
totalSupply += amount;
emit Issue(amount);
}
// ------------------------------------------------------------------------
// Redeem tokens.
// These tokens are withdrawn from the owner address
// if the balance must be enough to cover the redeem
// or the call will fail.
// @param _amount Number of tokens to be issued
// ------------------------------------------------------------------------
function redeem(uint amount) public onlyOwner {
require(totalSupply >= amount);
require(balances[owner] >= amount);
totalSupply -= amount;
balances[owner] -= amount;
emit Redeem(amount);
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public validLock permissionCheck onlyPayloadSize(2 * 32) returns (bool success) {
require(to != address(0));
require(balances[msg.sender] >= tokens && tokens > 0);
require(balances[to] + tokens >= balances[to]);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public validLock permissionCheck onlyPayloadSize(3 * 32) returns (bool success) {
require(to != address(0));
require(balances[from] >= tokens && tokens > 0);
require(balances[to] + tokens >= balances[to]);
balances[from] = balances[from].sub(tokens);
if(allowed[from][msg.sender] > 0)
{
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
}
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferStore(address from, address to, uint tokens) public validLock permissionCheck onlyPayloadSize(3 * 32) returns (bool success) {
require(to != address(0));
require(balances[from] >= tokens && tokens > 0);
require(balances[to] + tokens >= balances[to]);
balances[from] = balances[from].sub(tokens);
if(allowed[from][msg.sender] > 0)
{
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
}
balances[to] = balances[to].add(tokens);
bank_balances[from] = bank_balances[from].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner {
// return ERC20Interface(tokenAddress).transfer(owner, tokens);
address(uint160(tokenAddress)).transfer(0);
emit Sent(owner,tokenAddress,tokens);
}
// ------------------------------------------------------------------------
// ERC20 withdraw
// -----------------------------------------
function withdraw() onlyOwner public {
msg.sender.transfer(0);
_amount = 0;
}
function showAmount() onlyOwner public view returns (uint) {
return _amount;
}
function showBalance() onlyOwner public view returns (uint) {
return owner.balance;
}
// ------------------------------------------------------------------------
// ERC20 set rate
// -----------------------------------------
function set_rate(uint _vlue) public onlyOwner{
require(_vlue > 0);
_rate = _vlue;
}
// ------------------------------------------------------------------------
// ERC20 tokens
// -----------------------------------------
receive() external payable{ //injected LOCKED ETHER
/* require(balances[owner] >= msg.value && msg.value > 0);
balances[msg.sender] = balances[msg.sender].add(msg.value * _rate);
balances[owner] = balances[owner].sub(msg.value * _rate); */
_amount=_amount.add(msg.value);
activeBalances[msg.sender] = activeBalances[msg.sender].add(msg.value);
}
// ------------------------------------------------------------------------
// ERC20 recharge
// -----------------------------------------
function recharge() public payable{ //injected LOCKED ETHER
_amount=_amount.add(msg.value);
activeBalances[msg.sender] = activeBalances[msg.sender].add(msg.value);
}
}
|
------------------------------------------------------------------------ Owner can transfer out any accidentally sent ERC20 tokens ------------------------------------------------------------------------ return ERC20Interface(tokenAddress).transfer(owner, tokens);
|
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner {
address(uint160(tokenAddress)).transfer(0);
emit Sent(owner,tokenAddress,tokens);
}
| 973,244
|
// SPDX-License-Identifier: MIT
pragma solidity >= 0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
/// Simply a rock-paper-scissors game with a commitment scheme to avoid front-running attacks.
/// 1 (FUNDING state). Both players must first fund the game with the agreedStake amount
/// 2 (COMMITMENT state). Then they will commit to their action ("ROCK", "PAPER" or "SCISSORS")
/// 3 (REVEAL state). When both have committed, they will reveal their action and the winner is designated.
/// In the case of a draw, goto 2.
/// 4 (WON state). The winner can withdraw his prise.
/// 5 (FINISHED state). The owner can kill the contract, any remaining funds are sent to the owner.
contract RockPaperScissors is Ownable {
enum GameState {FUNDING, COMMITMENT, REVEAL, WON, FINISHED, STALLED}
GameState public currentState = GameState.FUNDING;
address public immutable player1;
address public immutable player2;
address public winner;
uint256 public immutable agreedStake;
uint256 public immutable creationTime;
struct PlayerState {
uint stake;
bytes32 commitment;
string action;
}
mapping (address => PlayerState) public playerStates;
event GameStart(address player1, address player2, uint256 stake);
event PlayerCommitted(address player);
event PlayerRevealed(address player);
event Liar(address player);
event Draw(string action);
event Winner(address winner);
bytes32 public constant ROCK = keccak256(abi.encodePacked("ROCK"));
bytes32 public constant PAPER = keccak256(abi.encodePacked("PAPER"));
bytes32 public constant SCISSORS = keccak256(abi.encodePacked("SCISSORS"));
constructor(address _player1, address _player2, uint256 _agreedStake) {
require(_player1 != address(0) && _player2 != address(0), "Invalid player address (0x0)");
creationTime = block.timestamp;
// Limit the amount at stake, otherwise withdraw() could overflow and revert, and winner never gets paid
uint maxStake;
unchecked {
maxStake = (uint256(0)-1)/2;
}
require(_agreedStake <= maxStake, "Too much at stake");
player1 = _player1;
player2 = _player2;
agreedStake = _agreedStake;
PlayerState memory newPlayer = PlayerState(0, "0x0", "");
playerStates[_player1] = newPlayer;
playerStates[_player2] = newPlayer;
}
modifier onlyPlayers() {
require(msg.sender == player1 || msg.sender == player2, "Non players cannot interact with the game.");
_;
}
modifier stateCheck(GameState _state) {
require(currentState == _state, "Please check the state of the game");
_;
}
// Players have 1 week to go through the COMMITMENT and REVEAL states, after this time
// they can get back their amount at stake
modifier stateCheckWithStall(GameState _state) {
require(currentState == _state ||
currentState == GameState.STALLED ||
block.timestamp > creationTime + 1 weeks,
"Either it is too soon or the game is not finished.");
_;
}
modifier actionIsValid(bytes32 _action) {
require(_action == ROCK ||
_action == PAPER ||
_action == SCISSORS,
"Your action is invalid: choose between ROCK, PAPER and SCISSORS");
_;
}
/// @notice both players must put the amount at stake in the contract
function fundGame() external payable onlyPlayers stateCheck(GameState.FUNDING) {
require(msg.value == agreedStake, "The amount must correspond to the agreed stake.");
require(playerStates[msg.sender].stake == 0, "You already sent your money.");
playerStates[msg.sender].stake = msg.value;
// Lock fundings when both players have put amounts at stake
if (playerStates[player1].stake == agreedStake && playerStates[player2].stake == agreedStake) {
emit GameStart(player1, player2, agreedStake);
currentState = GameState.COMMITMENT;
}
}
/// @notice during the FUNDING phase, the players still can withdraw their funds
function unfundGame() external onlyPlayers stateCheck(GameState.FUNDING) {
uint refundAmount = playerStates[msg.sender].stake;
playerStates[msg.sender].stake = 0;
payable(msg.sender).transfer(refundAmount);
}
/// @notice after the FUNDING phase, each player will commit to his action
function commitToAction(bytes32 _playerCommitment) external onlyPlayers stateCheck(GameState.COMMITMENT) {
require(playerStates[msg.sender].commitment == bytes32("0x0"), "You already committed.");
// Store player commitment
playerStates[msg.sender].commitment = _playerCommitment;
emit PlayerCommitted(msg.sender);
if (playerStates[player1].commitment != bytes32("0x0") && playerStates[player2].commitment != bytes32("0x0")) {
// Go to next state when both committed
currentState = GameState.REVEAL;
}
}
/// @notice after the COMMITMENT phase, each player will reveal his action, the commitment value is checked, and
/// the battle ends with a winner, or a draw
function reveal(string calldata _action) external onlyPlayers stateCheck(GameState.REVEAL) actionIsValid(keccak256(abi.encodePacked(_action))) {
if (keccak256(abi.encodePacked(_action)) != playerStates[msg.sender].commitment) {
// If a player lies on his action, he loses immediately
emit Liar(msg.sender);
if (msg.sender == player1) {
winner = player2;
} else {
winner = player1;
}
currentState = GameState.WON;
emit Winner(winner);
return;
}
playerStates[msg.sender].action = _action;
bytes32 emptyString = keccak256(abi.encodePacked(""));
bytes32 action1 = keccak256(abi.encodePacked(playerStates[player1].action));
bytes32 action2 = keccak256(abi.encodePacked(playerStates[player2].action));
emit PlayerRevealed(msg.sender);
if (action1 != emptyString && action2 != emptyString) {
// Both players revealed, time to find the winner
if (action1 == action2) {
// In case of a draw, undo commitment and action
// and revert to COMMITMENT state
playerStates[player1].commitment = bytes32("0x0");
playerStates[player2].commitment = bytes32("0x0");
playerStates[player1].action = "";
playerStates[player2].action = "";
currentState = GameState.COMMITMENT;
emit Draw(_action);
} else {
if (action1 == ROCK) {
if (action2 == PAPER) {
winner = player2;
} else {
winner = player1;
}
} else if (action1 == PAPER) {
if (action2 == ROCK) {
winner = player1;
} else {
winner = player2;
}
} else {
// action1 == SCISSORS
if (action2 == ROCK) {
winner = player2;
} else {
winner = player1;
}
}
currentState = GameState.WON;
emit Winner(winner);
}
}
}
/// @notice once the winner is designated, the winner can withdraw the prize
function withdraw() external stateCheck(GameState.WON) {
playerStates[player1].stake = 0;
playerStates[player2].stake = 0;
currentState = GameState.FINISHED;
payable(winner).transfer(2*agreedStake);
}
/// @notice if the game is stalled (one of the players does not reveal) for more thant a week
/// the players are allowed to get back their stakes
function withdrawForStall() external onlyPlayers stateCheckWithStall(GameState.REVEAL) {
playerStates[msg.sender].stake = 0;
currentState = GameState.STALLED;
if (playerStates[player1].stake == 0 && playerStates[player2].stake == 0) {
currentState = GameState.FINISHED;
}
payable(msg.sender).transfer(agreedStake);
}
/// @notice no locked ether
function withdrawSurplus() external onlyOwner stateCheck(GameState.FINISHED) {
payable(owner()).transfer(address(this).balance);
}
}
/// Fabric for rock-paper-scissors games
/// nothing to see here
contract RockPaperScissorsFabric is Ownable {
function newGame(address _player1, address _player2, uint256 _agreedStake) external onlyOwner returns(address) {
RockPaperScissors newRPS = new RockPaperScissors(_player1, _player2, _agreedStake);
return address(newRPS);
}
function killGame(address _gameAddress) external onlyOwner {
RockPaperScissors rps = RockPaperScissors(_gameAddress);
rps.withdrawSurplus();
}
function withdraw(uint256 _amount) external onlyOwner {
require(_amount <= address(this).balance);
payable(msg.sender).transfer(_amount);
}
fallback() external payable {}
}
|
after the COMMITMENT phase, each player will reveal his action, the commitment value is checked, and the battle ends with a winner, or a draw If a player lies on his action, he loses immediately Both players revealed, time to find the winner In case of a draw, undo commitment and action and revert to COMMITMENT state action1 == SCISSORS
|
function reveal(string calldata _action) external onlyPlayers stateCheck(GameState.REVEAL) actionIsValid(keccak256(abi.encodePacked(_action))) {
if (keccak256(abi.encodePacked(_action)) != playerStates[msg.sender].commitment) {
emit Liar(msg.sender);
if (msg.sender == player1) {
winner = player2;
winner = player1;
}
currentState = GameState.WON;
emit Winner(winner);
return;
}
playerStates[msg.sender].action = _action;
bytes32 emptyString = keccak256(abi.encodePacked(""));
bytes32 action1 = keccak256(abi.encodePacked(playerStates[player1].action));
bytes32 action2 = keccak256(abi.encodePacked(playerStates[player2].action));
emit PlayerRevealed(msg.sender);
if (action1 != emptyString && action2 != emptyString) {
if (action1 == action2) {
playerStates[player1].commitment = bytes32("0x0");
playerStates[player2].commitment = bytes32("0x0");
playerStates[player1].action = "";
playerStates[player2].action = "";
currentState = GameState.COMMITMENT;
emit Draw(_action);
if (action1 == ROCK) {
if (action2 == PAPER) {
winner = player2;
winner = player1;
}
if (action2 == ROCK) {
winner = player1;
winner = player2;
}
if (action2 == ROCK) {
winner = player2;
winner = player1;
}
}
currentState = GameState.WON;
emit Winner(winner);
}
}
}
| 12,756,215
|
//Address: 0x8a98cf91fd2ea825a187e4ceaf3490c8a71d8d73
//Contract name: MowjowBounty
//Balance: 0 Ether
//Verification Date: 12/29/2017
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Destructible
* @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner.
*/
contract Destructible is Ownable {
function Destructible() public payable { }
/**
* @dev Transfers the current balance to the owner and terminates the contract.
*/
function destroy() onlyOwner public {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) onlyOwner public {
selfdestruct(_recipient);
}
}
/**
* @title PullPayment
* @dev Base contract supporting async send for pull payments. Inherit from this
* contract and use asyncSend instead of send.
*/
contract PullPayment {
using SafeMath for uint256;
mapping(address => uint256) public payments;
uint256 public totalPayments;
/**
* @dev Called by the payer to store the sent amount as credit to be pulled.
* @param dest The destination address of the funds.
* @param amount The amount to transfer.
*/
function asyncSend(address dest, uint256 amount) internal {
payments[dest] = payments[dest].add(amount);
totalPayments = totalPayments.add(amount);
}
/**
* @dev withdraw accumulated balance, called by payee.
*/
function withdrawPayments() public {
address payee = msg.sender;
uint256 payment = payments[payee];
require(payment != 0);
require(this.balance >= payment);
totalPayments = totalPayments.sub(payment);
payments[payee] = 0;
assert(payee.send(payment));
}
}
/**
* @title Bounty
* @dev This bounty will pay out to a researcher if they break invariant logic of the contract.
*/
contract Bounty is PullPayment, Destructible {
bool public claimed;
mapping(address => address) public researchers;
event TargetCreated(address createdAddress);
/**
* @dev Fallback function allowing the contract to receive funds, if they haven't already been claimed.
*/
function() external payable {
require(!claimed);
}
/**
* @dev Create and deploy the target contract (extension of Target contract), and sets the
* msg.sender as a researcher
* @return A target contract
*/
function createTarget() public returns(Target) {
Target target = Target(deployContract());
researchers[target] = msg.sender;
TargetCreated(target);
return target;
}
/**
* @dev Internal function to deploy the target contract.
* @return A target contract address
*/
function deployContract() internal returns(address);
/**
* @dev Sends the contract funds to the researcher that proved the contract is broken.
* @param target contract
*/
function claim(Target target) public {
address researcher = researchers[target];
require(researcher != 0);
// Check Target contract invariants
require(!target.checkInvariant());
asyncSend(researcher, this.balance);
claimed = true;
}
}
/**
* @title Target
* @dev Your main contract should inherit from this class and implement the checkInvariant method.
*/
contract Target {
/**
* @dev Checks all values a contract assumes to be true all the time. If this function returns
* false, the contract is broken in some way and is in an inconsistent state.
* In order to win the bounty, security researchers will try to cause this broken state.
* @return True if all invariant values are correct, false otherwise.
*/
function checkInvariant() public returns(bool);
}
/*
* @title PricingStrategy
* An abstract class for all Pricing Strategy contracts.
*/
contract PricingStrategy is Ownable {
/*
* @dev Number sold tokens for current strategy
*/
uint256 public totalSoldTokens = 0;
uint256 public weiRaised = 0;
/*
* @dev Count number of tokens with bonuses
* @param _value uint256 Value in ether from investor
* @return uint256 Return number of tokens for investor
*/
function countTokens(uint256 _value) internal returns (uint256 tokensAndBonus);
/*
* @dev Summing sold of tokens
* @param _tokensAndBonus uint256 Number tokens for current sale in a tranche
*/
function soldInTranche(uint256 _tokensAndBonus) internal;
/*
* @dev Check required of tokens in the tranche
* @param _requiredTokens uint256 Number required of tokens
* @return boolean Return true if count of tokens is available
*/
function getFreeTokensInTranche(uint256 _requiredTokens) internal constant returns (bool);
function isNoEmptyTranches() public constant returns(bool);
}
contract TranchePricingStrategy is PricingStrategy, Target {
using SafeMath for uint256;
uint256 public tokensCap;
uint256 public capInWei;
/*
* Define bonus schedule of tranches.
*/
struct BonusSchedule {
uint256 bonus; // Bonus rate for current tranche
uint valueForTranche; // Amount of tokens available for the current period
uint rate; // How much tokens for one ether
}
//event for testing
event TokenForInvestor(uint256 _token, uint256 _tokenAndBonus, uint256 indexOfperiod);
uint tranchesCount = 0;
uint MAX_TRANCHES = 50;
//Store BonusStrategy in a fixed array, so that it can be seen in a blockchain explorer
BonusSchedule[] public tranches;
/*
* @dev Constructor
* @param _bonuses uint256[] Bonuses in tranches
* @param _valueForTranches uint[] Value of tokens in tranches
* @params _rates uint[] Rates for tranches
*/
function TranchePricingStrategy(uint256[] _bonuses, uint[] _valueForTranches, uint[] _rates,
uint256 _capInWei, uint256 _tokensCap) public {
tokensCap = _tokensCap;
capInWei = _capInWei;
require(_bonuses.length == _valueForTranches.length && _valueForTranches.length == _rates.length);
require(_bonuses.length <= MAX_TRANCHES);
tranchesCount = _bonuses.length;
for (uint i = 0; i < _bonuses.length; i++) {
tranches.push(BonusSchedule({
bonus: _bonuses[i],
valueForTranche: _valueForTranches[i],
rate: _rates[i]
}));
}
}
/*
* @dev Count number of tokens with bonuses
* @param _value uint256 Value in ether
* @return uint256 Return number of tokens for an investor
*/
function countTokens(uint256 _value) internal returns (uint256 tokensAndBonus) {
uint256 indexOfTranche = defineTranchePeriod();
require(indexOfTranche != MAX_TRANCHES + 1);
BonusSchedule currentTranche = tranches[indexOfTranche];
uint256 etherInWei = 1e18;
uint256 bonusRate = currentTranche.bonus;
uint val = msg.value * etherInWei;
uint256 oneTokenInWei = etherInWei/currentTranche.rate;
uint tokens = val / oneTokenInWei;
uint256 bonusToken = tokens.mul(bonusRate).div(100);
tokensAndBonus = tokens.add(bonusToken);
soldInTranche(tokensAndBonus);
weiRaised += _value;
TokenForInvestor(tokens, tokensAndBonus, indexOfTranche);
return tokensAndBonus;
}
/*
* @dev Check required of tokens in the tranche
* @param _requiredTokens uint256 Number of tokens
* @return boolean Return true if count of tokens is available
*/
function getFreeTokensInTranche(uint256 _requiredTokens) internal constant returns (bool) {
bool hasTokens = false;
uint256 indexOfTranche = defineTranchePeriod();
hasTokens = tranches[indexOfTranche].valueForTranche > _requiredTokens;
return hasTokens;
}
/*
* @dev Summing sold of tokens
* @param _tokensAndBonus uint256 Number tokens for current sale
*/
function soldInTranche(uint256 _tokensAndBonus) internal {
uint256 indexOfTranche = defineTranchePeriod();
require(tranches[indexOfTranche].valueForTranche >= _tokensAndBonus);
tranches[indexOfTranche].valueForTranche = tranches[indexOfTranche].valueForTranche.sub(_tokensAndBonus);
totalSoldTokens = totalSoldTokens.add(_tokensAndBonus);
}
/*
* @dev Check sum of the tokens for sale in the tranches in the crowdsale time
*/
function isNoEmptyTranches() public constant returns(bool) {
uint256 sumFreeTokens = 0;
for (uint i = 0; i < tranches.length; i++) {
sumFreeTokens = sumFreeTokens.add(tranches[i].valueForTranche);
}
bool isValid = sumFreeTokens > 0;
return isValid;
}
/*
* @dev get index of tranche
* @return uint256 number of current tranche in array tranches
*/
function defineTranchePeriod() internal constant returns (uint256) {
for (uint256 i = 0; i < tranches.length; i++) {
if (tranches[i].valueForTranche > 0) {
return i;
}
}
return MAX_TRANCHES + 1;
}
/* Now we have the Bounty code, as the contract is Bounty.
* @dev Function to check if the contract has been compromised.
*/
function checkInvariant() public returns(bool) {
uint256 tranchePeriod = defineTranchePeriod();
bool isTranchesDone = tranchePeriod == MAX_TRANCHES + 1;
bool isTokensCapReached = tokensCap == totalSoldTokens;
bool isWeiCapReached = weiRaised == capInWei;
bool isNoCapReached = isTranchesDone &&
(!isTokensCapReached || !isWeiCapReached);
bool isExceededCap = !isTranchesDone &&
(isTokensCapReached || isWeiCapReached);
// Check the compromised flag.
if (isNoCapReached || isExceededCap) {
return false;
}
return true;
}
function payContract() payable {
countTokens(msg.value);
}
}
contract MowjowBounty is Bounty {
uint256[] public rates;
uint256[] public bonuses;
uint256[] public valueForTranches;
uint256 capInWei;
uint256 capInTokens;
function MowjowBounty (uint256[] _bonuses, uint256[] _valueForTranches,
uint256[] _rates, uint256 _capInWei, uint256 _capInTokens) public {
bonuses = _bonuses;
valueForTranches = _valueForTranches;
rates = _rates;
capInWei = _capInWei;
capInTokens = _capInTokens;
}
function deployContract() internal returns(address) {
return new TranchePricingStrategy(bonuses, valueForTranches, rates, capInWei, capInTokens);
}
}
|
Internal function to deploy the target contract. return A target contract address/ Sends the contract funds to the researcher that proved the contract is broken. target contract/ Check Target contract invariants
|
function deployContract() internal returns(address);
function claim(Target target) public {
address researcher = researchers[target];
require(researcher != 0);
require(!target.checkInvariant());
asyncSend(researcher, this.balance);
claimed = true;
}
| 5,479,743
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
import "./interfaces/IRewardManager.sol";
/**
* @title Reward Manager
* @author JaboiNads
* @notice Responsible for tracking and distributing rewards
*/
contract RewardManager is OwnableUpgradeable, ERC165Upgradeable, IRewardManager {
// The token to manage shared rewards for.
IERC721EnumerableUpgradeable private _token;
// The maximum reward potential for each token.
uint256 private _sharedRewardPotential;
// Maps a token to the reward potential the last time rewards were claimed.
mapping(uint256 => uint256) private _lastClaimedSharedRewardPotential;
// Maps an address to its unclaimed personal reward.
mapping(address => uint256) private _unclaimedPersonalRewards;
/**
* @notice Emitted when a shared reward is deposited.
* @param amount The reward amount distributed to each holders.
*/
event SharedRewardReceived(
address indexed sender,
uint256 amount
);
/**
* @notice Emitted when a personal reward is deposited.
* @param recipient The address that received the reward.
* @param amount The reward amount that was received.
*/
event PersonalRewardReceived(
address indexed sender,
address indexed recipient,
uint256 amount
);
/**
* @notice Emitted when rewards are claimed.
* @param recipient The address that claimed the rewards.
* @param amount The amount that was claimed.
*/
event RewardsReleased(
address indexed recipient,
uint256 amount
);
function initialize(
IERC721EnumerableUpgradeable token
) external initializer {
__Ownable_init();
__RewardsManager_init_unchained(token);
}
// solhint-disable-next-line func-name-mixedcase
function __RewardsManager_init_unchained(
IERC721EnumerableUpgradeable token
) internal onlyInitializing {
require(token.supportsInterface(type(IERC721EnumerableUpgradeable).interfaceId), "not ERC721Enumerable");
_token = token;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IRewardManager).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @notice Initializes a token with the reward manager.
* @param tokenId The id of the token.
*/
function initializeToken(
uint256 tokenId
) external {
require(_msgSender() == address(_token), "unauthorized sender");
require(_lastClaimedSharedRewardPotential[tokenId] == 0, "token already initialized");
_lastClaimedSharedRewardPotential[tokenId] = _sharedRewardPotential;
}
/**
* @notice Deposits a reward that is evenly distributed to all registered holders.
*/
function depositSharedReward() external payable {
require(msg.value > 0, "no reward provided");
uint256 supply = _token.totalSupply();
require(supply > 0, "no token supply exists");
uint256 reward = msg.value / supply;
_sharedRewardPotential += reward;
emit SharedRewardReceived(_msgSender(), reward);
}
/**
* @notice Deposits a reward that is given to the specified recipient.
* @param recipient The receiver of the reward.
*/
function depositPersonalReward(
address recipient
) external payable {
require(msg.value > 0, "no reward provided");
require(recipient != address(0), "cannot reward zero-address");
_unclaimedPersonalRewards[recipient] += msg.value;
emit PersonalRewardReceived(_msgSender(), recipient, msg.value);
}
/**
* @notice Releases all unclaimed rewards for the caller.
* @return reward The amount of reward that was claimed.
*/
function release() external returns (uint256 reward) {
// Claim all pending personal rewards.
reward = _unclaimedPersonalRewards[_msgSender()];
_unclaimedPersonalRewards[_msgSender()] = 0;
// Claim rewards for all held tokens.
uint256 numTokens = _token.balanceOf(_msgSender());
for (uint256 i = 0; i < numTokens; i++) {
uint256 tokenId = _token.tokenOfOwnerByIndex(_msgSender(), i);
// Claim pending rewards for the token.
reward += _sharedRewardPotential - _lastClaimedSharedRewardPotential[tokenId];
_lastClaimedSharedRewardPotential[tokenId] = _sharedRewardPotential;
}
// Transfer the calculated rewards to the sender.
AddressUpgradeable.sendValue(payable(_msgSender()), reward);
// Notify the world that rewards were released.
emit RewardsReleased(_msgSender(), reward);
}
function calculateAvailableRewards(
address recipient
) external view returns (uint256 reward) {
// Claim all pending personal rewards.
reward = _unclaimedPersonalRewards[recipient];
// Calculate rewards for all held tokens.
uint256 numTokens = _token.balanceOf(recipient);
for (uint256 i = 0; i < numTokens; i++) {
uint256 tokenId = _token.tokenOfOwnerByIndex(recipient, i);
reward += _sharedRewardPotential - _lastClaimedSharedRewardPotential[tokenId];
}
}
}
|
solhint-disable-next-line func-name-mixedcase
|
function __RewardsManager_init_unchained(
IERC721EnumerableUpgradeable token
) internal onlyInitializing {
require(token.supportsInterface(type(IERC721EnumerableUpgradeable).interfaceId), "not ERC721Enumerable");
_token = token;
}
| 14,070,131
|
pragma solidity ^0.4.23;
contract Ownable {
address public owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_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;
}
}
contract Mortal is Ownable{
uint public stopTS;
uint public minimumWait = 1 hours;
bool public killed;
/**
* keep people from joining games or initiating new ones
* */
function stopPlaying() public onlyOwner{
stopTS = now;
}
/**
* kills the contract if enough time has passed. time to pass = twice the waiting time for withdrawal of funds of a running game.
* */
function kill() public onlyOwner{
require(stopTS > 0 && stopTS + 2 * minimumWait <= now, "before killing, playing needs to be stopped and sufficient time has to pass");
selfdestruct(owner);
}
/**
* like killing, because playing will no longer be possible and funds are withdrawn, but keeps the data available on the blockchain
* (especially scores)
* */
function permaStop() public onlyOwner{
require(stopTS > 0 && stopTS + 2 * minimumWait <= now, "before killing, playing needs to be stopped and sufficient time has to pass");
killed = true;
owner.transfer(address(this).balance);
}
/**
* resume playing. stops the killing preparation.
* */
function resumePlaying() public onlyOwner{
require(!killed, "killed contract cannot be reactivated");
stopTS = 0;
}
/**
* don't allow certain functions if playing has been stopped
* */
modifier active(){
require(stopTS == 0, "playing has been stopped by the owner");
_;
}
}
contract Administrable is Mortal{
/** the different pots */
uint public charityPot;
uint public highscorePot;
uint public affiliatePot;
uint public surprisePot;
uint public developerPot;
/** the Percentage of the game stake which go into a pot with one decimal (25 => 2.5%) */
uint public charityPercent = 25;
uint public highscorePercent = 50;
uint public affiliatePercent = 50;
uint public surprisePercent = 25;
uint public developerPercent = 50;
uint public winnerPercent = 800;
/** the current highscore holder **/
address public highscoreHolder;
address public signer;
/** balance of affiliate partners */
mapping (address => uint) public affiliateBalance;
/** tells if a hash has already been used for withdrawal **/
mapping (bytes32 => bool) public used;
event Withdrawal(uint8 pot, address receiver, uint value);
modifier validAddress(address receiver){
require(receiver != 0x0, "invalid receiver");
_;
}
/**
* set the minimum waiting time for withdrawal of funds of a started but not-finished game
* */
function setMinimumWait(uint newMin) public onlyOwner{
minimumWait = newMin;
}
/**
* withdraw from the developer pot
* */
function withdrawDeveloperPot(address receiver) public onlyOwner validAddress(receiver){
uint value = developerPot;
developerPot = 0;
receiver.transfer(value);
emit Withdrawal(0, receiver, value);
}
/**
* withdraw from the charity pot
* */
function donate(address charity) public onlyOwner validAddress(charity){
uint value = charityPot;
charityPot = 0;
charity.transfer(value);
emit Withdrawal(1, charity, value);
}
/**
* withdraw from the highscorePot
* */
function withdrawHighscorePot(address receiver) public validAddress(receiver){
require(msg.sender == highscoreHolder);
uint value = highscorePot;
highscorePot = 0;
receiver.transfer(value);
emit Withdrawal(2, receiver, value);
}
/**
* withdraw from the affiliate pot
* */
function withdrawAffiliateBalance(address receiver) public validAddress(receiver){
uint value = affiliateBalance[msg.sender];
require(value > 0);
affiliateBalance[msg.sender] = 0;
receiver.transfer(value);
emit Withdrawal(3, receiver, value);
}
/**
* withdraw from the surprise pot
* */
function withdrawSurprisePot(address receiver) public onlyOwner validAddress(receiver){
uint value = surprisePot;
surprisePot = 0;
receiver.transfer(value);
emit Withdrawal(4, receiver, value);
}
/**
* allows an user to withdraw from the surprise pot with a valid signature
* */
function withdrawSurprisePotUser(uint value, uint expiry, uint8 v, bytes32 r, bytes32 s) public{
require(expiry >= now, "signature expired");
bytes32 hash = keccak256(abi.encodePacked(msg.sender, value, expiry));
require(!used[hash], "same signature was used before");
require(ecrecover(hash, v, r, s) == signer, "invalid signer");
require(value <= surprisePot, "not enough in the pot");
surprisePot -= value;
used[hash] = true;
msg.sender.transfer(value);
emit Withdrawal(4, msg.sender, value);
}
/**
* sets the signing address
* */
function setSigner(address signingAddress) public onlyOwner{
signer = signingAddress;
}
/**
* sets the pot Percentages
* */
function setPercentages(uint affiliate, uint charity, uint dev, uint highscore, uint surprise) public onlyOwner{
uint sum = affiliate + charity + highscore + surprise + dev;
require(sum < 500, "winner should not lose money");
charityPercent = charity;
affiliatePercent = affiliate;
highscorePercent = highscore;
surprisePercent = surprise;
developerPercent = dev;
winnerPercent = 1000 - sum;
}
}
contract Etherman is Administrable{
struct game{
uint32 timestamp;
uint128 stake;
address player1;
address player2;
}
struct player{
uint8 team;
uint64 score;
address referrer;
}
mapping (bytes32 => game) public games;
mapping (address => player) public players;
event NewGame(bytes32 gameId, address player1, uint stake);
event GameStarted(bytes32 gameId, address player1, address player2, uint stake);
event GameDestroyed(bytes32 gameId);
event GameEnd(bytes32 gameId, address winner, uint value);
event NewHighscore(address holder, uint score, uint lastPot);
modifier onlyHuman(){
require(msg.sender == tx.origin, "contract calling");
_;
}
constructor(address signingAddress) public{
setSigner(signingAddress);
}
/**
* sets the referrer for the lifetime affiliate program and initiates a new game
* */
function initGameReferred(address referrer, uint8 team) public payable active onlyHuman validAddress(referrer){
//new player which does not have a referrer set yet
if(players[msg.sender].referrer == 0x0 && players[msg.sender].score == 0)
players[msg.sender] = player(team, 0, referrer);
initGame();
}
/**
* sets the team and initiates a game
* */
function initGameTeam(uint8 team) public payable active onlyHuman{
if(players[msg.sender].score == 0)
players[msg.sender].team = team;
initGame();
}
/**
* initiates a new game
* */
function initGame() public payable active onlyHuman{
require(msg.value <= 10 ether, "stake needs to be lower than or equal to 10 ether");
require(msg.value > 1 finney, "stake needs to be at least 1 finney");
bytes32 gameId = keccak256(abi.encodePacked(msg.sender, block.number));
games[gameId] = game(uint32(now), uint128(msg.value), msg.sender, 0x0);
emit NewGame(gameId, msg.sender, msg.value);
}
/**
* sets the referrer for the lifetime affiliate program and joins a game
* */
function joinGameReferred(bytes32 gameId, address referrer, uint8 team) public payable active onlyHuman validAddress(referrer){
//new player which does not have a referrer set yet
if(players[msg.sender].referrer == 0x0 && players[msg.sender].score == 0)
players[msg.sender] = player(team, 0, referrer);
joinGame(gameId);
}
/**
* sets the team and joins a game
* */
function joinGameTeam(bytes32 gameId, uint8 team) public payable active onlyHuman{
if(players[msg.sender].score == 0)
players[msg.sender].team = team;
joinGame(gameId);
}
/**
* join a game
* */
function joinGame(bytes32 gameId) public payable active onlyHuman{
game storage cGame = games[gameId];
require(cGame.player1!=0x0, "game id unknown");
require(cGame.player1 != msg.sender, "cannot play with one self");
require(msg.value >= cGame.stake, "value does not suffice to join the game");
cGame.player2 = msg.sender;
cGame.timestamp = uint32(now);
emit GameStarted(gameId, cGame.player1, msg.sender, cGame.stake);
if(msg.value > cGame.stake) developerPot += msg.value - cGame.stake;
}
/**
* withdraw from the game stake in case no second player joined or the game was not ended within the
* minimum waiting time
* */
function withdraw(bytes32 gameId) public onlyHuman{
game storage cGame = games[gameId];
uint128 value = cGame.stake;
if(msg.sender == cGame.player1){
if(cGame.player2 == 0x0){
delete games[gameId];
msg.sender.transfer(value);
}
else if(cGame.timestamp + minimumWait <= now){
address player2 = cGame.player2;
delete games[gameId];
msg.sender.transfer(value);
player2.transfer(value);
}
else{
revert("minimum waiting time has not yet passed");
}
}
else if(msg.sender == cGame.player2){
if(cGame.timestamp + minimumWait <= now){
address player1 = cGame.player1;
delete games[gameId];
msg.sender.transfer(value);
player1.transfer(value);
}
else{
revert("minimum waiting time has not yet passed");
}
}
else{
revert("sender is not a player in this game");
}
emit GameDestroyed(gameId);
}
/**
* The winner can claim his winnings, only with a signature from the contract owner.
* the pot is distributed amongst the winner, the developers, the affiliate partner, a charity and the surprise pot
* */
function claimWin(bytes32 gameId, uint8 v, bytes32 r, bytes32 s) public onlyHuman{
game storage cGame = games[gameId];
require(cGame.player2!=0x0, "game has not started yet");
require(msg.sender == cGame.player1 || msg.sender == cGame.player2, "sender is not a player in this game");
require(ecrecover(keccak256(abi.encodePacked(gameId, msg.sender)), v, r, s) == signer, "invalid signature");
uint256 value = 2*cGame.stake;
uint256 win = winnerPercent * value / 1000;
addScore(msg.sender, cGame.stake);
delete games[gameId];
charityPot += value * charityPercent / 1000;
//players of the leading team do not pay tributes
if(players[highscoreHolder].team == players[msg.sender].team){
win += value * highscorePercent / 1000;
}
else{
highscorePot += value * highscorePercent / 1000;
}
surprisePot += value * surprisePercent / 1000;
if(players[msg.sender].referrer == 0x0){
developerPot += value * (developerPercent + affiliatePercent) / 1000;
}
else{
developerPot += value * developerPercent / 1000;
affiliateBalance[players[msg.sender].referrer] += value * affiliatePercent / 1000;
}
msg.sender.transfer(win);//no overflow possible because stake is <= max uint128, but now we have 256 bit
emit GameEnd(gameId, msg.sender, win);
}
function addScore(address receiver, uint stake) private{
player storage rec = players[receiver];
player storage hsh = players[highscoreHolder];
if(rec.team == hsh.team){
if(stake < 0.05 ether) rec.score += 1;
else if(stake < 0.5 ether) rec.score += 5;
else rec.score += 10;
}
else{//extra points if not belonging to the highscore team
if(stake < 0.05 ether) rec.score += 2;
else if(stake < 0.5 ether) rec.score += 7;
else rec.score += 13;
}
if(rec.score > hsh.score){
uint pot = highscorePot;
if(pot > 0){
highscorePot = 0;
highscoreHolder.transfer(pot);
}
highscoreHolder = receiver;
emit NewHighscore(receiver, rec.score, pot);
}
}
/**
* any directly sent ETH are considered a donation for development
* */
function() public payable{
developerPot+=msg.value;
}
function doNothing(){
}
}
|
withdraw from the affiliate pot /
|
function withdrawAffiliateBalance(address receiver) public validAddress(receiver){
uint value = affiliateBalance[msg.sender];
require(value > 0);
affiliateBalance[msg.sender] = 0;
receiver.transfer(value);
emit Withdrawal(3, receiver, value);
}
| 2,576,966
|
./full_match/1/0xeF6303006a994f469Ef0FBDe20b269e804adB985/sources/src/Math.sol
|
Calculate x y / scale rounding down./
|
function mulScale(uint256 x, uint256 y, uint128 scale) internal pure returns (uint256) {
uint256 a = x / scale;
uint256 b = x % scale;
uint256 c = y / scale;
uint256 d = y % scale;
return a * c * scale + a * d + b * c + b * d / scale;
}
| 16,403,935
|
// File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
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));
}
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'
// solhint-disable-next-line max-line-length
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).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_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.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @opengsn/gsn/contracts/0x/errors/LibBytesRichErrorsV06.sol
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.2;
library LibBytesRichErrorsV06 {
enum InvalidByteOperationErrorCodes {
FromLessThanOrEqualsToRequired,
ToLessThanOrEqualsLengthRequired,
LengthGreaterThanZeroRequired,
LengthGreaterThanOrEqualsFourRequired,
LengthGreaterThanOrEqualsTwentyRequired,
LengthGreaterThanOrEqualsThirtyTwoRequired,
LengthGreaterThanOrEqualsNestedBytesLengthRequired,
DestinationLengthGreaterThanOrEqualSourceLengthRequired
}
// bytes4(keccak256("InvalidByteOperationError(uint8,uint256,uint256)"))
bytes4 internal constant INVALID_BYTE_OPERATION_ERROR_SELECTOR =
0x28006595;
// solhint-disable func-name-mixedcase
function InvalidByteOperationError(
InvalidByteOperationErrorCodes errorCode,
uint256 offset,
uint256 required
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
INVALID_BYTE_OPERATION_ERROR_SELECTOR,
errorCode,
offset,
required
);
}
}
// File: @opengsn/gsn/contracts/0x/errors/LibRichErrorsV06.sol
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.2;
library LibRichErrorsV06 {
// bytes4(keccak256("Error(string)"))
bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0;
// solhint-disable func-name-mixedcase
/// @dev ABI encode a standard, string revert error payload.
/// This is the same payload that would be included by a `revert(string)`
/// solidity statement. It has the function signature `Error(string)`.
/// @param message The error string.
/// @return The ABI encoded error.
function StandardError(string memory message)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
STANDARD_ERROR_SELECTOR,
bytes(message)
);
}
// solhint-enable func-name-mixedcase
/// @dev Reverts an encoded rich revert reason `errorData`.
/// @param errorData ABI encoded error data.
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
}
// File: @opengsn/gsn/contracts/0x/LibBytesV06.sol
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.2;
library LibBytesV06 {
using LibBytesV06 for bytes;
/// @dev Gets the memory address for a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of byte array. This
/// points to the header of the byte array which contains
/// the length.
function rawAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := input
}
return memoryAddress;
}
/// @dev Gets the memory address for the contents of a byte array.
/// @param input Byte array to lookup.
/// @return memoryAddress Memory address of the contents of the byte array.
function contentAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := add(input, 32)
}
return memoryAddress;
}
/// @dev Copies `length` bytes from memory location `source` to `dest`.
/// @param dest memory address to copy bytes to.
/// @param source memory address to copy bytes from.
/// @param length number of bytes to copy.
function memCopy(
uint256 dest,
uint256 source,
uint256 length
)
internal
pure
{
if (length < 32) {
// Handle a partial word by reading destination and masking
// off the bits we are interested in.
// This correctly handles overlap, zero lengths and source == dest
assembly {
let mask := sub(exp(256, sub(32, length)), 1)
let s := and(mload(source), not(mask))
let d := and(mload(dest), mask)
mstore(dest, or(s, d))
}
} else {
// Skip the O(length) loop when source == dest.
if (source == dest) {
return;
}
// For large copies we copy whole words at a time. The final
// word is aligned to the end of the range (instead of after the
// previous) to handle partial words. So a copy will look like this:
//
// ####
// ####
// ####
// ####
//
// We handle overlap in the source and destination range by
// changing the copying direction. This prevents us from
// overwriting parts of source that we still need to copy.
//
// This correctly handles source == dest
//
if (source > dest) {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because it
// is easier to compare with in the loop, and these
// are also the addresses we need for copying the
// last bytes.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the last 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the last bytes in
// source already due to overlap.
let last := mload(sEnd)
// Copy whole words front to back
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} lt(source, sEnd) {} {
mstore(dest, mload(source))
source := add(source, 32)
dest := add(dest, 32)
}
// Write the last 32 bytes
mstore(dEnd, last)
}
} else {
assembly {
// We subtract 32 from `sEnd` and `dEnd` because those
// are the starting points when copying a word at the end.
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
// Remember the first 32 bytes of source
// This needs to be done here and not after the loop
// because we may have overwritten the first bytes in
// source already due to overlap.
let first := mload(source)
// Copy whole words back to front
// We use a signed comparisson here to allow dEnd to become
// negative (happens when source and dest < 32). Valid
// addresses in local memory will never be larger than
// 2**255, so they can be safely re-interpreted as signed.
// Note: the first check is always true,
// this could have been a do-while loop.
// solhint-disable-next-line no-empty-blocks
for {} slt(dest, dEnd) {} {
mstore(dEnd, mload(sEnd))
sEnd := sub(sEnd, 32)
dEnd := sub(dEnd, 32)
}
// Write the first 32 bytes
mstore(dest, first)
}
}
}
}
/// @dev Returns a slices from a byte array.
/// @param b The byte array to take a slice from.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function slice(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
from,
to
));
}
if (to > b.length) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
to,
b.length
));
}
// Create a new bytes structure and copy contents
result = new bytes(to - from);
memCopy(
result.contentAddress(),
b.contentAddress() + from,
result.length
);
return result;
}
/// @dev Returns a slice from a byte array without preserving the input.
/// When `from == 0`, the original array will match the slice.
/// In other cases its state will be corrupted.
/// @param b The byte array to take a slice from. Will be destroyed in the process.
/// @param from The starting index for the slice (inclusive).
/// @param to The final index for the slice (exclusive).
/// @return result The slice containing bytes at indices [from, to)
function sliceDestructive(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
// Ensure that the from and to positions are valid positions for a slice within
// the byte array that is being used.
if (from > to) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.FromLessThanOrEqualsToRequired,
from,
to
));
}
if (to > b.length) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.ToLessThanOrEqualsLengthRequired,
to,
b.length
));
}
// Create a new bytes structure around [from, to) in-place.
assembly {
result := add(b, from)
mstore(result, sub(to, from))
}
return result;
}
/// @dev Pops the last byte off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return result The byte that was popped off.
function popLastByte(bytes memory b)
internal
pure
returns (bytes1 result)
{
if (b.length == 0) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanZeroRequired,
b.length,
0
));
}
// Store last byte.
result = b[b.length - 1];
assembly {
// Decrement length of byte array.
let newLen := sub(mload(b), 1)
mstore(b, newLen)
}
return result;
}
/// @dev Tests equality of two byte arrays.
/// @param lhs First byte array to compare.
/// @param rhs Second byte array to compare.
/// @return equal True if arrays are the same. False otherwise.
function equals(
bytes memory lhs,
bytes memory rhs
)
internal
pure
returns (bool equal)
{
// Keccak gas cost is 30 + numWords * 6. This is a cheap way to compare.
// We early exit on unequal lengths, but keccak would also correctly
// handle this.
return lhs.length == rhs.length && keccak256(lhs) == keccak256(rhs);
}
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return result address from byte array.
function readAddress(
bytes memory b,
uint256 index
)
internal
pure
returns (address result)
{
if (b.length < index + 20) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Read address from array memory
assembly {
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 20-byte mask to obtain address
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
/// @dev Writes an address into a specific position in a byte array.
/// @param b Byte array to insert address into.
/// @param index Index in byte array of address.
/// @param input Address to put into byte array.
function writeAddress(
bytes memory b,
uint256 index,
address input
)
internal
pure
{
if (b.length < index + 20) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsTwentyRequired,
b.length,
index + 20 // 20 is length of address
));
}
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Store address into array memory
assembly {
// The address occupies 20 bytes and mstore stores 32 bytes.
// First fetch the 32-byte word where we'll be storing the address, then
// apply a mask so we have only the bytes in the word that the address will not occupy.
// Then combine these bytes with the address and store the 32 bytes back to memory with mstore.
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address
let neighbors := and(
mload(add(b, index)),
0xffffffffffffffffffffffff0000000000000000000000000000000000000000
)
// Make sure input address is clean.
// (Solidity does not guarantee this)
input := and(input, 0xffffffffffffffffffffffffffffffffffffffff)
// Store the neighbors and address into memory
mstore(add(b, index), xor(input, neighbors))
}
}
/// @dev Reads a bytes32 value from a position in a byte array.
/// @param b Byte array containing a bytes32 value.
/// @param index Index in byte array of bytes32 value.
/// @return result bytes32 value from byte array.
function readBytes32(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes32 result)
{
if (b.length < index + 32) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
b.length,
index + 32
));
}
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
result := mload(add(b, index))
}
return result;
}
/// @dev Writes a bytes32 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes32 to put into byte array.
function writeBytes32(
bytes memory b,
uint256 index,
bytes32 input
)
internal
pure
{
if (b.length < index + 32) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsThirtyTwoRequired,
b.length,
index + 32
));
}
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(b, index), input)
}
}
/// @dev Reads a uint256 value from a position in a byte array.
/// @param b Byte array containing a uint256 value.
/// @param index Index in byte array of uint256 value.
/// @return result uint256 value from byte array.
function readUint256(
bytes memory b,
uint256 index
)
internal
pure
returns (uint256 result)
{
result = uint256(readBytes32(b, index));
return result;
}
/// @dev Writes a uint256 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input uint256 to put into byte array.
function writeUint256(
bytes memory b,
uint256 index,
uint256 input
)
internal
pure
{
writeBytes32(b, index, bytes32(input));
}
/// @dev Reads an unpadded bytes4 value from a position in a byte array.
/// @param b Byte array containing a bytes4 value.
/// @param index Index in byte array of bytes4 value.
/// @return result bytes4 value from byte array.
function readBytes4(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes4 result)
{
if (b.length < index + 4) {
LibRichErrorsV06.rrevert(LibBytesRichErrorsV06.InvalidByteOperationError(
LibBytesRichErrorsV06.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired,
b.length,
index + 4
));
}
// Arrays are prefixed by a 32 byte length field
index += 32;
// Read the bytes4 from array memory
assembly {
result := mload(add(b, index))
// Solidity does not require us to clean the trailing bytes.
// We do it anyway
result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
}
return result;
}
/// @dev Writes a new length to a byte array.
/// Decreasing length will lead to removing the corresponding lower order bytes from the byte array.
/// Increasing length may lead to appending adjacent in-memory bytes to the end of the byte array.
/// @param b Bytes array to write new length to.
/// @param length New length of byte array.
function writeLength(bytes memory b, uint256 length)
internal
pure
{
assembly {
mstore(b, length)
}
}
}
// File: @opengsn/gsn/contracts/interfaces/IRelayRecipient.sol
pragma solidity ^0.6.2;
/**
* a contract must implement this interface in order to support relayed transaction.
* It is better to inherit the BaseRelayRecipient as its implementation.
*/
abstract contract IRelayRecipient {
/**
* return the forwarder we trust to forward relayed transactions to us.
* the forwarder is required to verify the sender's signature, and verify
* the call is not a replay.
*/
function getTrustedForwarder() public virtual view returns(address);
/**
* return the sender of this call.
* if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes
* of the msg.data.
* otherwise, return `msg.sender`
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal virtual view returns (address payable);
}
// File: @opengsn/gsn/contracts/BaseRelayRecipient.sol
pragma solidity ^0.6.2;
/**
* A base contract to be inherited by any contract that want to receive relayed transactions
* A subclass must use "_msgSender()" instead of "msg.sender"
*/
contract BaseRelayRecipient is IRelayRecipient {
/// the TrustedForwarder singleton we accept calls from.
// we trust it to verify the caller's signature, and pass the caller's address as last 20 bytes
address internal trustedForwarder;
/*
* require a function to be called through GSN only
*/
modifier trustedForwarderOnly() {
require(msg.sender == address(trustedForwarder), "Function can only be called through trustedForwarder");
_;
}
function getTrustedForwarder() public override view returns(address) {
return trustedForwarder;
}
/**
* return the sender of this call.
* if the call came through our trusted forwarder, return the original sender.
* otherwise, return `msg.sender`.
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal override virtual view returns (address payable) {
if (msg.data.length >= 24 && msg.sender == address(getTrustedForwarder())) {
// At this point we know that the sender is a trusted forwarder,
// so we trust that the last bytes of msg.data are the verified sender address.
// extract sender address from the end of msg.data
return address(uint160(LibBytesV06.readAddress(msg.data, msg.data.length - 20)));
}
return msg.sender;
}
}
// File: contracts/Stealth.sol
// SPDX-License-Identifier: GPL-3.0
/**
* Stealth.sol
* Implements the StealthSwap core functionnality.
* GSN Placeholders are used to fetch msg.sender until
* Future integration where withdrawals will be processed trough
* GSN.
*/
pragma solidity ^0.6.2;
/// @title StealthSwap Oracle Contract for Broadcasting Payment Notes
contract Stealth is BaseRelayRecipient, OwnableUpgradeSafe {
using SafeMath for uint256;
/// @dev protocol token (OWL) definition
IERC20 private protocolToken;
uint256 public protocolFee;
uint256 public etherProtocolFee;
uint256 public abyss;
address public feeManager;
address payable public feeTaker;
bool private initialized;
constructor(
IERC20 _protocolToken,
uint256 _protocolFee,
uint256 _etherProtocolFee,
address _feeManager,
address payable _feeTaker
) public {
__Ownable_init();
protocolToken = _protocolToken;
protocolFee = _protocolFee;
etherProtocolFee = _etherProtocolFee;
feeManager = _feeManager;
feeTaker = _feeTaker;
abyss = 1 wei;
}
mapping(address => bool) usedAddrs;
mapping(address => Payment) processedPayments;
/// Ownable Functions : Ownership is set at owner, then changed
/// to Governing Contract.
function setProtocolFee(uint256 _newFee) public onlyOwner {
protocolFee = _newFee;
}
function setEtherProtocolFee(uint256 _newEtherFee) public onlyOwner {
etherProtocolFee = _newEtherFee;
}
function setFeeManager(address _newFeeManager) public onlyOwner {
feeManager = _newFeeManager;
}
function setFeeTaker(address payable _newFeeTaker) public onlyOwner {
feeTaker = _newFeeTaker;
}
/// Events are singular blobs broadcasted by the oracle contract.
/// @notice PaymentNote represent a new payment made trough StealthSwap
/// @param receiver receiver's stealth address
/// @param token address of transferred token
/// @param amount amount transferred
/// @param iv initialization vector
/// @param xCoord ephemeral public key (X-coord)
/// @param yCoord ephemeral public key (Y-coord)
/// @param ctBuf0 cipher text first chuncked to 32 bytes
/// @param ctBuf1 cipher text second chunck
/// @param ctBuf2 cipher text last chunck
/// @param mac message authentification tag (HMAC-SHA256)
event PaymentNote(
address indexed receiver,
address indexed token,
uint256 indexed amount,
bytes16 iv,
bytes32 xCoord,
bytes32 yCoord,
bytes32 ctBuf0,
bytes32 ctBuf1,
bytes32 ctBuf2,
bytes32 mac
);
/// @notice Withdrawal is emitted from the local payment storage
/// @param receiver withdrawal address
/// @param interim hodler approving withdrawls
/// @param token address
/// @param amount being withdrawn (always full amounts prevent partials)
event Withdrawal(
address indexed receiver,
address indexed interim,
address indexed token,
uint256 amount
);
/// @notice a payment is represented by its token address and amount
struct Payment {
address token;
uint256 amount;
}
/// @dev Checksummed address similar to 0x0000000000000000000000000000000000000000
address constant ETHER_TOKEN = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
/// Sending Functions
/// @notice send ether to stealth address
/// @param _receiver receiver's address
/// @param _iv initialization vector
/// @param _xCoord ephemeral public key (X-coord)
/// @param _yCoord ephemeral public key (Y-coord)
/// @param _enc0 cipher text
/// @param _enc1 cipher text
/// @param _enc2 cipher text
/// @param _mac message authentification tag
function sendEther(
address payable _receiver,
bytes16 _iv,
bytes32 _xCoord,
bytes32 _yCoord,
bytes32 _enc0,
bytes32 _enc1,
bytes32 _enc2,
bytes32 _mac
) public payable unusedAddr(_receiver) {
/// enforce against dust attacks for ether transactions
require(msg.value >= protocolFee, "StealthSwap: Must have value higher than the protocol fee");
uint256 feeAllowance = IERC20(protocolToken).allowance(_msgSender(), address(this));
/// insure allowance is sufficient to pay for protocol fee
require(feeAllowance >= protocolFee, "StealthSwap: You must provide allowance to pay the protocol fee");
uint256 amount = msg.value;
/// enforce protocol fee payment
IERC20(protocolToken).transferFrom(_msgSender(), address(this), protocolFee);
/// emit new Payment Note
emit PaymentNote(_receiver, ETHER_TOKEN, amount, _iv, _xCoord, _yCoord, _enc0, _enc1, _enc2, _mac);
// Tag address as used to prevent stealth address re-use
usedAddrs[_receiver] = true;
// Transfer Ether to receiving stealth address
_receiver.transfer(amount);
}
/// @notice send erc20 token to stealth address
/// @param _receiver receiver's address
/// @param _tokenAddr token transferred address
/// @param _amount amount transferred
/// @param _iv initialization vector
/// @param _xCoord ephemeral public key (X-coord)
/// @param _yCoord ephemeral public key (Y-coord)
/// @param _enc0 cipher text
/// @param _enc1 cipher text
/// @param _enc2 cipher text
/// @param _mac message authentification tag
function sendERC20(
address payable _receiver,
address _tokenAddr,
uint256 _amount,
bytes16 _iv,
bytes32 _xCoord,
bytes32 _yCoord,
bytes32 _enc0,
bytes32 _enc1,
bytes32 _enc2,
bytes32 _mac
) public payable unusedAddr(_receiver) {
/// otherwise we will be accepting 0 ether transaction
/// this prevents the case where attackers mint and send worthless tokens
require(msg.value >= etherProtocolFee, "StealthSwap: Must have value greater than or equal to ether protocol fee");
uint256 feeAllowance = IERC20(protocolToken).allowance(_msgSender(), address(this));
/// insure allowance is sufficient to pay for protocol fee
require(feeAllowance >= protocolFee, "StealthSwap: You must provide allowance to pay the protocol fee");
uint256 tokenAllowance = IERC20(_tokenAddr).allowance(_msgSender(), address(this));
/// insure allowance is higher than protocolFee
require(tokenAllowance >= _amount, "StealthSwap: You must provide allowance to pay the protocol fee");
/// enforce protocol fee payment
IERC20(protocolToken).transferFrom(_msgSender(), address(this), protocolFee);
/// store token payment in our balance sheet
processedPayments[_receiver] = Payment({token: _tokenAddr, amount: _amount});
/// emit payment note
emit PaymentNote(_receiver, _tokenAddr, _amount, _iv, _xCoord, _yCoord, _enc0, _enc1, _enc2, _mac);
/// transfer tokens to contract control
IERC20(_tokenAddr).transferFrom(_msgSender(), _receiver, _amount);
/// tag stealth address as used to prevent re-use
usedAddrs[_receiver] = true;
/// transfer Ether protocol fee to receiver's address to afford withdrawals
_receiver.transfer(etherProtocolFee);
}
/// Withdrawal Processing
function withdraw(address _receiver) public {
uint256 amount = processedPayments[_msgSender()].amount;
address tokenAddr = processedPayments[_msgSender()].token;
// make sure _msgSender() has proper allocation
require(amount > 0, "StealthSwap: Unavailable tokens for withdrawal");
/// remove token payment from our balance sheet
delete processedPayments[_msgSender()];
emit Withdrawal(_msgSender(), _receiver, tokenAddr, amount);
/// send token to receiver
IERC20(tokenAddr).transferFrom(_msgSender(), _receiver, amount);
}
/// @notice collect paid fees for redistribituion
/// @dev this should be called by the staking contract
function collectPaidFees() public onlyManager {
feeTaker.transfer(address(this).balance);
uint256 totalFees = IERC20(protocolToken).balanceOf(address(this));
IERC20(protocolToken).approve(feeTaker,totalFees);
IERC20(protocolToken).transfer(feeTaker, totalFees);
}
/// Modifiers
function _msgSender()
internal
override(ContextUpgradeSafe, BaseRelayRecipient)
view
returns (address payable)
{
return BaseRelayRecipient._msgSender();
}
modifier onlyManager() {
require(_msgSender() == feeManager, "StealthSwap: Wrong Fee Manager");
_;
}
modifier unusedAddr(address _addr) {
require(!usedAddrs[_addr], "StealthSwap: stealth address cannot be reused");
_;
}
}
|
make sure _msgSender() has proper allocation
|
function withdraw(address _receiver) public {
uint256 amount = processedPayments[_msgSender()].amount;
address tokenAddr = processedPayments[_msgSender()].token;
require(amount > 0, "StealthSwap: Unavailable tokens for withdrawal");
delete processedPayments[_msgSender()];
emit Withdrawal(_msgSender(), _receiver, tokenAddr, amount);
IERC20(tokenAddr).transferFrom(_msgSender(), _receiver, amount);
| 6,571,078
|
pragma solidity ^0.4.18;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @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
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title InbestToken
* @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator.
* Note they can later distribute these tokens as they wish using `transfer` and other
* `StandardToken` functions.
*/
contract InbestToken is StandardToken {
string public constant name = "Inbest Token";
string public constant symbol = "IBST";
uint8 public constant decimals = 18;
// TBD
uint256 public constant INITIAL_SUPPLY = 17656263110 * (10 ** uint256(decimals));
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
function InbestToken() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Inbest Token initial distribution
*
* @dev Distribute Investors' and Company's tokens
*/
contract InbestDistribution is Ownable {
using SafeMath for uint256;
// Token
InbestToken public IBST;
// Status of admins
mapping (address => bool) public admins;
// Number of decimal places for tokens
uint256 private constant DECIMALFACTOR = 10**uint256(18);
// Cliff period = 6 months
uint256 CLIFF = 180 days;
// Vesting period = 12 months after cliff
uint256 VESTING = 365 days;
// Total of tokens
uint256 public constant INITIAL_SUPPLY = 17656263110 * DECIMALFACTOR; // 14.000.000.000 IBST
// Total of available tokens
uint256 public AVAILABLE_TOTAL_SUPPLY = 17656263110 * DECIMALFACTOR; // 14.000.000.000 IBST
// Total of available tokens for presale allocations
uint256 public AVAILABLE_PRESALE_SUPPLY = 16656263110 * DECIMALFACTOR; // 500.000.000 IBST, 18 months vesting, 6 months cliff
// Total of available tokens for company allocation
uint256 public AVAILABLE_COMPANY_SUPPLY = 1000000000 * DECIMALFACTOR; // 13.500.000.000 INST at token distribution event
// Allocation types
enum AllocationType { PRESALE, COMPANY}
// Amount of total tokens claimed
uint256 public grandTotalClaimed = 0;
// Time when InbestDistribution goes live
uint256 public startTime;
// The only wallet allowed for Company supply
address public companyWallet;
// Allocation with vesting and cliff information
struct Allocation {
uint8 allocationType; // Type of allocation
uint256 endCliff; // Tokens are locked until
uint256 endVesting; // This is when the tokens are fully unvested
uint256 totalAllocated; // Total tokens allocated
uint256 amountClaimed; // Total tokens claimed
}
mapping (address => Allocation) public allocations;
// Modifier to control who executes functions
modifier onlyOwnerOrAdmin() {
require(msg.sender == owner || admins[msg.sender]);
_;
}
// Event fired when a new allocation is made
event LogNewAllocation(address indexed _recipient, AllocationType indexed _fromSupply, uint256 _totalAllocated, uint256 _grandTotalAllocated);
// Event fired when IBST tokens are claimed
event LogIBSTClaimed(address indexed _recipient, uint8 indexed _fromSupply, uint256 _amountClaimed, uint256 _totalAllocated, uint256 _grandTotalClaimed);
// Event fired when admins are modified
event SetAdmin(address _caller, address _admin, bool _allowed);
// Event fired when refunding tokens mistakenly sent to contract
event RefundTokens(address _token, address _refund, uint256 _value);
/**
* @dev Constructor function - Set the inbest token address
* @param _startTime The time when InbestDistribution goes live
* @param _companyWallet The wallet to allocate Company tokens
*/
function InbestDistribution(uint256 _startTime, address _companyWallet) public {
require(_companyWallet != address(0));
require(_startTime >= now);
require(AVAILABLE_TOTAL_SUPPLY == AVAILABLE_PRESALE_SUPPLY.add(AVAILABLE_COMPANY_SUPPLY));
startTime = _startTime;
companyWallet = _companyWallet;
IBST = new InbestToken();
require(AVAILABLE_TOTAL_SUPPLY == IBST.totalSupply()); //To verify that totalSupply is correct
// Allocate Company Supply
uint256 tokensToAllocate = AVAILABLE_COMPANY_SUPPLY;
AVAILABLE_COMPANY_SUPPLY = 0;
allocations[companyWallet] = Allocation(uint8(AllocationType.COMPANY), 0, 0, tokensToAllocate, 0);
AVAILABLE_TOTAL_SUPPLY = AVAILABLE_TOTAL_SUPPLY.sub(tokensToAllocate);
LogNewAllocation(companyWallet, AllocationType.COMPANY, tokensToAllocate, grandTotalAllocated());
}
/**
* @dev Allow the owner or admins of the contract to assign a new allocation
* @param _recipient The recipient of the allocation
* @param _totalAllocated The total amount of IBST tokens available to the receipient (after vesting and cliff)
*/
function setAllocation (address _recipient, uint256 _totalAllocated) public onlyOwnerOrAdmin {
require(_recipient != address(0));
require(startTime > now); //Allocations are allowed only before starTime
require(AVAILABLE_PRESALE_SUPPLY >= _totalAllocated); //Current allocation must be less than remaining presale supply
require(allocations[_recipient].totalAllocated == 0 && _totalAllocated > 0); // Must be the first and only allocation for this recipient
require(_recipient != companyWallet); // Receipient of presale allocation can't be company wallet
// Allocate
AVAILABLE_PRESALE_SUPPLY = AVAILABLE_PRESALE_SUPPLY.sub(_totalAllocated);
allocations[_recipient] = Allocation(uint8(AllocationType.PRESALE), startTime.add(CLIFF), startTime.add(CLIFF).add(VESTING), _totalAllocated, 0);
AVAILABLE_TOTAL_SUPPLY = AVAILABLE_TOTAL_SUPPLY.sub(_totalAllocated);
LogNewAllocation(_recipient, AllocationType.PRESALE, _totalAllocated, grandTotalAllocated());
}
/**
* @dev Transfer a recipients available allocation to their address
* @param _recipient The address to withdraw tokens for
*/
function transferTokens (address _recipient) public {
require(_recipient != address(0));
require(now >= startTime); //Tokens can't be transfered until start date
require(_recipient != companyWallet); // Tokens allocated to COMPANY can't be withdrawn.
require(now >= allocations[_recipient].endCliff); // Cliff period must be ended
// Receipient can't claim more IBST tokens than allocated
require(allocations[_recipient].amountClaimed < allocations[_recipient].totalAllocated);
uint256 newAmountClaimed;
if (allocations[_recipient].endVesting > now) {
// Transfer available amount based on vesting schedule and allocation
newAmountClaimed = allocations[_recipient].totalAllocated.mul(now.sub(allocations[_recipient].endCliff)).div(allocations[_recipient].endVesting.sub(allocations[_recipient].endCliff));
} else {
// Transfer total allocated (minus previously claimed tokens)
newAmountClaimed = allocations[_recipient].totalAllocated;
}
//Transfer
uint256 tokensToTransfer = newAmountClaimed.sub(allocations[_recipient].amountClaimed);
allocations[_recipient].amountClaimed = newAmountClaimed;
require(IBST.transfer(_recipient, tokensToTransfer));
grandTotalClaimed = grandTotalClaimed.add(tokensToTransfer);
LogIBSTClaimed(_recipient, allocations[_recipient].allocationType, tokensToTransfer, newAmountClaimed, grandTotalClaimed);
}
/**
* @dev Transfer IBST tokens from Company allocation to reicipient address - Only owner and admins can execute
* @param _recipient The address to transfer tokens for
* @param _tokensToTransfer The amount of IBST tokens to transfer
*/
function manualContribution(address _recipient, uint256 _tokensToTransfer) public onlyOwnerOrAdmin {
require(_recipient != address(0));
require(_recipient != companyWallet); // Company can't withdraw tokens for itself
require(_tokensToTransfer > 0); // The amount must be valid
require(now >= startTime); // Tokens cant't be transfered until start date
//Company can't trasnfer more tokens than allocated
require(allocations[companyWallet].amountClaimed.add(_tokensToTransfer) <= allocations[companyWallet].totalAllocated);
//Transfer
allocations[companyWallet].amountClaimed = allocations[companyWallet].amountClaimed.add(_tokensToTransfer);
require(IBST.transfer(_recipient, _tokensToTransfer));
grandTotalClaimed = grandTotalClaimed.add(_tokensToTransfer);
LogIBSTClaimed(_recipient, uint8(AllocationType.COMPANY), _tokensToTransfer, allocations[companyWallet].amountClaimed, grandTotalClaimed);
}
/**
* @dev Returns remaining Company allocation
* @return Returns remaining Company allocation
*/
function companyRemainingAllocation() public view returns (uint256) {
return allocations[companyWallet].totalAllocated.sub(allocations[companyWallet].amountClaimed);
}
/**
* @dev Returns the amount of IBST allocated
* @return Returns the amount of IBST allocated
*/
function grandTotalAllocated() public view returns (uint256) {
return INITIAL_SUPPLY.sub(AVAILABLE_TOTAL_SUPPLY);
}
/**
* @dev Admin management
* @param _admin Address of the admin to modify
* @param _allowed Status of the admin
*/
function setAdmin(address _admin, bool _allowed) public onlyOwner {
require(_admin != address(0));
admins[_admin] = _allowed;
SetAdmin(msg.sender,_admin,_allowed);
}
function refundTokens(address _token, address _refund, uint256 _value) public onlyOwner {
require(_refund != address(0));
require(_token != address(0));
require(_token != address(IBST));
ERC20 token = ERC20(_token);
require(token.transfer(_refund, _value));
RefundTokens(_token, _refund, _value);
}
}
|
Transfer IBST tokens from Company allocation to reicipient address - Only owner and admins can execute _recipient The address to transfer tokens for _tokensToTransfer The amount of IBST tokens to transfer/Company can't trasnfer more tokens than allocatedTransfer
|
function manualContribution(address _recipient, uint256 _tokensToTransfer) public onlyOwnerOrAdmin {
require(_recipient != address(0));
require(allocations[companyWallet].amountClaimed.add(_tokensToTransfer) <= allocations[companyWallet].totalAllocated);
allocations[companyWallet].amountClaimed = allocations[companyWallet].amountClaimed.add(_tokensToTransfer);
require(IBST.transfer(_recipient, _tokensToTransfer));
grandTotalClaimed = grandTotalClaimed.add(_tokensToTransfer);
LogIBSTClaimed(_recipient, uint8(AllocationType.COMPANY), _tokensToTransfer, allocations[companyWallet].amountClaimed, grandTotalClaimed);
}
| 1,679,009
|
/* Copyright (C) 2021 Soteria.fund
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.17;
import "./external/Governed.sol";
import "./external/OwnedUpgradeabilityProxy.sol";
import "../../libraries/SafeMath.sol";
import "../claims/Claims.sol";
import "../capital/Pool2.sol";
import "../cover/Quotation.sol";
import "./MemberRoles.sol";
contract SOTEMaster is Governed {
using SafeMath for uint;
struct EmergencyPause {
bool pause;
uint time;
bytes4 by;
}
EmergencyPause[] public emergencyPaused;
bytes2[] internal allContractNames;
mapping(address => bool) public contractsActive;
mapping(bytes2 => address payable) internal allContractVersions;
mapping(bytes2 => bool) public isProxy;
mapping(bytes2 => bool) public isUpgradable;
address public tokenAddress;
bool internal reentrancyLock;
bool public masterInitialized;
address public owner;
uint public pauseTime;
bool constructorCheck;
modifier noReentrancy() {
require(!reentrancyLock, "Reentrant call.");
reentrancyLock = true;
_;
reentrancyLock = false;
}
/// @dev to initiate master data
/// @param _tokenAdd SOTE token address.
function initiateMaster(address _tokenAdd,address payable _govAdd) external {
OwnedUpgradeabilityProxy proxy = OwnedUpgradeabilityProxy(address(uint160(address(this))));
require(msg.sender == proxy.proxyOwner(),"Sender is not proxy owner.");
require(!constructorCheck,"Constructor already ran.");
constructorCheck = true;
tokenAddress = _tokenAdd;
owner = msg.sender;
masterAddress = address(this);
contractsActive[address(this)] = true;
pauseTime = 28 days; //4 weeks
// 1. init gov
allContractNames.push("GV");
allContractVersions["GV"] = _govAdd;
contractsActive[_govAdd] = true;
isProxy["GV"] = true;
// 2. set masterInitialized
masterInitialized = true;
}
function upgradeMultipleImplementations(
bytes2[] calldata _contractNames,
address[] calldata _contractAddresses
)
external
onlyAuthorizedToGovern
{
require(_contractNames.length == _contractAddresses.length,"Array length should be equal.");
for (uint i=0; i < _contractNames.length; i++) {
require(_contractAddresses[i] != address(0),"null address is not allowed.");
require(isProxy[_contractNames[i]],"Contract should be proxy.");
OwnedUpgradeabilityProxy proxy = OwnedUpgradeabilityProxy(allContractVersions[_contractNames[i]]);
proxy.upgradeTo(_contractAddresses[i]);
}
}
/// @dev Adds new internal contract
/// @param _type pass 1 if contract is upgradable, 2 if contract is proxy, any other uint if none.
function addNewInternalContract(
bytes2 _contractName,
address payable _contractAddress,
uint _type
)
external
onlyAuthorizedToGovern {
require(allContractVersions[_contractName] == address(0),"Contract code is already available.");
require(_contractAddress != address(0),"NULL address is not allowed.");
allContractNames.push(_contractName);
address newInternalContract = _contractAddress; // Using extra varible to get rid of if condition.
if (_type == 1) {
isUpgradable[_contractName] = true;
} else if (_type == 2) {
newInternalContract = _generateProxy(_contractAddress);
isProxy[_contractName] = true;
}
allContractVersions[_contractName] = address(uint160(newInternalContract));
contractsActive[newInternalContract] = true;
Iupgradable up = Iupgradable(allContractVersions[_contractName]);
up.changeMasterAddress(address(this));
up.changeDependentContractAddress();
}
/**
* @dev Anyone can close a claim if oraclize fails to close it.
* @param _claimId id of claim to be closed.
*/
function closeClaim(uint _claimId) external {
require(canCall(_claimId), "Payout retry time not reached.");
ClaimsReward cr = ClaimsReward(getLatestAddress("CR"));
cr.changeClaimStatus(_claimId);
}
/**
* @dev Handles the oraclize query callback.
* @param myid ID of oraclize query to be processed
*/
function delegateCallBack(bytes32 myid) external noReentrancy {
PoolData pd = PoolData(getLatestAddress("PD"));
uint callTime = pd.getDateUpdOfAPI(myid);
uint dateAdd = pd.getDateAddOfAPI(myid);
require(callTime == dateAdd, "Callback already received");
bytes4 res = pd.getApiIdTypeOf(myid);
pd.updateDateUpdOfAPI(myid);
if (isPause()) {
bytes4 by;
(, , by) = getLastEmergencyPause();
require(res == "EP", "Only callback of type EP is allowed during emergency pause");
require(callTime.add(pauseTime) < now, "Callback was called too soon");
require(by == "AB", "Emergency paused was not started by Advisory Board");
addEmergencyPause(false, "AUT");
return;
}
uint id = pd.getIdOfApiId(myid);
if (res == "COV") {
Quotation qt = Quotation(getLatestAddress("QT"));
qt.expireCover(id);
return;
}
if (res == "CLA") {
require(canCall(id), "Payout retry time not reached");
ClaimsReward cr = ClaimsReward(getLatestAddress("CR"));
cr.changeClaimStatus(id);
return;
}
if (res == "MCRF") {
require(callTime.add(pd.mcrFailTime()) < now, "MCR posting time not reached");
MCR m1 = MCR(getLatestAddress("MC"));
m1.addLastMCRData(uint64(id));
return;
}
if (res == "ULT") {
require(callTime.add(pd.liquidityTradeCallbackTime()) < now, "Liquidity trade time not reached");
Pool2 p2 = Pool2(getLatestAddress("P2"));
p2.externalLiquidityTrade();
return;
}
if (res == "MCR" || res == "IARB") {
return;
}
revert("Invalid callback");
}
function getOwnerParameters(bytes8 code) external view returns(bytes8 codeVal, address val) {
codeVal = code;
QuotationData qd;
PoolData pd;
if (code == "MSWALLET") {
TokenData td;
td = TokenData(getLatestAddress("TD"));
val = td.walletAddress();
} else if (code == "MCRNOTA") {
pd = PoolData(getLatestAddress("PD"));
val = pd.notariseMCR();
} else if (code == "DAIFEED") {
pd = PoolData(getLatestAddress("PD"));
val = pd.daiFeedAddress();
} else if (code == "UNISWADD") {
Pool2 p2;
p2 = Pool2(getLatestAddress("P2"));
val = p2.uniswapFactoryAddress();
} else if (code == "OWNER") {
val = owner;
} else if (code == "QUOAUTH") {
qd = QuotationData(getLatestAddress("QD"));
val = qd.authQuoteEngine();
} else if (code == "KYCAUTH") {
qd = QuotationData(getLatestAddress("QD"));
val = qd.kycAuthAddress();
}
}
/// @dev Add Emergency pause
/// @param _pause to set Emergency Pause ON/OFF
/// @param _by to set who Start/Stop EP
function addEmergencyPause(bool _pause, bytes4 _by) public {
require(_by == "AB" || _by == "AUT","Invalid call.");
require(msg.sender == getLatestAddress("P1") || msg.sender == getLatestAddress("GV"),"Callable by P1 and GV only.");
emergencyPaused.push(EmergencyPause(_pause, now, _by));
if (_pause == false) {
Claims c1 = Claims(allContractVersions["CL"]);
c1.submitClaimAfterEPOff(); // Process claims submitted while EP was on
c1.startAllPendingClaimsVoting(); // Resume voting on all pending claims
}
}
///@dev update time in seconds for which emergency pause is applied.
function updatePauseTime(uint _time) public {
require(isInternal(msg.sender),"Not internal call.");
pauseTime = _time;
}
/// @dev upgrades All Address at a time
function upgradeAllAddress()
public
onlyAuthorizedToGovern
{
_changeAllAddress();
}
function changeAllAddress(uint8 start,uint8 end) public
{
uint i;
for (i = start; i < end; i++) {
contractsActive[allContractVersions[allContractNames[i]]] = true;
Iupgradable up = Iupgradable(allContractVersions[allContractNames[i]]);
up.changeDependentContractAddress();
}
}
/// @dev upgrades contract at a time
function upgradeContract(
bytes2 _contractsName,
address payable _contractsAddress
)
public
onlyAuthorizedToGovern
{
address payable oldAddress = allContractVersions[_contractsName];
contractsActive[oldAddress] = false;
allContractVersions[_contractsName] = _contractsAddress;
contractsActive[_contractsAddress] = true;
Iupgradable up = Iupgradable(allContractVersions[_contractsName]);
up.changeMasterAddress(address(this));
}
/// @dev upgrades multiple contracts at a time
function upgradeMultipleContracts(
bytes2[] memory _contractsName,
address payable[] memory _contractsAddress
)
public
onlyAuthorizedToGovern
{
require(_contractsName.length == _contractsAddress.length, "Array length should be equal.");
for (uint i=0; i<_contractsName.length; i++) {
address payable newAddress = _contractsAddress[i];
require(newAddress != address(0),"NULL address is not allowed.");
require(isUpgradable[_contractsName[i]],"Contract should be upgradable.");
if (_contractsName[i] == "QT") {
Quotation qt = Quotation(allContractVersions["QT"]);
qt.transferAssetsToNewContract(newAddress);
} else if (_contractsName[i] == "CR") {
TokenController tc = TokenController(getLatestAddress("TC"));
tc.addToWhitelist(newAddress);
tc.removeFromWhitelist(allContractVersions["CR"]);
ClaimsReward cr = ClaimsReward(allContractVersions["CR"]);
cr.upgrade(newAddress);
} else if (_contractsName[i] == "P1") {
Pool1 p1 = Pool1(allContractVersions["P1"]);
p1.upgradeCapitalPool(newAddress);
} else if (_contractsName[i] == "P2") {
Pool2 p2 = Pool2(allContractVersions["P2"]);
p2.upgradeInvestmentPool(newAddress);
}
address payable oldAddress = allContractVersions[_contractsName[i]];
contractsActive[oldAddress] = false;
allContractVersions[_contractsName[i]] = newAddress;
contractsActive[newAddress] = true;
Iupgradable up = Iupgradable(allContractVersions[_contractsName[i]]);
up.changeMasterAddress(address(this));
}
_changeAllAddress();
}
/// @dev checks whether the address is an internal contract address.
function isInternal(address _contractAddress) public view returns(bool) {
return contractsActive[_contractAddress];
}
/// @dev checks whether the address is the Owner or not.
function isOwner(address _address) public view returns(bool) {
return owner == _address;
}
/// @dev Checks whether emergency pause id on/not.
function isPause() public view returns(bool) {
uint length = emergencyPaused.length;
return length > 0 && emergencyPaused[length - 1].pause;
}
/// @dev checks whether the address is a member of the mutual or not.
function isMember(address _add) public view returns(bool) {
MemberRoles mr = MemberRoles(getLatestAddress("MR"));
return mr.checkRole(_add, uint(MemberRoles.Role.Member));
}
///@dev Gets the number of emergency pause has been toggled.
function getEmergencyPausedLength() public view returns(uint len) {
len = emergencyPaused.length;
}
///@dev Gets last emergency pause details.
function getLastEmergencyPause() public view returns(bool _pause, uint _time, bytes4 _by) {
_pause = false;
_time = 0;
_by = "";
uint len = getEmergencyPausedLength();
if (len > 0) {
len = len.sub(1);
_pause = emergencyPaused[len].pause;
_time = emergencyPaused[len].time;
_by = emergencyPaused[len].by;
}
}
/// @dev Gets latest version name and address
/// @return contractsName Latest version's contract names
/// @return contractsAddress Latest version's contract addresses
function getVersionData()
public
view
returns (
bytes2[] memory contractsName,
address[] memory contractsAddress
)
{
contractsName = allContractNames;
contractsAddress = new address[](allContractNames.length);
for (uint i = 0; i < allContractNames.length; i++) {
contractsAddress[i] = allContractVersions[allContractNames[i]];
}
}
/**
* @dev returns the address of token controller
* @return address is returned
*/
function dAppLocker() public view returns(address _add) {
_add = getLatestAddress("TC");
}
/**
* @dev returns the address of sote token
* @return address is returned
*/
function dAppToken() public view returns(address _add) {
_add = tokenAddress;
}
/// @dev Gets latest contract address
/// @param _contractName Contract name to fetch
function getLatestAddress(bytes2 _contractName) public view returns(address payable contractAddress) {
contractAddress = allContractVersions[_contractName];
}
/// @dev Creates a new version of contract addresses
/// @param _contractAddresses Array of contract addresses which will be generated
function addNewVersion(address payable[] memory _contractAddresses) public {
require(msg.sender == owner && !masterInitialized,"Caller should be owner and should only be called once.");
require(_contractAddresses.length == allContractNames.length, "array length not same");
masterInitialized = true;
MemberRoles mr = MemberRoles(_contractAddresses[14]);
// shoud send proxy address for proxy contracts (if not 1st time deploying)
// bool isMasterUpgrade = mr.soteMasterAddress() != address(0);
for (uint i = 0; i < allContractNames.length; i++) {
require(_contractAddresses[i] != address(0),"NULL address is not allowed.");
allContractVersions[allContractNames[i]] = _contractAddresses[i];
contractsActive[_contractAddresses[i]] = true;
}
// Need to override owner as owner in MR to avoid inconsistency as owner in MR is some other address.
(, address[] memory mrOwner) = mr.members(uint(MemberRoles.Role.Owner));
owner = mrOwner[0];
}
/**
* @dev to check if the address is authorized to govern or not
* @param _add is the address in concern
* @return the boolean status status for the check
*/
function checkIsAuthToGoverned(address _add) public view returns(bool) {
return isAuthorizedToGovern(_add);
}
/// @dev Allow AB Members to Start Emergency Pause
function startEmergencyPause() public onlyAuthorizedToGovern {
addEmergencyPause(true, "AB"); //Start Emergency Pause
Pool1 p1 = Pool1(allContractVersions["P1"]);
p1.closeEmergencyPause(pauseTime); //oraclize callback of 4 weeks
Claims c1 = Claims(allContractVersions["CL"]);
c1.pauseAllPendingClaimsVoting(); //Pause Voting of all pending Claims
}
/**
* @dev to update the owner parameters
* @param code is the associated code
* @param val is value to be set
*/
function updateOwnerParameters(bytes8 code, address payable val) public onlyAuthorizedToGovern {
QuotationData qd;
PoolData pd;
if (code == "MSWALLET") {
TokenData td;
td = TokenData(getLatestAddress("TD"));
td.changeWalletAddress(val);
} else if (code == "MCRNOTA") {
pd = PoolData(getLatestAddress("PD"));
pd.changeNotariseAddress(val);
} else if (code == "DAIFEED") {
pd = PoolData(getLatestAddress("PD"));
pd.changeDAIfeedAddress(val);
} else if (code == "UNISWADD") {
Pool2 p2;
p2 = Pool2(getLatestAddress("P2"));
p2.changeUniswapFactoryAddress(val);
} else if (code == "OWNER") {
MemberRoles mr = MemberRoles(getLatestAddress("MR"));
mr.swapOwner(val);
owner = val;
} else if (code == "QUOAUTH") {
qd = QuotationData(getLatestAddress("QD"));
qd.changeAuthQuoteEngine(val);
} else if (code == "KYCAUTH") {
qd = QuotationData(getLatestAddress("QD"));
qd.setKycAuthAddress(val);
} else {
revert("Invalid param code");
}
}
/**
* @dev to generater proxy
* @param _implementationAddress of the proxy
*/
function _generateProxy(address _implementationAddress) internal returns(address) {
OwnedUpgradeabilityProxy proxy = new OwnedUpgradeabilityProxy(_implementationAddress);
return address(proxy);
}
/// @dev Sets the older versions of contract addresses as inactive and the latest one as active.
function _changeAllAddress() internal {
uint i;
for (i = 0; i < allContractNames.length; i++) {
contractsActive[allContractVersions[allContractNames[i]]] = true;
Iupgradable up = Iupgradable(allContractVersions[allContractNames[i]]);
up.changeDependentContractAddress();
}
}
function canCall(uint _claimId) internal view returns(bool)
{
ClaimsData cd = ClaimsData(getLatestAddress("CD"));
(, , , uint status, uint dateUpd, ) = cd.getClaim(_claimId);
if (status == 12) {
if (dateUpd.add(cd.payoutRetryTime()) > now) {
return false;
}
}
return true;
}
}
|
Checks whether emergency pause id on/not.
|
function isPause() public view returns(bool) {
uint length = emergencyPaused.length;
return length > 0 && emergencyPaused[length - 1].pause;
}
| 7,293,428
|
./full_match/44787/0xEE238f805347a5EfC8772Ef9541d77edaF093C31/sources/contracts/marketPlace/CyberBoxMarket.sol
|
Remove token listing
|
function buyTokenComplete(address sender, uint256 tokenId) external {
_erc721.safeTransferFrom(listing.seller, sender, tokenId);
_delistToken(tokenId);
_removeBidOfBidder(tokenId, sender);
}
| 13,242,106
|
/**
*Submitted for verification at Etherscan.io on 2022-04-14
*/
//SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
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
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 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");
(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");
(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");
(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");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal 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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: erc721a/contracts/ERC721A.sol
// Creator: Chiru Labs
pragma solidity ^0.8.4;
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerQueryForNonexistentToken();
error TransferCallerNotOwnerNorApproved();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
error URIQueryForNonexistentToken();
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256).
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
// For miscellaneous variable(s) pertaining to the address
// (e.g. number of whitelist mint slots used).
// If there are multiple variables, please pack them into a uint64.
uint64 aux;
}
// The tokenId of the next token to be minted.
uint256 internal _currentIndex;
// The number of tokens burned.
uint256 internal _burnCounter;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
/**
* To change the starting tokenId, please override this function.
*/
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens.
*/
function totalSupply() public view returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex - _startTokenId() times
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
/**
* Returns the total amount of tokens minted in the contract.
*/
function _totalMinted() internal view returns (uint256) {
// Counter underflow is impossible as _currentIndex does not decrement,
// and it is initialized to _startTokenId()
unchecked {
return _currentIndex - _startTokenId();
}
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
/**
* Returns the number of tokens minted by `owner`.
*/
function _numberMinted(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberMinted);
}
/**
* Returns the number of tokens burned by or on behalf of `owner`.
*/
function _numberBurned(address owner) internal view returns (uint256) {
return uint256(_addressData[owner].numberBurned);
}
/**
* Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
*/
function _getAux(address owner) internal view returns (uint64) {
return _addressData[owner].aux;
}
/**
* Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used).
* If there are multiple variables, please pack them into a uint64.
*/
function _setAux(address owner, uint64 aux) internal {
_addressData[owner].aux = aux;
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return '';
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
if (operator == _msgSender()) revert ApproveToCaller();
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
_transfer(from, to, tokenId);
if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1
// updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
// Reentrancy protection
if (_currentIndex != startTokenId) revert();
} else {
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = to;
currSlot.startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev This is equivalent to _burn(tokenId, false)
*/
function _burn(uint256 tokenId) internal virtual {
_burn(tokenId, false);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
address from = prevOwnership.addr;
if (approvalCheck) {
bool isApprovedOrOwner = (_msgSender() == from ||
isApprovedForAll(from, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, from);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
AddressData storage addressData = _addressData[from];
addressData.balance -= 1;
addressData.numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
TokenOwnership storage currSlot = _ownerships[tokenId];
currSlot.addr = from;
currSlot.startTimestamp = uint64(block.timestamp);
currSlot.burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
TokenOwnership storage nextSlot = _ownerships[nextTokenId];
if (nextSlot.addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId != _currentIndex) {
nextSlot.addr = from;
nextSlot.startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// File: contracts/CyberRonin Haruka.sol
/*
HarukaRonin.sol
Updated Contract by @NftDoyler
Original Security Audit by @CryptoSec_Group
*/
contract HarukaRonin is Ownable, ERC721A {
bytes32 public merkleRoot;
// Note: This should be marked constant if you NEVER plan on changing them to save gas.
// That said, leaving the option open in case you wanted to increase mints/decrease collection size.
// Note AGAIN: That said, setting this to a constant saves the SLOADs and about 1.8% gas per mint.
uint256 public MAX_SUPPLY = 5555;
// Updated: This was never modified, so is now a constant
uint256 constant public MAX_SUPPLY_PRIVATE_WHITELISTED = 55;
// Same with this, these should be constant if you never plan on changing them.
uint256 public mintRatePublicWhitelist = 0.055 ether;
uint256 public mintRatePublicSale = 0.069 ether;
// Updated: "Private" WL logic has been removed as it was unnecessary
// There is now a method for the dev team to mint their 55
//bool public privateWhitelisted = true;
//uint256 public mintRatePrivateWhitelist = 0 ether;
// Also lets the public see exactly how many they've minted.
uint256 public DEV_MINTS;
// Note: For even MORE gas efficiency you can actually pack bools into one bit instead of 8.
// That said, it's unnecessary complexity at a time like this, but a fun experiment for the reader!
// Updated: I've set paused to be true to start, so that the team has time to make annoucements etc.
// (See publicSale/publicWhitelisted logic for more information)
bool public paused = true;
bool public revealed = false;
// Updated: With the new on/off switch logic, these need to be set to different values by default.
// This means that, once the contract is deployed, WL will be available immediately (if not paused).
// Updated AGAIN: Yould think that with the new on/off logic that this isn't necessary.
// That said, due to the usage and comparisons, it SAVES a miniscule amount of gas.
bool public publicWhitelisted = true;
bool public publicSale = false;
uint256 public mintedPublicWhitelistAddressLimit = 2;
uint256 public mintedPublicAddressLimit = 3;
string public baseURI = "ipfs://QmfEjT2YeRcE3pzL8HovHPX1kCsNPFgWSiRytHfj38kpUt/";
// Updated: Setting the default value here instead of the constructor.
// I'd personally make this a constant since it shouldn't have to change, but leaving for v1 compatability.
string public hiddenMetadataUri = "ipfs://QmfEjT2YeRcE3pzL8HovHPX1kCsNPFgWSiRytHfj38kpUt/Hidden.json";
string constant public uriSuffix = ".json";
// Updated: This is a new string that the owners can use for CONTRACT_URI
// This is how you can easily set Collection name/description/image,
// as well as royalty fees and wallet address.
string public CONTRACT_URI = "ipfs://QmXLBLk2CqPEFP2KRS1VoTtnoxkM3BbT8yoBwfK7twW4ne";
// Note: If this was never going to be changed it could have also been a constant.
// That said, not sure if the v2 updates mess with this or not.
address public privateWLAddress = 0x016100D875E932c7B6f9416f151e562e04Faf779;
// Updated AGAIN: By disabling this and ONLY tracking one mapping we save about 11.8% gas per WL mint.
//mapping(address => uint256) public publicWhitelistAddressMintedBalance;
// That said, it's the quickest and easiest way to handle the previous v1 logic
// Note: If you wanted to save even MORE gas, you could disable this mapping entirely and only use balanceOf(msg.sender)
// This saves you about 19.5% per publicMint at the cost of not letting users buy on secondary and THEN mint
// Basically you save out on one SLOAD and SSTORE PER MINT!
mapping(address => uint256) public numUserMints;
// Updated: Hard-coded developer address for use in the withdraw functionality
//Note: This wallet does not get any of the secondary fees/deposits, just mints
address constant public doylerAddress = 0xeD19c8970c7BE64f5AC3f4beBFDDFd571861c3b7;
// Community Wallet - this gets 55% of the withdrawals
address public communityWallet = 0xE2836891C9B57821b9Fba1B7Ccc110E9DDaBCf85;
// Team Wallet - this gets 15% (technically a little less counting gas fees) of the withdrawals
address public teamWallet = 0x016100D875E932c7B6f9416f151e562e04Faf779;
uint256 private doylerPayable;
// Updated: This was the primary cause of most of the original gas issues.
// Left it in for the bit of history.
//address[] public mintedPublicWhitelistAddresses;
// Updated: I removed the initial hidden metadata URI from here as it was not necessary
// Also, the constructor no longer sets the Merkle Root to separate out those functions
// This does require a second call to the contract, but prevents a failure in that call from preventing deployment.
constructor() ERC721A("CyberRonin Haruka", "Haruka") { }
/*
*
$$$$$$$\ $$\ $$\ $$$$$$$$\ $$\ $$\
$$ __$$\ \__| $$ | $$ _____| $$ | \__|
$$ | $$ | $$$$$$\ $$\ $$\ $$\ $$$$$$\ $$$$$$\ $$$$$$\ $$ | $$\ $$\ $$$$$$$\ $$$$$$$\ $$$$$$\ $$\ $$$$$$\ $$$$$$$\ $$$$$$$\
$$$$$$$ |$$ __$$\ $$ |\$$\ $$ |\____$$\\_$$ _| $$ __$$\ $$$$$\ $$ | $$ |$$ __$$\ $$ _____|\_$$ _| $$ |$$ __$$\ $$ __$$\ $$ _____|
$$ ____/ $$ | \__|$$ | \$$\$$ / $$$$$$$ | $$ | $$$$$$$$ | $$ __|$$ | $$ |$$ | $$ |$$ / $$ | $$ |$$ / $$ |$$ | $$ |\$$$$$$\
$$ | $$ | $$ | \$$$ / $$ __$$ | $$ |$$\ $$ ____| $$ | $$ | $$ |$$ | $$ |$$ | $$ |$$\ $$ |$$ | $$ |$$ | $$ | \____$$\
$$ | $$ | $$ | \$ / \$$$$$$$ | \$$$$ |\$$$$$$$\ $$ | \$$$$$$ |$$ | $$ |\$$$$$$$\ \$$$$ |$$ |\$$$$$$ |$$ | $$ |$$$$$$$ |
\__| \__| \__| \_/ \_______| \____/ \_______| \__| \______/ \__| \__| \_______| \____/ \__| \______/ \__| \__|\_______/
*
*/
// This function is if you want to override the first Token ID# for ERC721A
// In this case, HR is starting at #1 instead of #0
// Note: Fun fact - by overloading this method you save a small amount of gas for minting (technically just the first mint)
function _startTokenId() internal view virtual override returns (uint256) {
return 1;
}
// Updated: Internal verifyPublicWL method.
// This is the one that is actually losed for contract logic and uses msg.sender
function _verifyPublicWL(bytes32[] memory _proof) internal view returns (bool) {
return MerkleProof.verify(_proof, merkleRoot, keccak256(abi.encodePacked(msg.sender)));
}
// Updated: This didn't exist in v1 of the contract, but is a best practice to protect users
function refundOverpay(uint256 price) private {
if (msg.value > price) {
(bool succ, ) = payable(msg.sender).call{
value: (msg.value - price)
}("");
require(succ, "Transfer failed");
}
}
/*
*
$$$$$$$\ $$\ $$\ $$\ $$$$$$$$\ $$\ $$\
$$ __$$\ $$ | $$ |\__| $$ _____| $$ | \__|
$$ | $$ |$$\ $$\ $$$$$$$\ $$ |$$\ $$$$$$$\ $$ | $$\ $$\ $$$$$$$\ $$$$$$$\ $$$$$$\ $$\ $$$$$$\ $$$$$$$\ $$$$$$$\
$$$$$$$ |$$ | $$ |$$ __$$\ $$ |$$ |$$ _____| $$$$$\ $$ | $$ |$$ __$$\ $$ _____|\_$$ _| $$ |$$ __$$\ $$ __$$\ $$ _____|
$$ ____/ $$ | $$ |$$ | $$ |$$ |$$ |$$ / $$ __|$$ | $$ |$$ | $$ |$$ / $$ | $$ |$$ / $$ |$$ | $$ |\$$$$$$\
$$ | $$ | $$ |$$ | $$ |$$ |$$ |$$ | $$ | $$ | $$ |$$ | $$ |$$ | $$ |$$\ $$ |$$ | $$ |$$ | $$ | \____$$\
$$ | \$$$$$$ |$$$$$$$ |$$ |$$ |\$$$$$$$\ $$ | \$$$$$$ |$$ | $$ |\$$$$$$$\ \$$$$ |$$ |\$$$$$$ |$$ | $$ |$$$$$$$ |
\__| \______/ \_______/ \__|\__| \_______| \__| \______/ \__| \__| \_______| \____/ \__| \______/ \__| \__|\_______/
*
*/
// Note: Generally speaking you COULD save some gas making functions 'external' instead of 'public'
// That said, you can no longer call them from other contracts OR internally.
// Also, these gas savings are usually just when dealing with large arrays, which we've removed.
// Updated: No reason devs shouldn't be allowed to mint during public or WL windows
// Updated: Removed other unnecessary require statements
function privateMint(uint256 quantity) public payable mintCompliance(quantity) {
// Updated: Just shorter reason strings, it's a small savings, but why not?
require(msg.sender == privateWLAddress, "Dev minting only");
// Note: You could technically save like 0.004% in gas by replacing every <= with < etc.
// That said, it isn't worth the confusion when looking at the code
require(DEV_MINTS + quantity <= MAX_SUPPLY_PRIVATE_WHITELISTED, "No dev mints left");
// Note: This is SLIGHTLY more efficient than including the dev mints into the universal mapping
DEV_MINTS += quantity;
_safeMint(msg.sender, quantity);
}
// Updated AGAIN: Using a local require() instead of a modifier saved a touch of gas
function publicWhitelistMint(uint256 quantity, bytes32[] memory proof) external payable mintCompliance(quantity) {
// Updated AGAIN: Setting this variable locally saves 2 SLOAD calls and about 0.2% gas
uint256 price = mintRatePublicWhitelist;
// Updated AGAIN: By using this as a local variable we save 1 SLOAD call and about 0.1% gas
uint256 currMints = numUserMints[msg.sender];
require(publicWhitelisted, "WL sale inactive");
// Updated AGAIN: See notes in variable section above as to the reasoning behind this removal.
//require(publicWhitelistAddressMintedBalance[msg.sender] + quantity <= mintedPublicWhitelistAddressLimit, "User max WL mint limit");
// Updated AGAIN: By using this as a local variable we save 1 SLOAD call and about 0.1% gas
//require(numUserMints[msg.sender] + quantity <= mintedPublicWhitelistAddressLimit, "User max WL mint limit");
require(currMints + quantity <= mintedPublicWhitelistAddressLimit, "User max WL mint limit");
// Note: Here is the example if you wanted to just use balanceOf
//require(balanceOf(msg.sender) + quantity <= mintedPublicWhitelistAddressLimit, "User max WL mint limit");
require(msg.value >= (price * quantity), "Not enough ETH sent");
require(_verifyPublicWL(proof), "User not on WL");
//publicWhitelistAddressMintedBalance[msg.sender] += quantity;
//numUserMints[msg.sender] += quantity;
numUserMints[msg.sender] = (currMints + quantity);
_safeMint(msg.sender, quantity);
doylerPayable += ((price * quantity) * 30) / 100;
// That said, it only adds about 0.13% gas to each transaction to protect users who messed up.
refundOverpay(price * quantity);
}
// Updated: Removed a lot of unnecessary require statements
// Updated: Implemented more efficient tracking of user mints
function publicMint(uint256 quantity) external payable mintCompliance(quantity) {
// Updated AGAIN: Setting this variable locally saves 2 SLOAD calls and about 0.2% gas
uint256 price = mintRatePublicSale;
// Updated AGAIN: By using this as a local variable we save 1 SLOAD call and about 0.1% gas
uint256 currMints = numUserMints[msg.sender];
require(publicSale, "Public sale inactive");
require(currMints + quantity <= mintedPublicAddressLimit, "User max mint limit");
// Note: Here is the example if you wanted to just use balanceOf
//require(balanceOf(msg.sender) + quantity <= mintedPublicAddressLimit, "User max mint limit");
require(msg.value >= (price * quantity), "Not enough ETH sent");
// Note: This line + the require add an additional 22% gas to this method
// That said, was the most convenient way to track 2 limits at the same time.
//numUserMints[msg.sender] += quantity;
numUserMints[msg.sender] = (currMints + quantity);
// Updated AGAIN: By using this as a local variable we save 1 SLOAD call and about 0.1% gas
//require(numUserMints[msg.sender] + quantity <= mintedPublicAddressLimit, "User max mint limit");
_safeMint(msg.sender, quantity);
// Note: Having both of these in the mint methods is not the most efficient
// That said, it worked for the time constraints
doylerPayable += ((price * quantity) * 30) / 100;
// Note: This method didn't exist in the last version of the contract.
// That said, it only adds about 0.13% gas to each transaction to protect users who messed up.
refundOverpay(price * quantity);
}
/*
*
$$\ $$\ $$\ $$$$$$$$\ $$\ $$\
$$ | $$ |\__| $$ _____| $$ | \__|
$$ | $$ |$$\ $$$$$$\ $$\ $$\ $$\ $$ | $$\ $$\ $$$$$$$\ $$$$$$$\ $$$$$$\ $$\ $$$$$$\ $$$$$$$\ $$$$$$$\
\$$\ $$ |$$ |$$ __$$\ $$ | $$ | $$ | $$$$$\ $$ | $$ |$$ __$$\ $$ _____|\_$$ _| $$ |$$ __$$\ $$ __$$\ $$ _____|
\$$\$$ / $$ |$$$$$$$$ |$$ | $$ | $$ | $$ __|$$ | $$ |$$ | $$ |$$ / $$ | $$ |$$ / $$ |$$ | $$ |\$$$$$$\
\$$$ / $$ |$$ ____|$$ | $$ | $$ | $$ | $$ | $$ |$$ | $$ |$$ | $$ |$$\ $$ |$$ | $$ |$$ | $$ | \____$$\
\$ / $$ |\$$$$$$$\ \$$$$$\$$$$ | $$ | \$$$$$$ |$$ | $$ |\$$$$$$$\ \$$$$ |$$ |\$$$$$$ |$$ | $$ |$$$$$$$ |
\_/ \__| \_______| \_____\____/ \__| \______/ \__| \__| \_______| \____/ \__| \______/ \__| \__|\_______/
*
*/
// Note: walletOfOwner is only really necessary for enumerability when staking/using on websites etc.
// That said, it's again a public view so we can keep it in.
// This could also be optimized if someone REALLY wanted, but it's just a public view.
// Check the pinned tweets of 0xInuarashi for more ideas on this method!
// For now, this is just the version that existed in v1.
function walletOfOwner(address _owner) public view returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = 1;
uint256 ownedTokenIndex = 0;
while (ownedTokenIndex < ownerTokenCount && currentTokenId <= MAX_SUPPLY) {
address currentTokenOwner = ownerOf(currentTokenId);
if (currentTokenOwner == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
ownedTokenIndex++;
}
currentTokenId++;
}
return ownedTokenIds;
}
// Updated: There was no reason this needed to be virtual unless something plans on inheriting HR.
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
// Note: You don't REALLY need this require statement since nothing should be querying for non-existing tokens after reveal.
// That said, it's a public view method so gas efficiency shouldn't come into play.
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
// Updated: The old contract had unnecessary logic and conditionals about a _baseURI that was set by default.
if (revealed) {
return string(abi.encodePacked(baseURI, Strings.toString(_tokenId), uriSuffix));
}
else {
return hiddenMetadataUri;
}
}
// https://docs.opensea.io/docs/contract-level-metadata
function contractURI() public view returns (string memory) {
return CONTRACT_URI;
}
// Updated: Public verification functionality
// This may not be necessary, but can be a nice to have.
function verifyPublicWL(address _address, bytes32[] memory _proof) public view returns (bool) {
return MerkleProof.verify(_proof, keccak256(abi.encodePacked(_address)), merkleRoot);
}
/*
*
$$$$$$\ $$$$$$$$\ $$\ $$\
$$ __$$\ $$ _____| $$ | \__|
$$ / $$ |$$\ $$\ $$\ $$$$$$$\ $$$$$$\ $$$$$$\ $$ | $$\ $$\ $$$$$$$\ $$$$$$$\ $$$$$$\ $$\ $$$$$$\ $$$$$$$\ $$$$$$$\
$$ | $$ |$$ | $$ | $$ |$$ __$$\ $$ __$$\ $$ __$$\ $$$$$\ $$ | $$ |$$ __$$\ $$ _____|\_$$ _| $$ |$$ __$$\ $$ __$$\ $$ _____|
$$ | $$ |$$ | $$ | $$ |$$ | $$ |$$$$$$$$ |$$ | \__| $$ __|$$ | $$ |$$ | $$ |$$ / $$ | $$ |$$ / $$ |$$ | $$ |\$$$$$$\
$$ | $$ |$$ | $$ | $$ |$$ | $$ |$$ ____|$$ | $$ | $$ | $$ |$$ | $$ |$$ | $$ |$$\ $$ |$$ | $$ |$$ | $$ | \____$$\
$$$$$$ |\$$$$$\$$$$ |$$ | $$ |\$$$$$$$\ $$ | $$ | \$$$$$$ |$$ | $$ |\$$$$$$$\ \$$$$ |$$ |\$$$$$$ |$$ | $$ |$$$$$$$ |
\______/ \_____\____/ \__| \__| \_______|\__| \__| \______/ \__| \__| \_______| \____/ \__| \______/ \__| \__|\_______/
*
*/
// Note: Again, these aren't REALLY necessary if the mint numbers aren't going to change.
// That said, leaving for posterity/compatability.
function setPublicWhitelistedAddressLimit(uint256 _limit) public onlyOwner {
mintedPublicWhitelistAddressLimit = _limit;
}
function setPublicAddressLimit(uint256 _limit) public onlyOwner {
mintedPublicAddressLimit = _limit;
}
function setBaseURI(string memory _baseUri) public onlyOwner {
baseURI = _baseUri;
}
// Note: I don't see this needing to change, especially at this point.
// But, again, leaving for posterity/compatability.
function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner {
hiddenMetadataUri = _hiddenMetadataUri;
}
// Updated: This is a new method that the developers can call if they don't want to make separate calls
// Should save a touch of gas plus handles reveal/URI in one swoop.
function revealCollection(bool _revealed, string memory _baseUri) public onlyOwner {
revealed = _revealed;
baseURI = _baseUri;
}
// https://docs.opensea.io/docs/contract-level-metadata
function setContractURI(string memory _contractURI) public onlyOwner {
CONTRACT_URI = _contractURI;
}
// Note: Another option is to inherit Pausable without implementing the logic yourself.
// This is fine for now and I'm keeping it for compatability with v1
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/Pausable.sol
function setPaused(bool _state) public onlyOwner {
paused = _state;
}
function setRevealed(bool _state) public onlyOwner {
revealed = _state;
}
// Updated: The publicSale/publicWhitelisted variables now function as an on/off switch.
// If publicSale is enabled, then WL cannot mint and vice-versa
// Dev minting can now happen
function setPublicSale(bool _state) public onlyOwner {
publicSale = _state;
publicWhitelisted = !_state;
}
function setPublicWhitelisted(bool _state) public onlyOwner {
publicWhitelisted = _state;
publicSale = !_state;
}
// Updated: Added a setter for the privateWLAddress variable in case the devs wanted to change it.
// This was hard-coded in the previous version.
function setPrivateWLAddress(address _privateWLAddress) public onlyOwner {
privateWLAddress = _privateWLAddress;
}
// Updated: This functionality was ONLY handled by the constructor in the previous version.
// This did not allow for WL additions/removals
function setPublicMerkleRoot(bytes32 _merkleRoot) external onlyOwner {
merkleRoot = _merkleRoot;
}
// Updated: Added a setter for the communityWallet variable in case the devs wanted to change it.
function setCommunityWalletAddress(address _communityWalletAddress) public onlyOwner {
communityWallet = _communityWalletAddress;
}
// Updated: Added a setter for the teamWallet variable in case the devs wanted to change it.
function setTeamWalletAddress(address _teamWalletAddress) public onlyOwner {
teamWallet = _teamWalletAddress;
}
// Updated: Added functionality for withdrawal payments as well
// Note: The inspiration for this withdrawal method came from MD's work on Kiwami.
// Be sure to check out their contract for the OG - https://etherscan.io/address/0x701a038af4bd0fc9b69a829ddcb2f61185a49568#code
// Thanks to @_MouseDev for the big brain ideas.
function withdraw() external payable onlyOwner {
// Get the current funds to calculate community percentage
uint256 currBalance = address(this).balance;
// Note: This is the withdrawal to the doylerAddress - MINT FEES ONLY
(bool succ, ) = payable(doylerAddress).call{
value: doylerPayable
}("");
require(succ, "Doyler transfer failed");
// Note: There is TECHNICALLY a re-entrancy issue if doylerAddress was a contract by doing this after the transfer
// That said, it's clearly NOT a contract and that account cannot call withdraw()
// Just making sure I get paid before it's 0ed out!
doylerPayable = 0;
// Withdraw 55% of the ENTIRE balance to the community wallet.
// Note: If developers add any extra funds or people over pay, this will also get withdrawn here.
(succ, ) = payable(communityWallet).call{
value: (currBalance * 55) / 100
}("");
require(succ, "Community transfer failed");
// Withdraw the ENTIRE remaining balance to the team wallet.
(succ, ) = payable(teamWallet).call{
value: address(this).balance
}("");
require(succ, "Team transfer failed");
}
// Updated: Added owner-only mint functionality to "Airdrop" the old NFTs to the original owners
// There are cooler and more efficient ways
function mintToOwner(uint256 quantity, address receiver) public onlyOwner mintCompliance(quantity) {
_safeMint(receiver, quantity);
}
/*
*
$$\ $$\ $$\ $$\ $$$$$$\ $$\
$$$\ $$$ | $$ |\__|$$ __$$\ \__|
$$$$\ $$$$ | $$$$$$\ $$$$$$$ |$$\ $$ / \__|$$\ $$$$$$\ $$$$$$\ $$$$$$$\
$$\$$\$$ $$ |$$ __$$\ $$ __$$ |$$ |$$$$\ $$ |$$ __$$\ $$ __$$\ $$ _____|
$$ \$$$ $$ |$$ / $$ |$$ / $$ |$$ |$$ _| $$ |$$$$$$$$ |$$ | \__|\$$$$$$\
$$ |\$ /$$ |$$ | $$ |$$ | $$ |$$ |$$ | $$ |$$ ____|$$ | \____$$\
$$ | \_/ $$ |\$$$$$$ |\$$$$$$$ |$$ |$$ | $$ |\$$$$$$$\ $$ | $$$$$$$ |
\__| \__| \______/ \_______|\__|\__| \__| \_______|\__| \_______/
*
*/
// Note: Something this simple doesn't HAVE to be a modifier, but it saves a little duplication
// Updated: Removed the unnecessary isValidateEvent logic
// Updated: Removed other unnecessary require statements
modifier mintCompliance(uint256 quantity) {
require(!paused, "Contract is paused");
require(totalSupply() + quantity <= MAX_SUPPLY, "Not enough mints left");
// Note: This wasn't in the original contract, and adding it only costs like 21 gas/mint
require(tx.origin == msg.sender, "No contract minting");
_;
}
}
|
Updated: Public verification functionality This may not be necessary, but can be a nice to have.
|
function verifyPublicWL(address _address, bytes32[] memory _proof) public view returns (bool) {
return MerkleProof.verify(_proof, keccak256(abi.encodePacked(_address)), merkleRoot);
}
$$$$$$\ $$$$$$$$\ $$\ $$\
$$ __$$\ $$ _____| $$ | \__|
$$ / $$ |$$\ $$\ $$\ $$$$$$$\ $$$$$$\ $$$$$$\ $$ | $$\ $$\ $$$$$$$\ $$$$$$$\ $$$$$$\ $$\ $$$$$$\ $$$$$$$\ $$$$$$$\
$$ | $$ |$$ | $$ | $$ |$$ __$$\ $$ __$$\ $$ __$$\ $$$$$\ $$ | $$ |$$ __$$\ $$ _____|\_$$ _| $$ |$$ __$$\ $$ __$$\ $$ _____|
$$ | $$ |$$ | $$ | $$ |$$ | $$ |$$$$$$$$ |$$ | \__| $$ __|$$ | $$ |$$ | $$ |$$ / $$ | $$ |$$ / $$ |$$ | $$ |\$$$$$$\
$$ | $$ |$$ | $$ | $$ |$$ | $$ |$$ ____|$$ | $$ | $$ | $$ |$$ | $$ |$$ | $$ |$$\ $$ |$$ | $$ |$$ | $$ | \____$$\
$$$$$$ |\$$$$$\$$$$ |$$ | $$ |\$$$$$$$\ $$ | $$ | \$$$$$$ |$$ | $$ |\$$$$$$$\ \$$$$ |$$ |\$$$$$$ |$$ | $$ |$$$$$$$ |
\______/ \_____\____/ \__| \__| \_______|\__| \__| \______/ \__| \__| \_______| \____/ \__| \______/ \__| \__|\_______/
| 2,323,526
|
./partial_match/80001/0xbFABf2373eEFf171E4462819ba5E51e1F842e51c/sources/contracts/farmings/AlgebraEternalFarming.sol
|
@inheritdoc IAlgebraEternalFarming
|
function enterFarming(IncentiveKey memory key, uint256 tokenId) external override onlyFarmingCenter {
if (isEmergencyWithdrawActivated) revert emergencyActivated();
(bytes32 incentiveId, int24 tickLower, int24 tickUpper, uint128 liquidity, address virtualPoolAddress) = _enterFarming(key, tokenId);
IAlgebraEternalVirtualPool virtualPool = IAlgebraEternalVirtualPool(virtualPoolAddress);
(uint256 innerRewardGrowth0, uint256 innerRewardGrowth1) = _getInnerRewardsGrowth(virtualPool, tickLower, tickUpper);
farms[tokenId][incentiveId] = Farm(liquidity, tickLower, tickUpper, innerRewardGrowth0, innerRewardGrowth1);
emit FarmEntered(tokenId, incentiveId, liquidity);
}
| 8,815,070
|
/*
ERC20CompetitiveRewardModuleInfo
https://github.com/gysr-io/core
SPDX-License-Identifier: MIT
*/
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "../interfaces/IRewardModule.sol";
import "../ERC20CompetitiveRewardModule.sol";
import "../GysrUtils.sol";
/**
* @title ERC20 competitive reward module info library
*
* @notice this library provides read-only convenience functions to query
* additional information about the ERC20CompetitiveRewardModule contract.
*/
library ERC20CompetitiveRewardModuleInfo {
using GysrUtils for uint256;
/**
* @notice convenience function to get token metadata in a single call
* @param module address of reward module
* @return address
* @return name
* @return symbol
* @return decimals
*/
function token(address module)
public
view
returns (
address,
string memory,
string memory,
uint8
)
{
IRewardModule m = IRewardModule(module);
IERC20Metadata tkn = IERC20Metadata(m.tokens()[0]);
return (address(tkn), tkn.name(), tkn.symbol(), tkn.decimals());
}
/**
* @notice preview estimated rewards
* @param module address of reward module
* @param addr account address of interest for preview
* @param shares number of shares that would be unstaked
* @param gysr number of GYSR tokens that would be applied
* @return estimated reward
* @return estimated time multiplier
* @return estimated gysr multiplier
*/
function rewards(
address module,
address addr,
uint256 shares,
uint256 gysr
)
public
view
returns (
uint256,
uint256,
uint256
)
{
ERC20CompetitiveRewardModule m = ERC20CompetitiveRewardModule(module);
// get associated share seconds
uint256 rawShareSeconds;
uint256 bonusShareSeconds;
(rawShareSeconds, bonusShareSeconds) = userShareSeconds(
module,
addr,
shares
);
if (rawShareSeconds == 0) {
return (0, 0, 0);
}
uint256 timeBonus = (bonusShareSeconds * 1e18) / rawShareSeconds;
// apply gysr bonus
uint256 gysrBonus =
gysr.gysrBonus(shares, m.totalStakingShares(), m.usage());
bonusShareSeconds = (gysrBonus * bonusShareSeconds) / 1e18;
// compute rewards based on expected updates
uint256 reward =
(unlocked(module) * bonusShareSeconds) /
(totalShareSeconds(module) +
bonusShareSeconds -
rawShareSeconds);
return (reward, timeBonus, gysrBonus);
}
/**
* @notice compute effective unlocked rewards
* @param module address of reward module
* @return estimated current unlocked rewards
*/
function unlocked(address module) public view returns (uint256) {
ERC20CompetitiveRewardModule m = ERC20CompetitiveRewardModule(module);
// compute expected updates to global totals
uint256 deltaUnlocked;
address tkn = m.tokens()[0];
uint256 totalLockedShares = m.lockedShares(tkn);
if (totalLockedShares != 0) {
uint256 sharesToUnlock;
for (uint256 i = 0; i < m.fundingCount(tkn); i++) {
sharesToUnlock = sharesToUnlock + m.unlockable(tkn, i);
}
deltaUnlocked =
(sharesToUnlock * m.totalLocked()) /
totalLockedShares;
}
return m.totalUnlocked() + deltaUnlocked;
}
/**
* @notice compute user share seconds for given number of shares
* @param module module contract address
* @param addr user address
* @param shares number of shares
* @return raw share seconds
* @return time bonus share seconds
*/
function userShareSeconds(
address module,
address addr,
uint256 shares
) public view returns (uint256, uint256) {
require(shares > 0, "crmi1");
ERC20CompetitiveRewardModule m = ERC20CompetitiveRewardModule(module);
uint256 rawShareSeconds;
uint256 timeBonusShareSeconds;
// compute first-in-last-out, time bonus weighted, share seconds
uint256 i = m.stakeCount(addr);
while (shares > 0) {
require(i > 0, "crmi2");
i -= 1;
uint256 s;
uint256 time;
(s, time) = m.stakes(addr, i);
time = block.timestamp - time;
// only redeem partial stake if more shares left than needed to burn
s = s < shares ? s : shares;
rawShareSeconds += (s * time);
timeBonusShareSeconds += ((s * time * m.timeBonus(time)) / 1e18);
shares -= s;
}
return (rawShareSeconds, timeBonusShareSeconds);
}
/**
* @notice compute total expected share seconds for a rewards module
* @param module address for reward module
* @return expected total shares seconds
*/
function totalShareSeconds(address module) public view returns (uint256) {
ERC20CompetitiveRewardModule m = ERC20CompetitiveRewardModule(module);
return
m.totalStakingShareSeconds() +
(block.timestamp - m.lastUpdated()) *
m.totalStakingShares();
}
}
|
compute effective unlocked rewards module address of reward module return estimated current unlocked rewards/ compute expected updates to global totals
|
function unlocked(address module) public view returns (uint256) {
ERC20CompetitiveRewardModule m = ERC20CompetitiveRewardModule(module);
uint256 deltaUnlocked;
address tkn = m.tokens()[0];
uint256 totalLockedShares = m.lockedShares(tkn);
if (totalLockedShares != 0) {
uint256 sharesToUnlock;
for (uint256 i = 0; i < m.fundingCount(tkn); i++) {
sharesToUnlock = sharesToUnlock + m.unlockable(tkn, i);
}
deltaUnlocked =
(sharesToUnlock * m.totalLocked()) /
totalLockedShares;
}
return m.totalUnlocked() + deltaUnlocked;
}
| 13,070,988
|
./partial_match/137/0x48304908669633459c9381CB538Ff7bffF3a8e43/sources/darkUSD.sol
|
This is needed to avoid costly repeat calls to different getter functions It is cheaper gas-wise to just dump everything and only use some of the info
|
function dusd_info() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
return (
);
}
| 3,525,548
|
./full_match/1/0x48Aca7352A34EeE4D324FfCee7F8352C99c7D22C/sources/src/v1/Nash21Manager.sol
|
@inheritdoc INash21Manager
|
function lock(bytes32 id) public onlyRole(DEFAULT_ADMIN_ROLE) {
locked[id] = true;
emit Locked(id, get[id]);
}
| 9,714,818
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IExtensionStorage} from "../../extensions/IExtensionStorage.sol";
import {ExtensionLib} from "./ExtensionLib.sol";
import {IExtension, TransferData} from "../../extensions/IExtension.sol";
import {ExtendableBase} from "./ExtendableBase.sol";
contract ExtendableRouter is ExtendableBase {
function _lookupExtension(bytes4 funcSig) internal view returns (address) {
return ExtensionLib._functionToExtensionContextAddress(funcSig);
}
function _callFunction(bytes4 funcSig) private {
// get extension context address from function selector
address toCall = _lookupExtension(funcSig);
require(toCall != address(0), "EXTROUTER: Function does not exist");
uint256 value = msg.value;
// Execute external function from facet using call and return any value.
assembly {
// copy function selector and any arguments
calldatacopy(0, 0, calldatasize())
// execute function call using the facet
let result := call(gas(), toCall, value, 0, calldatasize(), 0, 0)
// get any return value
returndatacopy(0, 0, returndatasize())
// return any return value or error back to the caller
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
function _registerExtension(address extension) internal virtual returns (bool) {
ExtensionLib._registerExtension(extension);
return true;
}
function _removeExtension(address extension) internal virtual returns (bool) {
ExtensionLib._removeExtension(extension);
return true;
}
function _disableExtension(address extension) internal virtual returns (bool) {
ExtensionLib._disableExtension(extension);
return true;
}
function _enableExtension(address extension) internal virtual returns (bool) {
ExtensionLib._enableExtension(extension);
return true;
}
function _allExtension() internal view virtual returns (address[] memory) {
return ExtensionLib._allExtensions();
}
function _isActiveExtension(address extension) internal view virtual returns (bool) {
return ExtensionLib._isActiveExtension(extension);
}
function _isContextAddress(address callsite) internal view virtual returns (bool) {
return ExtensionLib._isContextAddress(callsite);
}
function _isExtensionFunction(bytes4 funcSig) internal virtual view returns (bool) {
address facet = _lookupExtension(funcSig);
return _isContextAddress(facet);
}
function _invokeExtensionFunction() internal virtual {
address facet = _lookupExtension(msg.sig);
if (_isContextAddress(facet)) {
IExtensionStorage context = IExtensionStorage(payable(facet));
context.prepareCall(_msgSender());
}
_callFunction(msg.sig);
}
}
|
get extension context address from function selector Execute external function from facet using call and return any value. copy function selector and any arguments execute function call using the facet get any return value return any return value or error back to the caller
|
function _callFunction(bytes4 funcSig) private {
address toCall = _lookupExtension(funcSig);
require(toCall != address(0), "EXTROUTER: Function does not exist");
uint256 value = msg.value;
assembly {
calldatacopy(0, 0, calldatasize())
let result := call(gas(), toCall, value, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
| 7,285,895
|
pragma solidity ^0.4.24;
import "oraclize-api/usingOraclize.sol";
contract ConversionRate is usingOraclize {
uint256 public price;
uint public lastUpdated;
event LogNewOraclizeQuery(string description);
event LogCallback(string result, uint lastUpdated);
constructor() public payable {
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
}
function __callback(bytes32, string _result) public {
if (msg.sender != oraclize_cbAddress())
revert("Wrong sender");
// this parsing will return 15000 for "150.00" for example
price = parseInt(_result, 2);
lastUpdated = block.timestamp;
emit LogCallback(_result, lastUpdated);
}
function getConversionToSGD() external view returns (uint256) {
return price;
}
// Called when the contract is deployed by Truffle
// Should also be called periodically by the company to update the conversion rate
function updateConversionToSGD() public payable {
if (oraclize_getPrice("URL") > address(this).balance) {
emit LogNewOraclizeQuery("Oraclize query not sent, not enough ETH");
} else {
emit LogNewOraclizeQuery("Oraclize query was sent, standing by for the answer..");
oraclize_query("URL", "json(https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=SGD).SGD");
}
}
}
|
this parsing will return 15000 for "150.00" for example
|
function __callback(bytes32, string _result) public {
if (msg.sender != oraclize_cbAddress())
revert("Wrong sender");
price = parseInt(_result, 2);
lastUpdated = block.timestamp;
emit LogCallback(_result, lastUpdated);
}
| 952,769
|
// SPDX-License-Identifier: MIT
/**
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMWWWWWWWWWWWWWWWMMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMWWNXXKKKKKKKXXXXKKKKKKXXNWWMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMWNXKKKKXXNWWWWMMWWWWMWWWWNXXXKKKXNWMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMWNXKKKXNWMMMMMMMMMNOdxKWMMMMMMMMWNXKKKXNWMMMMMMMMMMMMMM
MMMMMMMMMMMMMWXKKKNWMMMMMMMMMMMMNx:;;l0WMMMMMMMMMMMWNK0KXWMMMMMMMMMMMM
MMMMMMMMMMMWXKKXWMMMMMMMMMMMMMMXd:;;;;cOWMMMMMMMMMMMMMWXKKXWMMMMMMMMMM
MMMMMMMMMWNKKXWMMMMMMMMMMMMMMWKo;;col:;:kNMMMMMMMMMMMMMMWX0KNWMMMMMMMM
MMMMMMMMWX0XWMMMMMMMMMMMMMMMWOl;;oKWXkc;:dXMMMMMMMMMMMMMMMWX0XWMMMMMMM
MMMMMMMNKKNWMMMMMMMMMMMMMMMNkc;:dXMMMWOc;;oKWMMMMMMMMMMMMMMWNKKNMMMMMM
MMMMMMNKKNMMMMMMMMMMMMMMMMNx:;:xNMMMMMW0l;;l0WMMMMMMMWMMMMMMMNKKNMMMMM
MMMMMNKKNMMMMMMMMMMMMMMMMXd:;ckNMMMMMMMMKo:;cOWMMMMXkxkXWMMMMMNKKNMMMM
MMMMWK0NMMMMMMMMMMMMMMMWKo;;l0WMMMMMMMMMMXx:;:xNMMW0lccxXMMMMMMN0KWMMM
MMMMX0XWMMMMMMWWMMMMMMWOl;;oKWMMMMMMMMMMMMNkc;:dXMMNklcoKMMMMMMMX0XMMM
MMMWKKNMMWK0OkkkkkkKWNkc;:dXMMMMMMMMMMMMMMMWOl;;oKWMXdcxNMMMMMMMNKKWMM
MMMN0XWMMWNXX0OdlccdKOc;:xNMMMWXKKXNWNNNNWWMW0o;;l0WNkdKWMMMMMMMWX0NMM
MMMX0XMMMMMMMMMN0dlcdOxoONMMMMW0xdddddodxk0KNWXd:;l0Kx0WMMMMMMMMMX0XMM
MMMX0NMMMMMMMMMMWXxlcoOXWMMMMWKkolclodkKNNNNWWMNxcxOkKWMMMMMMMMMMX0XMM
MMMX0XMMMMMMMMMMMMNklclkNMMWXklccodxdodKWMMMMMMMNKOkKWMMMMMMMMMMMX0XMM
MMMN0XWMMMMMMMMMMMMNOoclxXN0occcdKX0xlco0WMMMMMMNOOXMMMMMMMMMMMMMX0NMM
MMMWKKWMMMMMMMMMMMMMW0dccoxocccdKWMWNklclONMMMMXOONMMMMMMMMMMMMMWKKWMM
MMMMX0XMMMMMMMMMMMMMMWKdcccccco0WMMMMNOoclkNWWKk0NMMMMMMMMMMMMMMX0XWMM
MMMMWKKNMMMMMMMMMMMMMMMXxlcccckNMMMMMMW0oclxK0kKWMMMMMMMMMMMMMMNKKWMMM
MMMMMN0KWMMMMMMMMMMMMMMMNklccoKWMMMMMMMWKdlcoxKWMMMMMMMMMMMMMMWK0NMMMM
MMMMMMN0KWMMMMMMMMMMMMMMMNOod0KXWMMMMMMNK0xoxXWMMMMMMMMMMMMMMWK0NMMMMM
MMMMMMMN0KNMMMMMMMMMMMMMMMWXKkll0WMMMMXdcoOKNMMMMMMMMMMMMMMMNK0NMMMMMM
MMMMMMMMNK0XWMMMMMMMMMMMMMMMNd:;cOWMWKo:;c0WMMMMMMMMMMMMMMWX0KNMMMMMMM
MMMMMMMMMWXKKNWMMMMMMMMMMMMMMXd:;cx0kl;;l0WMMMMMMMMMMMMMWNKKXWMMMMMMMM
MMMMMMMMMMMWX0KNWMMMMMMMMMMMMMNkc;;::;:oKWMMMMMMMMMMMMWNK0XWMMMMMMMMMM
MMMMMMMMMMMMMNXKKXNWMMMMMMMMMMMWOc;;;:dXMMMMMMMMMMMWNXKKXWMMMMMMMMMMMM
MMMMMMMMMMMMMMMWNKKKXNWMMMMMMMMMW0l:ckNMMMMMMMMMWNXKKKNWMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMWNXKKKXXNWWWMMMMX0KWMMMWWWNXXKKKXNWMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMWWNXXKKKKKXXXXXXXXXXKKKKXXNWWMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMWWNNNNNNNNNNNNWWWMMMMMMMMMMMMMMMMMMMMMMMMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
---------------------- [ WPSmartContracts.com ] ----------------------
[ Blockchain Made Easy ]
|
| ERC-721 NFT Token Marketplace
|
|----------------------------
|
| Flavors
|
| > Suika v.2: Standard ERC-721 Token with Marketplace
| Supports Payment with Tokens, and royalties
|
*/
pragma solidity ^0.8.2;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/**
* @dev Collection of functions related to the address type
*/
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;
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");
(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");
(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");
(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");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal 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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
contract ERC721Mochi is ERC721, ERC721Enumerable, ERC721URIStorage, AccessControlEnumerable, ERC721Burnable {
using Counters for Counters.Counter;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
Counters.Counter private _tokenIdCounter;
bool public anyoneCanMint;
constructor(address owner, string memory name, string memory symbol, bool _anyoneCanMint) ERC721(name, symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, owner);
_setupRole(MINTER_ROLE, owner);
anyoneCanMint = _anyoneCanMint;
}
function autoMint(string memory _tokenURI, address to) public onlyMinter {
uint id;
do {
_tokenIdCounter.increment();
id = _tokenIdCounter.current();
} while(_exists(id));
_mint(to, id);
_setTokenURI(id, _tokenURI);
}
function mint(address to, uint256 tokenId) public onlyMinter {
_mint(to, tokenId);
}
function safeMint(address to, uint256 tokenId) public onlyMinter {
_safeMint(to, tokenId);
}
function isMinter(address account) public view returns (bool) {
return hasRole(MINTER_ROLE, account);
}
function safeMint(address to, uint256 tokenId, bytes memory _data) public onlyMinter {
_safeMint(to, tokenId, _data);
}
function _burn(uint256 tokenId) internal virtual override(ERC721, ERC721URIStorage) {
ERC721URIStorage._burn(tokenId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable, AccessControlEnumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function addMinter(address account) public onlyRole(MINTER_ROLE) {
grantRole(MINTER_ROLE, account);
}
function canIMint() public view returns (bool) {
return anyoneCanMint || isMinter(msg.sender);
}
/**
* Open modifier to anyone can mint possibility
*/
modifier onlyMinter() {
string memory mensaje;
require(
canIMint(),
"MinterRole: caller does not have the Minter role"
);
_;
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
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.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
contract EIP20 {
uint256 public totalSupply;
uint256 constant private MAX_UINT256 = 2**256 - 1;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show.
string public symbol; //An identifier: eg SBX
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
constructor(
uint256 _initialAmount,
string memory _tokenName,
uint8 _decimalUnits,
string memory _tokenSymbol
) {
balances[msg.sender] = _initialAmount; // Give the creator all initial tokens
totalSupply = _initialAmount; // Update total supply
name = _tokenName; // Set the name for display purposes
decimals = _decimalUnits; // Amount of decimals for display purposes
symbol = _tokenSymbol; // Set the symbol for display purposes
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 _allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && _allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (_allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title ERC721Suika
* ERC-721 Marketplace with tokens and royalties support
*/
contract ERC721Suika is ERC721Mochi, ReentrancyGuard {
using SafeMath for uint256;
using Address for address payable;
using Address for address;
// admin address, the owner of the marketplace
address payable admin;
address public contract_owner;
// ERC20 token to be used for payments
EIP20 public payment_token;
// commission rate is a value from 0 to 100
uint256 commissionRate;
// royalties commission rate is a value from 0 to 100
uint256 royaltiesCommissionRate;
// nft item creators list, used to pay royalties
mapping(uint256 => address) public creators;
// last price sold or auctioned
mapping(uint256 => uint256) public soldFor;
// Mapping from token ID to sell price in Ether or to bid price, depending if it is an auction or not
mapping(uint256 => uint256) public sellBidPrice;
// Mapping payment address for tokenId
mapping(uint256 => address payable) private _wallets;
event Sale(uint256 indexed tokenId, address indexed from, address indexed to, uint256 value);
event Commission(uint256 indexed tokenId, address indexed to, uint256 value, uint256 rate, uint256 total);
event Royalty(uint256 indexed tokenId, address indexed to, uint256 value, uint256 rate, uint256 total);
// Auction data
struct Auction {
// Parameters of the auction. Times are either
// absolute unix timestamps (seconds since 1970-01-01)
// or time periods in seconds.
address payable beneficiary;
uint auctionEnd;
// Current state of the auction.
address payable highestBidder;
uint highestBid;
// Set to true at the end, disallows any change
bool open;
// minimum reserve price in wei
uint256 reserve;
}
// mapping auctions for each tokenId
mapping(uint256 => Auction) public auctions;
// Events that will be fired on changes.
event Refund(address bidder, uint amount);
event HighestBidIncreased(address indexed bidder, uint amount, uint256 tokenId);
event AuctionEnded(address winner, uint amount);
event LimitSell(address indexed from, address indexed to, uint256 amount);
event LimitBuy(address indexed from, address indexed to, uint256 amount);
event MarketSell(address indexed from, address indexed to, uint256 amount);
event MarketBuy(address indexed from, address indexed to, uint256 amount);
constructor(
EIP20 _payment_token, address _owner, address payable _admin,
uint256 _commissionRate, uint256 _royaltiesCommissionRate, string memory name, string memory symbol, bool _anyoneCanMint)
ERC721Mochi(_owner, name, symbol, _anyoneCanMint)
{
admin = _admin;
contract_owner = _owner;
require(_commissionRate<=100, "ERC721Suika: Commission rate has to be between 0 and 100");
commissionRate = _commissionRate;
royaltiesCommissionRate = _royaltiesCommissionRate;
payment_token = _payment_token;
}
function canSell(uint256 tokenId) public view returns (bool) {
return (ownerOf(tokenId)==msg.sender && !auctions[tokenId].open);
}
// Sell option for a fixed price
function sell(uint256 tokenId, uint256 price, address payable wallet) public {
// onlyOwner
require(ownerOf(tokenId)==msg.sender, "ERC721Suika: Only owner can sell this item");
// cannot set a price if auction is activated
require(!auctions[tokenId].open, "ERC721Suika: Cannot sell an item which has an active auction");
// set sell price for index
sellBidPrice[tokenId] = price;
// If price is zero, means not for sale
if (price>0) {
// approve the Index to the current contract
approve(address(this), tokenId);
// set wallet payment
_wallets[tokenId] = wallet;
}
}
// simple function to return the price of a tokenId
// returns: sell price, bid price, sold price, only one can be non zero
function getPrice(uint256 tokenId) public view returns (uint256, uint256, uint256) {
if (sellBidPrice[tokenId]>0) return (sellBidPrice[tokenId], 0, 0);
if (auctions[tokenId].highestBid>0) return (0, auctions[tokenId].highestBid, 0);
return (0, 0, soldFor[tokenId]);
}
function canBuy(uint256 tokenId) public view returns (uint256) {
if (!auctions[tokenId].open && sellBidPrice[tokenId]>0 && sellBidPrice[tokenId]>0 && getApproved(tokenId) == address(this)) {
return sellBidPrice[tokenId];
} else {
return 0;
}
}
// Buy option
function buy(uint256 tokenId) public nonReentrant {
// is on sale
require(!auctions[tokenId].open && sellBidPrice[tokenId]>0, "ERC721Suika: The collectible is not for sale");
// transfer ownership
address owner = ownerOf(tokenId);
require(msg.sender!=owner, "ERC721Suika: The seller cannot buy his own collectible");
// we need to call a transferFrom from this contract, which is the one with permission to sell the NFT
callOptionalReturn(this, abi.encodeWithSelector(this.transferFrom.selector, owner, msg.sender, tokenId));
// calculate amounts
uint256 amount4admin = sellBidPrice[tokenId].mul(commissionRate).div(100);
uint256 amount4creator = sellBidPrice[tokenId].mul(royaltiesCommissionRate).div(100);
uint256 amount4owner = sellBidPrice[tokenId].sub(amount4admin).sub(amount4creator);
// to owner
require(payment_token.transferFrom(msg.sender, _wallets[tokenId], amount4owner), "Transfer failed.");
// to creator
if (amount4creator>0) {
require(payment_token.transferFrom(msg.sender, creators[tokenId], amount4creator), "Transfer failed.");
}
// to admin
if (amount4admin>0) {
require(payment_token.transferFrom(msg.sender, admin, amount4admin), "Transfer failed.");
}
emit Sale(tokenId, owner, msg.sender, sellBidPrice[tokenId]);
emit Commission(tokenId, owner, sellBidPrice[tokenId], commissionRate, amount4admin);
emit Royalty(tokenId, owner, sellBidPrice[tokenId], royaltiesCommissionRate, amount4creator);
soldFor[tokenId] = sellBidPrice[tokenId];
// close the sell
sellBidPrice[tokenId] = 0;
delete _wallets[tokenId];
}
function canAuction(uint256 tokenId) public view returns (bool) {
return (ownerOf(tokenId)==msg.sender && !auctions[tokenId].open && sellBidPrice[tokenId]==0);
}
// Instantiate an auction contract for a tokenId
function createAuction(uint256 tokenId, uint _closingTime, address payable _beneficiary, uint256 _reservePrice) public {
require(sellBidPrice[tokenId]==0, "ERC721Suika: The selected NFT is open for sale, cannot be auctioned");
require(!auctions[tokenId].open, "ERC721Suika: The selected NFT already has an auction");
require(ownerOf(tokenId)==msg.sender, "ERC721Suika: Only owner can auction this item");
auctions[tokenId].beneficiary = _beneficiary;
auctions[tokenId].auctionEnd = _closingTime;
auctions[tokenId].reserve = _reservePrice;
auctions[tokenId].open = true;
// approve the Index to the current contract
approve(address(this), tokenId);
}
function canBid(uint256 tokenId) public view returns (bool) {
if (!msg.sender.isContract() &&
auctions[tokenId].open &&
block.timestamp <= auctions[tokenId].auctionEnd &&
msg.sender != ownerOf(tokenId) &&
getApproved(tokenId) == address(this)
) {
return true;
} else {
return false;
}
}
/// Overrides minting function to keep track of item creators
function _mint(address to, uint256 tokenId) override internal {
creators[tokenId] = msg.sender;
super._mint(to, tokenId);
}
/// Bid on the auction with the value sent
/// together with this transaction.
/// The value will only be refunded if the
/// auction is not won.
function bid(uint256 tokenId, uint256 bid_value) public nonReentrant {
// Contracts cannot bid, because they can block the auction with a reentrant attack
require(!msg.sender.isContract(), "No script kiddies");
// auction has to be opened
require(auctions[tokenId].open, "No opened auction found");
// approve was lost
require(getApproved(tokenId) == address(this), "Cannot complete the auction");
// Revert the call if the bidding
// period is over.
require(
block.timestamp <= auctions[tokenId].auctionEnd,
"Auction already ended."
);
// If the bid is not higher, send the
// money back.
require(
bid_value > auctions[tokenId].highestBid,
"There already is a higher bid."
);
address owner = ownerOf(tokenId);
require(msg.sender!=owner, "ERC721Suika: The owner cannot bid his own collectible");
// return the funds to the previous bidder, if there is one
if (auctions[tokenId].highestBid>0) {
require(payment_token.transfer(auctions[tokenId].highestBidder, auctions[tokenId].highestBid), "Transfer failed.");
emit Refund(auctions[tokenId].highestBidder, auctions[tokenId].highestBid);
}
// now store the bid data
auctions[tokenId].highestBidder = payable(msg.sender);
// transfer tokens to contract
require(payment_token.transferFrom(msg.sender, address(this), bid_value), "Transfer failed.");
// register the highest bid value
auctions[tokenId].highestBid = bid_value;
emit HighestBidIncreased(msg.sender, bid_value, tokenId);
}
// anyone can execute withdraw if auction is opened and
// the bid time expired and the reserve was not met
// or
// the auction is openen but the contract is unable to transfer
function canWithdraw(uint256 tokenId) public view returns (bool) {
if (auctions[tokenId].open &&
(
(
block.timestamp >= auctions[tokenId].auctionEnd &&
auctions[tokenId].highestBid > 0 &&
auctions[tokenId].highestBid<auctions[tokenId].reserve
) ||
getApproved(tokenId) != address(this)
)
) {
return true;
} else {
return false;
}
}
/// Withdraw a bid when the auction is not finalized
function withdraw(uint256 tokenId) public nonReentrant {
require(canWithdraw(tokenId), "Conditions to withdraw are not met");
// transfer funds to highest bidder always
if (auctions[tokenId].highestBid > 0) {
require(payment_token.transfer(auctions[tokenId].highestBidder, auctions[tokenId].highestBid), "Transfer failed.");
}
// finalize the auction
delete auctions[tokenId];
}
function canFinalize(uint256 tokenId) public view returns (bool) {
if (auctions[tokenId].open &&
block.timestamp >= auctions[tokenId].auctionEnd &&
(
auctions[tokenId].highestBid>=auctions[tokenId].reserve ||
auctions[tokenId].highestBid==0
)
) {
return true;
} else {
return false;
}
}
// implement the auctionFinalize including the NFT transfer logic
function auctionFinalize(uint256 tokenId) public nonReentrant {
require(canFinalize(tokenId), "Cannot finalize");
if (auctions[tokenId].highestBid>0) {
// transfer the ownership of token to the highest bidder
address payable _highestBidder = auctions[tokenId].highestBidder;
// calculate payment amounts
uint256 amount4admin = auctions[tokenId].highestBid.mul(commissionRate).div(100);
uint256 amount4creator = auctions[tokenId].highestBid.mul(royaltiesCommissionRate).div(100);
uint256 amount4owner = auctions[tokenId].highestBid.sub(amount4admin).sub(amount4creator);
// to owner
require(payment_token.transfer(auctions[tokenId].beneficiary, amount4owner), "Transfer failed.");
// to creator
if (amount4creator>0) {
require(payment_token.transfer(creators[tokenId], amount4creator), "Transfer failed.");
}
// to admin
if (amount4admin>0) {
require(payment_token.transfer(admin, amount4admin), "Transfer failed.");
}
emit Sale(tokenId, auctions[tokenId].beneficiary, _highestBidder, auctions[tokenId].highestBid);
emit Royalty(tokenId, auctions[tokenId].beneficiary, auctions[tokenId].highestBid, royaltiesCommissionRate, amount4creator);
emit Commission(tokenId, auctions[tokenId].beneficiary, auctions[tokenId].highestBid, commissionRate, amount4admin);
// transfer ownership
address owner = ownerOf(tokenId);
// we need to call a transferFrom from this contract, which is the one with permission to sell the NFT
// transfer the NFT to the auction's highest bidder
callOptionalReturn(this, abi.encodeWithSelector(this.transferFrom.selector, owner, _highestBidder, tokenId));
soldFor[tokenId] = auctions[tokenId].highestBid;
}
emit AuctionEnded(auctions[tokenId].highestBidder, auctions[tokenId].highestBid);
// finalize the auction
delete auctions[tokenId];
}
// Bid query functions
function highestBidder(uint256 tokenId) public view returns (address payable) {
return auctions[tokenId].highestBidder;
}
function highestBid(uint256 tokenId) public view returns (uint256) {
return auctions[tokenId].highestBid;
}
/**
* @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(IERC721 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.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC721: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC721: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC721: ERC20 operation did not succeed");
}
}
// update contract fields
function updateAdmin(address payable _admin, uint256 _commissionRate, uint256 _royaltiesCommissionRate, bool _anyoneCanMint, EIP20 _payment_token) public {
require(msg.sender==contract_owner, "Only contract owner can do this");
admin = _admin;
commissionRate = _commissionRate;
royaltiesCommissionRate = _royaltiesCommissionRate;
anyoneCanMint = _anyoneCanMint;
payment_token = _payment_token;
}
// update owner
function updateOwner(address _contract_owner) public {
require(msg.sender==contract_owner, "Only contract owner can do this");
// grant roles to new owner
_setupRole(DEFAULT_ADMIN_ROLE, _contract_owner);
_setupRole(MINTER_ROLE, _contract_owner);
// revoke roles of old owner
revokeRole(MINTER_ROLE, contract_owner);
_setupRole(DEFAULT_ADMIN_ROLE, contract_owner);
// change ownership
contract_owner = _contract_owner;
}
}
|
Sell option for a fixed price onlyOwner cannot set a price if auction is activated set sell price for index If price is zero, means not for sale approve the Index to the current contract set wallet payment
|
function sell(uint256 tokenId, uint256 price, address payable wallet) public {
require(ownerOf(tokenId)==msg.sender, "ERC721Suika: Only owner can sell this item");
require(!auctions[tokenId].open, "ERC721Suika: Cannot sell an item which has an active auction");
sellBidPrice[tokenId] = price;
if (price>0) {
approve(address(this), tokenId);
_wallets[tokenId] = wallet;
}
}
| 1,140,413
|
./full_match/421613/0xba2691F82df09893618524a874D2aF746FC9e980/sources/contracts/core/SsovV4DatastoreClient.sol
|
Internal function to mint a debt position token to the address to mint the debt position to
|
function _mintDebtPositionToken(address to)
private
returns (uint256 tokenId)
{
return debtPositionMinter.mint(to);
}
| 11,581,533
|
./full_match/122/0xFAE02d404c327A1Eb2fB38eb89C38860a02D70e6/sources/contracts/LiquidStakingPool.sol
|
This handles the pool staking to validators Process the normal delegation of funds and redistribution _amount the value amount to be staked/
|
function _validatorStakeRedistribution(uint256 _amount) internal {
address currentValidator = _getCurrentValidator();
uint256 validatorDelegatedAmount = IConsensus(consensus()).stakeAmount(currentValidator);
uint256 availableAmount = IConsensus(consensus()).getMaxStake().sub(validatorDelegatedAmount);
if (availableAmount >= _amount) {
address payable consensusContract = payable(consensus());
address payable consensusContract = payable(consensus());
if(availableAmount > 0) {
}
uint256 remaining = _amount.sub(availableAmount);
address[] memory validatorList = getValidators();
uint256 currentDelegated = 0;
uint256 currentAvailable = 0;
for (uint256 i = 0; i < validatorList.length; i++) {
currentDelegated = IConsensus(consensus()).stakeAmount(validatorList[i]);
currentAvailable = IConsensus(consensus()).getMaxStake().sub(currentDelegated);
if (currentAvailable >= remaining) {
_setValidatorIndex(i);
remaining = 0;
break;
remaining = remaining.sub(currentAvailable);
}
}
require(remaining == 0, "excess amount");
}
}
| 16,366,188
|
./partial_match/42220/0x45ED71ddA0BCaa26aF6c578Fd6908E514D6c2d7d/sources/contracts/UniswapLiquiditySwapAdapter.sol
|
LendingPoolAddressesProvider contract Main registry of addresses part of or connected to the protocol, including permissioned roles - Acting also as factory of proxies and admin of those, so with right to change its implementations - Owned by the Aave Governance Aave/
|
interface ILendingPoolAddressesProvider {
event MarketIdSet(string newMarketId);
event LendingPoolUpdated(address indexed newAddress);
event ConfigurationAdminUpdated(address indexed newAddress);
event EmergencyAdminUpdated(address indexed newAddress);
event LendingPoolConfiguratorUpdated(address indexed newAddress);
event LendingPoolCollateralManagerUpdated(address indexed newAddress);
event PriceOracleUpdated(address indexed newAddress);
event LendingRateOracleUpdated(address indexed newAddress);
event ProxyCreated(bytes32 id, address indexed newAddress);
event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy);
function getMarketId() external view returns (string memory);
function setMarketId(string calldata marketId) external;
function setAddress(bytes32 id, address newAddress) external;
function setAddressAsProxy(bytes32 id, address impl) external;
function getAddress(bytes32 id) external view returns (address);
function getLendingPool() external view returns (address);
function setLendingPoolImpl(address pool) external;
function getLendingPoolConfigurator() external view returns (address);
function setLendingPoolConfiguratorImpl(address configurator) external;
function getLendingPoolCollateralManager() external view returns (address);
function setLendingPoolCollateralManager(address manager) external;
function getPoolAdmin() external view returns (address);
function setPoolAdmin(address admin) external;
function getEmergencyAdmin() external view returns (address);
function setEmergencyAdmin(address admin) external;
function getPriceOracle() external view returns (address);
function setPriceOracle(address priceOracle) external;
function getLendingRateOracle() external view returns (address);
function setLendingRateOracle(address lendingRateOracle) external;
}
| 3,499,470
|
./full_match/11155111/0x23e3Ce582115FeAc7B72CFf6a918F391efDB5477/sources/contracts/Vault.sol
|
guaranteedUsd stores the sum of (position.size - position.collateral) for all positions if a fee is charged on the collateral then guaranteedUsd should be increased by that fee amount since (position.size - position.collateral) would have increased by `fee` treat the deposited collateral as part of the pool fees need to be deducted from the pool since fees are deducted from position.collateral and collateral is treated as part of the pool
|
function increasePosition(address _account, address _collateralToken, address _indexToken, uint256 _sizeDelta, bool _isLong) external override nonReentrant {
_validate(isLeverageEnabled, 28);
_validateGasPrice();
_validateRouter(_account);
_validateTokens(_collateralToken, _indexToken, _isLong);
updateCumulativeFundingRate(_collateralToken);
bytes32 key = getPositionKey(_account, _collateralToken, _indexToken, _isLong);
Position storage position = positions[key];
uint256 price = _isLong ? getMaxPrice(_indexToken) : getMinPrice(_indexToken);
if (position.size == 0) {
position.averagePrice = price;
}
if (position.size > 0 && _sizeDelta > 0) {
position.averagePrice = getNextAveragePrice(_indexToken, position.size, position.averagePrice, _isLong, price, _sizeDelta, position.lastIncreasedTime);
}
uint256 fee = _collectMarginFees(_collateralToken, _sizeDelta, position.size, position.entryFundingRate);
uint256 collateralDelta = _transferIn(_collateralToken);
uint256 collateralDeltaUsd = tokenToUsdMin(_collateralToken, collateralDelta);
position.collateral = position.collateral.add(collateralDeltaUsd);
_validate(position.collateral >= fee, 29);
position.collateral = position.collateral.sub(fee);
position.entryFundingRate = cumulativeFundingRates[_collateralToken];
position.size = position.size.add(_sizeDelta);
position.lastIncreasedTime = block.timestamp;
_validate(position.size > 0, 30);
_validatePosition(position.size, position.collateral);
validateLiquidation(_account, _collateralToken, _indexToken, _isLong, true);
position.reserveAmount = position.reserveAmount.add(reserveDelta);
_increaseReservedAmount(_collateralToken, reserveDelta);
if (_isLong) {
_increaseGuaranteedUsd(_collateralToken, _sizeDelta.add(fee));
_decreaseGuaranteedUsd(_collateralToken, collateralDeltaUsd);
_increasePoolAmount(_collateralToken, collateralDelta);
_decreasePoolAmount(_collateralToken, usdToTokenMin(_collateralToken, fee));
if (globalShortSizes[_indexToken] == 0) {
globalShortAveragePrices[_indexToken] = price;
globalShortAveragePrices[_indexToken] = getNextGlobalShortAveragePrice(_indexToken, price, _sizeDelta);
}
globalShortSizes[_indexToken] = globalShortSizes[_indexToken].add(_sizeDelta);
}
emit IncreasePosition(key, _account, _collateralToken, _indexToken, collateralDeltaUsd, _sizeDelta, _isLong, price, fee);
emit UpdatePosition(key, position.size, position.collateral, position.averagePrice, position.entryFundingRate, position.reserveAmount, position.realisedPnl);
}
| 3,795,031
|
pragma solidity 0.5.12;
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/utils/Address.sol";
import "./Token/IERC677MultiBridgeToken.sol";
import "./IMultipleDistribution.sol";
import "./IDistribution.sol";
/// @dev Distributes Defimist Stake tokens for Private Offering and Advisors Reward.
contract MultipleDistribution is Ownable, IMultipleDistribution {
using SafeMath for uint256;
using Address for address;
/// @dev Emits when `initialize` method has been called.
/// @param token The address of ERC677MultiBridgeToken contract.
/// @param caller The address of the caller.
event Initialized(address token, address caller);
/// @dev Emits when the `Distribution` address has been set.
/// @param distribution `Distribution` contract address.
/// @param caller The address of the caller.
event DistributionAddressSet(address distribution, address caller);
/// @dev Emits when `withdraw` method has been called.
/// @param recipient Recipient address.
/// @param value Transferred value.
event Withdrawn(address recipient, uint256 value);
/// @dev Emits when `burn` method has been called.
/// @param value Burnt value.
event Burnt(uint256 value);
/// @dev Emits when `addParticipants` method has been called.
/// @param participants Participants addresses.
/// @param stakes Participants stakes.
/// @param caller The address of the caller.
event ParticipantsAdded(address[] participants, uint256[] stakes, address caller);
/// @dev Emits when `editParticipant` method has been called.
/// @param participant Participant address.
/// @param oldStake Old participant stake.
/// @param newStake New participant stake.
/// @param caller The address of the caller.
event ParticipantEdited(address participant, uint256 oldStake, uint256 newStake, address caller);
/// @dev Emits when `removeParticipant` method has been called.
/// @param participant Participant address.
/// @param stake Participant stake.
/// @param caller The address of the caller.
event ParticipantRemoved(address participant, uint256 stake, address caller);
/// @dev Emits when `finalizeParticipants` method has been called.
/// @param numberOfParticipants Number of participants.
/// @param caller The address of the caller.
event ParticipantsFinalized(uint256 numberOfParticipants, address caller);
uint256 public TOTAL_STAKE;
uint8 public POOL_NUMBER;
/// @dev The instance of ERC677MultiBridgeToken contract.
IERC677MultiBridgeToken public token;
/// @dev Distribution contract address.
address public distributionAddress;
/// @dev Participants addresses.
address[] public participants;
/// @dev Stake for a specified participant.
mapping (address => uint256) public participantStake;
/// @dev Amount of tokens that have already been withdrawn by a specified participant.
mapping (address => uint256) public paidAmount;
/// @dev Contains max balance (sum of all installments).
uint256 public maxBalance = 0;
/// @dev Boolean variable that indicates whether the contract was initialized.
bool public isInitialized = false;
/// @dev Boolean variable that indicates whether the participant set was finalized.
bool public isFinalized = false;
/// @dev Contains current sum of stakes.
uint256 public sumOfStakes = 0;
/// @dev Checks that the contract is initialized.
modifier initialized() {
require(isInitialized, "not initialized");
_;
}
/// @dev Checks that the participant set is not finalized.
modifier notFinalized() {
require(!isFinalized, "already finalized");
_;
}
constructor(uint8 _pool) public {
require(_pool == 3 || _pool == 4, "wrong pool number");
POOL_NUMBER = _pool;
if (POOL_NUMBER == 3) {
TOTAL_STAKE = 1970951 ether; // Private Offering supply. `ether` is used as the token has 18 decimals
} else {
TOTAL_STAKE = 651000 ether; // Advisors Reward supply. `ether` is used as the token has 18 decimals
}
}
/// @dev Adds participants. This function doesn't limit max gas consumption,
/// so adding too many participants can cause it to reach the out-of-gas error.
/// @param _participants The addresses of new participants.
/// @param _stakes The amounts of the tokens that belong to each participant.
function addParticipants(
address[] calldata _participants,
uint256[] calldata _stakes
) external onlyOwner notFinalized {
require(_participants.length == _stakes.length, "different arrays sizes");
for (uint256 i = 0; i < _participants.length; i++) {
require(_participants[i] != address(0), "invalid address");
require(_stakes[i] > 0, "the participant stake must be more than 0");
require(participantStake[_participants[i]] == 0, "participant already added");
participants.push(_participants[i]);
participantStake[_participants[i]] = _stakes[i];
sumOfStakes = sumOfStakes.add(_stakes[i]);
}
require(sumOfStakes <= TOTAL_STAKE, "wrong sum of values");
emit ParticipantsAdded(_participants, _stakes, msg.sender);
}
/// @dev Edits participant stake.
/// @param _participant Participant address.
/// @param _newStake New stake of the participant.
function editParticipant(
address _participant,
uint256 _newStake
) external onlyOwner notFinalized {
require(_participant != address(0), "invalid address");
uint256 oldStake = participantStake[_participant];
require(oldStake > 0, "the participant doesn't exist");
require(_newStake > 0, "the participant stake must be more than 0");
sumOfStakes = sumOfStakes.sub(oldStake).add(_newStake);
require(sumOfStakes <= TOTAL_STAKE, "wrong sum of values");
participantStake[_participant] = _newStake;
emit ParticipantEdited(_participant, oldStake, _newStake, msg.sender);
}
/// @dev Removes participant. This function doesn't limit max gas consumption,
/// so having too many participants can cause it to reach the out-of-gas error.
/// @param _participant Participant address.
function removeParticipant(
address _participant
) external onlyOwner notFinalized {
require(_participant != address(0), "invalid address");
uint256 stake = participantStake[_participant];
require(stake > 0, "the participant doesn't exist");
uint256 index = 0;
uint256 participantsLength = participants.length;
for (uint256 i = 0; i < participantsLength; i++) {
if (participants[i] == _participant) {
index = i;
break;
}
}
require(participants[index] == _participant, "the participant not found");
sumOfStakes = sumOfStakes.sub(stake);
participantStake[_participant] = 0;
address lastParticipant = participants[participants.length.sub(1)];
participants[index] = lastParticipant;
participants.length = participants.length.sub(1);
emit ParticipantRemoved(_participant, stake, msg.sender);
}
/// @dev Calculates unused stake and disables the following additions/edits.
function finalizeParticipants() external onlyOwner notFinalized {
uint256 unusedStake = TOTAL_STAKE.sub(sumOfStakes);
if (unusedStake > 0) {
participants.push(address(0));
participantStake[address(0)] = unusedStake;
}
isFinalized = true;
emit ParticipantsFinalized(participants.length, msg.sender);
}
/// @dev Initializes the contract after the token is created.
/// @param _tokenAddress The address of the STAKE token contract.
function initialize(
address _tokenAddress
) external {
require(msg.sender == distributionAddress, "wrong sender");
require(!isInitialized, "already initialized");
require(isFinalized, "not finalized");
require(_tokenAddress != address(0));
token = IERC677MultiBridgeToken(_tokenAddress);
isInitialized = true;
emit Initialized(_tokenAddress, msg.sender);
}
/// @dev The removed implementation of the ownership renouncing.
function renounceOwnership() public onlyOwner {
revert("not implemented");
}
/// @dev Sets the `Distribution` contract address.
/// @param _distributionAddress The `Distribution` contract address.
function setDistributionAddress(address _distributionAddress) external onlyOwner {
require(distributionAddress == address(0), "already set");
require(
address(this) == IDistribution(_distributionAddress).poolAddress(POOL_NUMBER),
"wrong address"
);
distributionAddress = _distributionAddress;
emit DistributionAddressSet(distributionAddress, msg.sender);
}
/// @dev Transfers a share to participant.
/// Can only be called by Private Offering or Advisors Reward participant
/// to withdraw their currently available share.
function withdraw() external {
uint256 amount = _withdraw(msg.sender);
emit Withdrawn(msg.sender, amount);
}
/// @dev Transfers unclaimed part to address(0).
function burn() external onlyOwner {
uint256 amount = _withdraw(address(0));
emit Burnt(amount);
}
/// @dev Updates an internal value of the balance to use it for correct
/// share calculation (see the `_withdraw` function) and prevents transferring
/// tokens to this contract not from the `Distribution` contract.
/// @param _from The address from which the tokens are transferred.
/// @param _value The amount of transferred tokens.
function onTokenTransfer(
address _from,
uint256 _value,
bytes calldata
) external returns (bool) {
require(msg.sender == address(token), "the caller can only be the token contract");
require(_from == distributionAddress, "the _from value can only be the distribution contract");
maxBalance = maxBalance.add(_value);
return true;
}
/// @dev Returns a total amount of tokens.
function poolStake() external view returns (uint256) {
return TOTAL_STAKE;
}
/// @dev Returns an array of participants.
function getParticipants() external view returns (address[] memory) {
return participants;
}
/// @dev Transfers a share to participant or unclaimed part to address(0).
/// Used by the `withdraw` and `burn` functions.
/// @param _recipient The address of a participant or address(0).
function _withdraw(address _recipient) internal initialized returns(uint256) {
uint256 stake = participantStake[_recipient];
require(stake > 0, "you are not a participant");
uint256 maxShare = maxBalance.mul(stake).div(TOTAL_STAKE);
uint256 currentShare = maxShare.sub(paidAmount[_recipient]);
require(currentShare > 0, "no tokens available to withdraw");
paidAmount[_recipient] = paidAmount[_recipient].add(currentShare);
token.transferDistribution(_recipient, currentShare);
return currentShare;
}
}
|
Calculates unused stake and disables the following additions/edits.
|
function finalizeParticipants() external onlyOwner notFinalized {
uint256 unusedStake = TOTAL_STAKE.sub(sumOfStakes);
if (unusedStake > 0) {
participants.push(address(0));
participantStake[address(0)] = unusedStake;
}
isFinalized = true;
emit ParticipantsFinalized(participants.length, msg.sender);
}
| 12,831,379
|
pragma solidity ^0.4.19;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library KeysUtils {
// Such order is important to load from state
struct Object {
uint32 gasPriceGwei;
uint32 gasLimit;
uint32 timestamp;
address contractAddress;
}
function toKey(Object _obj) internal pure returns (bytes32) {
return toKey(_obj.contractAddress, _obj.timestamp, _obj.gasLimit, _obj.gasPriceGwei);
}
function toKeyFromStorage(Object storage _obj) internal view returns (bytes32 _key) {
assembly {
_key := sload(_obj_slot)
}
}
function toKey(address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) internal pure returns (bytes32 result) {
result = 0x0000000000000000000000000000000000000000000000000000000000000000;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - address (20 bytes)
// ^^^^^^^^ - timestamp (4 bytes)
// ^^^^^^^^ - gas limit (4 bytes)
// ^^^^^^^^ - gas price (4 bytes)
assembly {
result := or(result, mul(_address, 0x1000000000000000000000000))
result := or(result, mul(and(_timestamp, 0xffffffff), 0x10000000000000000))
result := or(result, mul(and(_gasLimit, 0xffffffff), 0x100000000))
result := or(result, and(_gasPrice, 0xffffffff))
}
}
function toMemoryObject(bytes32 _key, Object memory _dest) internal pure {
assembly {
mstore(_dest, and(_key, 0xffffffff))
mstore(add(_dest, 0x20), and(div(_key, 0x100000000), 0xffffffff))
mstore(add(_dest, 0x40), and(div(_key, 0x10000000000000000), 0xffffffff))
mstore(add(_dest, 0x60), div(_key, 0x1000000000000000000000000))
}
}
function toObject(bytes32 _key) internal pure returns (Object memory _dest) {
toMemoryObject(_key, _dest);
}
function toStateObject(bytes32 _key, Object storage _dest) internal {
assembly {
sstore(_dest_slot, _key)
}
}
function getTimestamp(bytes32 _key) internal pure returns (uint result) {
assembly {
result := and(div(_key, 0x10000000000000000), 0xffffffff)
}
}
}
contract TransferToken is Ownable {
function transferToken(ERC20Basic _token, address _to, uint _value) public onlyOwner {
_token.transfer(_to, _value);
}
}
contract JouleProxyAPI {
/**
* Function hash is: 0x73027f6d
*/
function callback(address _contract) public;
}
contract CheckableContract {
event Checked();
/*
* Function hash is 0x919840ad.
*/
function check() public;
}
contract JouleAPI {
event Invoked(address indexed _address, bool _status, uint _usedGas);
event Registered(address indexed _address, uint _timestamp, uint _gasLimit, uint _gasPrice);
/**
* @dev Registers the specified contract to invoke at the specified time with the specified gas and price.
* @notice It required amount of ETH as value, to cover gas usage. See getPrice method.
*
* @param _address Contract's address. Contract MUST implements Checkable interface.
* @param _timestamp Timestamp at what moment contract should be called. It MUST be in future.
* @param _gasLimit Gas which will be posted to call.
* @param _gasPrice Gas price which is recommended to use for this invocation.
*/
function register(address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) external payable returns (uint);
/**
* @dev Invokes next contracts in the queue.
* @notice Eth amount to cover gas will be returned if gas price is equal or less then specified for contract. Check getTop for right gas price.
* @return Reward amount.
*/
function invoke() public returns (uint);
/**
* @dev Invokes the top contract in the queue.
* @notice Eth amount to cover gas will be returned if gas price is equal or less then specified for contract. Check getTop for right gas price.
* @return Reward amount.
*/
function invokeTop() public returns (uint);
/**
* @dev Calculates required to register amount of WEI.
*
* @param _gasLimit Gas which will be posted to call.
* @param _gasPrice Gas price which is recommended to use for this invocation.
* @return Amount in wei.
*/
function getPrice(uint _gasLimit, uint _gasPrice) external view returns (uint);
/**
* @dev Gets how many contracts are registered (and not invoked).
*/
function getCount() public view returns (uint);
/**
* @dev Gets top contract (the next to invoke).
*
* @return contractAddress The contract address.
* @return timestamp The invocation timestamp.
* @return gasLimit The invocation maximum gas.
* @return gasPrice The invocation expected price.
*/
function getTop() external view returns (
address contractAddress,
uint timestamp,
uint gasLimit,
uint gasPrice
);
/**
* @dev Gets top _count contracts (in order to invoke).
*
* @param _count How many records will be returned.
* @return addresses The contracts addresses.
* @return timestamps The invocation timestamps.
* @return gasLimits The invocation gas limits.
* @return gasPrices The invocation expected prices.
*/
function getTop(uint _count) external view returns (
address[] addresses,
uint[] timestamps,
uint[] gasLimits,
uint[] gasPrices
);
/**
* @dev Gets actual code version.
* @return Code version. Mask: 0xff.0xff.0xffff-0xffffffff (major.minor.build-hash)
*/
function getVersion() external view returns (bytes8);
}
contract usingConsts {
uint constant GWEI = 0.001 szabo;
// this value influence to the reward price! do not change for already registered contracts!
uint constant IDLE_GAS = 22273;
uint constant MAX_GAS = 4000000;
// Code version
bytes8 constant VERSION = 0x0100001300000000;
// ^^ - major
// ^^ - minor
// ^^^^ - build
// ^^^^^^^^ - git hash
}
contract JouleIndex {
using KeysUtils for bytes32;
uint constant YEAR = 0x1DFE200;
// year -> month -> day -> hour
mapping (bytes32 => bytes32) index;
bytes32 head;
function insert(bytes32 _key) public {
uint timestamp = _key.getTimestamp();
bytes32 year = toKey(timestamp, YEAR);
bytes32 headLow;
bytes32 headHigh;
(headLow, headHigh) = fromValue(head);
if (year < headLow || headLow == 0 || year > headHigh) {
if (year < headLow || headLow == 0) {
headLow = year;
}
if (year > headHigh) {
headHigh = year;
}
head = toValue(headLow, headHigh);
}
bytes32 week = toKey(timestamp, 1 weeks);
bytes32 low;
bytes32 high;
(low, high) = fromValue(index[year]);
if (week < low || week > high) {
if (week < low || low == 0) {
low = week;
}
if (week > high) {
high = week;
}
index[year] = toValue(low, high);
}
(low, high) = fromValue(index[week]);
bytes32 hour = toKey(timestamp, 1 hours);
if (hour < low || hour > high) {
if (hour < low || low == 0) {
low = hour;
}
if (hour > high) {
high = hour;
}
index[week] = toValue(low, high);
}
(low, high) = fromValue(index[hour]);
bytes32 minute = toKey(timestamp, 1 minutes);
if (minute < low || minute > high) {
if (minute < low || low == 0) {
low = minute;
}
if (minute > high) {
high = minute;
}
index[hour] = toValue(low, high);
}
(low, high) = fromValue(index[minute]);
bytes32 tsKey = toKey(timestamp);
if (tsKey < low || tsKey > high) {
if (tsKey < low || low == 0) {
low = tsKey;
}
if (tsKey > high) {
high = tsKey;
}
index[minute] = toValue(low, high);
}
index[tsKey] = _key;
}
function findFloorKeyYear(uint _timestamp, bytes32 _low, bytes32 _high) view internal returns (bytes32) {
bytes32 year = toKey(_timestamp, YEAR);
if (year < _low) {
return 0;
}
if (year > _high) {
// week
(low, high) = fromValue(index[_high]);
// hour
(low, high) = fromValue(index[high]);
// minute
(low, high) = fromValue(index[high]);
// ts
(low, high) = fromValue(index[high]);
return index[high];
}
bytes32 low;
bytes32 high;
while (year >= _low) {
(low, high) = fromValue(index[year]);
if (low != 0) {
bytes32 key = findFloorKeyWeek(_timestamp, low, high);
if (key != 0) {
return key;
}
}
// 0x1DFE200 = 52 weeks = 31449600
assembly {
year := sub(year, 0x1DFE200)
}
}
return 0;
}
function findFloorKeyWeek(uint _timestamp, bytes32 _low, bytes32 _high) view internal returns (bytes32) {
bytes32 week = toKey(_timestamp, 1 weeks);
if (week < _low) {
return 0;
}
bytes32 low;
bytes32 high;
if (week > _high) {
// hour
(low, high) = fromValue(index[_high]);
// minute
(low, high) = fromValue(index[high]);
// ts
(low, high) = fromValue(index[high]);
return index[high];
}
while (week >= _low) {
(low, high) = fromValue(index[week]);
if (low != 0) {
bytes32 key = findFloorKeyHour(_timestamp, low, high);
if (key != 0) {
return key;
}
}
// 1 weeks = 604800
assembly {
week := sub(week, 604800)
}
}
return 0;
}
function findFloorKeyHour(uint _timestamp, bytes32 _low, bytes32 _high) view internal returns (bytes32) {
bytes32 hour = toKey(_timestamp, 1 hours);
if (hour < _low) {
return 0;
}
bytes32 low;
bytes32 high;
if (hour > _high) {
// minute
(low, high) = fromValue(index[_high]);
// ts
(low, high) = fromValue(index[high]);
return index[high];
}
while (hour >= _low) {
(low, high) = fromValue(index[hour]);
if (low != 0) {
bytes32 key = findFloorKeyMinute(_timestamp, low, high);
if (key != 0) {
return key;
}
}
// 1 hours = 3600
assembly {
hour := sub(hour, 3600)
}
}
return 0;
}
function findFloorKeyMinute(uint _timestamp, bytes32 _low, bytes32 _high) view internal returns (bytes32) {
bytes32 minute = toKey(_timestamp, 1 minutes);
if (minute < _low) {
return 0;
}
bytes32 low;
bytes32 high;
if (minute > _high) {
// ts
(low, high) = fromValue(index[_high]);
return index[high];
}
while (minute >= _low) {
(low, high) = fromValue(index[minute]);
if (low != 0) {
bytes32 key = findFloorKeyTimestamp(_timestamp, low, high);
if (key != 0) {
return key;
}
}
// 1 minutes = 60
assembly {
minute := sub(minute, 60)
}
}
return 0;
}
function findFloorKeyTimestamp(uint _timestamp, bytes32 _low, bytes32 _high) view internal returns (bytes32) {
bytes32 tsKey = toKey(_timestamp);
if (tsKey < _low) {
return 0;
}
if (tsKey > _high) {
return index[_high];
}
while (tsKey >= _low) {
bytes32 key = index[tsKey];
if (key != 0) {
return key;
}
assembly {
tsKey := sub(tsKey, 1)
}
}
return 0;
}
function findFloorKey(uint _timestamp) view public returns (bytes32) {
// require(_timestamp > 0xffffffff);
// if (_timestamp < 1515612415) {
// return 0;
// }
bytes32 yearLow;
bytes32 yearHigh;
(yearLow, yearHigh) = fromValue(head);
return findFloorKeyYear(_timestamp, yearLow, yearHigh);
}
function toKey(uint _timestamp, uint rounder) pure internal returns (bytes32 result) {
// 0x0...00000000000000000
// ^^^^^^^^ - rounder marker (eg, to avoid crossing first day of year with year)
// ^^^^^^^^ - rounded moment (year, week, etc)
assembly {
result := or(mul(rounder, 0x100000000), mul(div(_timestamp, rounder), rounder))
}
}
function toValue(bytes32 _lowKey, bytes32 _highKey) pure internal returns (bytes32 result) {
assembly {
result := or(mul(_lowKey, 0x10000000000000000), _highKey)
}
}
function fromValue(bytes32 _value) pure internal returns (bytes32 _lowKey, bytes32 _highKey) {
assembly {
_lowKey := and(div(_value, 0x10000000000000000), 0xffffffffffffffff)
_highKey := and(_value, 0xffffffffffffffff)
}
}
function toKey(uint timestamp) pure internal returns (bytes32) {
return bytes32(timestamp);
}
}
contract JouleContractHolder is usingConsts {
using KeysUtils for bytes32;
// event Found(uint timestamp);
uint internal length;
bytes32 head;
mapping (bytes32 => bytes32) objects;
JouleIndex index;
function JouleContractHolder() public {
index = new JouleIndex();
}
function insert(address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) internal {
length ++;
bytes32 id = KeysUtils.toKey(_address, _timestamp, _gasLimit, _gasPrice);
if (head == 0) {
head = id;
index.insert(id);
// Found(0xffffffff);
return;
}
bytes32 previous = index.findFloorKey(_timestamp);
// reject duplicate key on the end
require(previous != id);
// reject duplicate in the middle
require(objects[id] == 0);
uint prevTimestamp = previous.getTimestamp();
// Found(prevTimestamp);
uint headTimestamp = head.getTimestamp();
// add as head, prevTimestamp == 0 or in the past
if (prevTimestamp < headTimestamp) {
objects[id] = head;
head = id;
}
// add after the previous
else {
objects[id] = objects[previous];
objects[previous] = id;
}
index.insert(id);
}
function next() internal returns (KeysUtils.Object memory _next) {
head = objects[head];
length--;
_next = head.toObject();
}
function getCount() public view returns (uint) {
return length;
}
function getTop(uint _count) external view returns (
address[] _addresses,
uint[] _timestamps,
uint[] _gasLimits,
uint[] _gasPrices
) {
uint amount = _count <= length ? _count : length;
_addresses = new address[](amount);
_timestamps = new uint[](amount);
_gasLimits = new uint[](amount);
_gasPrices = new uint[](amount);
bytes32 current = head;
for (uint i = 0; i < amount; i ++) {
KeysUtils.Object memory obj = current.toObject();
_addresses[i] = obj.contractAddress;
_timestamps[i] = obj.timestamp;
_gasLimits[i] = obj.gasLimit;
_gasPrices[i] = obj.gasPriceGwei * GWEI;
current = objects[current];
}
}
function getTop() external view returns (
address contractAddress,
uint timestamp,
uint gasLimit,
uint gasPrice
) {
KeysUtils.Object memory obj = head.toObject();
contractAddress = obj.contractAddress;
timestamp = obj.timestamp;
gasLimit = obj.gasLimit;
gasPrice = obj.gasPriceGwei * GWEI;
}
function getNext(address _contractAddress,
uint _timestamp,
uint _gasLimit,
uint _gasPrice) public view returns (
address contractAddress,
uint timestamp,
uint gasLimit,
uint gasPrice
) {
if (_timestamp == 0) {
return this.getTop();
}
bytes32 prev = KeysUtils.toKey(_contractAddress, _timestamp, _gasLimit, _gasPrice / GWEI);
bytes32 current = objects[prev];
KeysUtils.Object memory obj = current.toObject();
contractAddress = obj.contractAddress;
timestamp = obj.timestamp;
gasLimit = obj.gasLimit;
gasPrice = obj.gasPriceGwei * GWEI;
}
}
contract Joule is JouleAPI, JouleContractHolder {
function register(address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) external payable returns (uint) {
uint price = this.getPrice(_gasLimit, _gasPrice);
require(msg.value >= price);
require(_timestamp > now);
require(_timestamp < 0x100000000);
require(_gasLimit < MAX_GAS);
// from 1 gwei to 0x100000000 gwei
require(_gasPrice > GWEI);
require(_gasPrice < 0x100000000 * GWEI);
insert(_address, _timestamp, _gasLimit, _gasPrice / GWEI);
Registered(_address, _timestamp, _gasLimit, _gasPrice);
if (msg.value > price) {
msg.sender.transfer(msg.value - price);
return msg.value - price;
}
return 0;
}
function getPrice(uint _gasLimit, uint _gasPrice) external view returns (uint) {
require(_gasLimit < 4300000);
require(_gasPrice > GWEI);
require(_gasPrice < 0x100000000 * GWEI);
return getPriceInner(_gasLimit, _gasPrice);
}
function getPriceInner(uint _gasLimit, uint _gasPrice) internal pure returns (uint) {
return (_gasLimit + IDLE_GAS) * _gasPrice;
}
function invoke() public returns (uint) {
return innerInvoke(invokeCallback);
}
function invokeTop() public returns (uint) {
return innerInvokeTop(invokeCallback);
}
function getVersion() external view returns (bytes8) {
return VERSION;
}
function innerInvoke(function (address, uint) internal returns (bool) _callback) internal returns (uint _amount) {
KeysUtils.Object memory current = KeysUtils.toObject(head);
uint amount;
while (current.timestamp != 0 && current.timestamp < now && msg.gas >= current.gasLimit) {
uint gas = msg.gas;
bool status = _callback(current.contractAddress, current.gasLimit);
// current.contractAddress.call.gas(current.gasLimit)(0x919840ad);
gas -= msg.gas;
Invoked(current.contractAddress, status, gas);
amount += getPriceInner(current.gasLimit, current.gasPriceGwei * GWEI);
current = next();
}
if (amount > 0) {
msg.sender.transfer(amount);
}
return amount;
}
function innerInvokeTop(function (address, uint) internal returns (bool) _callback) internal returns (uint _amount) {
KeysUtils.Object memory current = KeysUtils.toObject(head);
uint gas = msg.gas;
bool status = _callback(current.contractAddress, current.gasLimit);
gas -= msg.gas;
Invoked(current.contractAddress, status, gas);
uint amount = getPriceInner(current.gasLimit, current.gasPriceGwei * GWEI);
if (amount > 0) {
msg.sender.transfer(amount);
}
return amount;
}
function invokeCallback(address _contract, uint _gas) internal returns (bool) {
return _contract.call.gas(_gas)(0x919840ad);
}
}
contract JouleBehindProxy is Joule, Ownable, TransferToken {
address public proxy;
function setProxy(address _proxy) public onlyOwner {
proxy = _proxy;
}
modifier onlyProxy() {
require(msg.sender == proxy);
_;
}
function invoke() public onlyProxy returns (uint) {
return super.invoke();
}
function invokeTop() public onlyProxy returns (uint) {
return super.invokeTop();
}
function invokeCallback(address _contract, uint _gas) internal returns (bool) {
return proxy.call.gas(_gas)(0x73027f6d, _contract);
}
}
contract JouleProxy is JouleProxyAPI, JouleAPI, Ownable, TransferToken {
JouleBehindProxy public joule;
function setJoule(JouleBehindProxy _joule) public onlyOwner {
joule = _joule;
}
modifier onlyJoule() {
require(msg.sender == address(joule));
_;
}
function () public payable onlyJoule {
}
function getCount() public view returns (uint) {
return joule.getCount();
}
function register(address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) external payable returns (uint) {
uint change = joule.register.value(msg.value)(_address, _timestamp, _gasLimit, _gasPrice);
if (change > 0) {
msg.sender.transfer(change);
}
return change;
}
function invoke() public returns (uint) {
uint amount = joule.invoke();
if (amount > 0) {
msg.sender.transfer(amount);
}
return amount;
}
function invokeTop() public returns (uint) {
uint amount = joule.invokeTop();
if (amount > 0) {
msg.sender.transfer(amount);
}
return amount;
}
function getPrice(uint _gasLimit, uint _gasPrice) external view returns (uint) {
return joule.getPrice(_gasLimit, _gasPrice);
}
function getTop() external view returns (
address contractAddress,
uint timestamp,
uint gasLimit,
uint gasPrice
) {
(contractAddress, timestamp, gasLimit, gasPrice) = joule.getTop();
}
function getNext(address _contractAddress,
uint _timestamp,
uint _gasLimit,
uint _gasPrice) public view returns (
address contractAddress,
uint timestamp,
uint gasLimit,
uint gasPrice
) {
(contractAddress, timestamp, gasLimit, gasPrice) = joule.getNext(_contractAddress, _timestamp, _gasLimit, _gasPrice);
}
function getTop(uint _count) external view returns (
address[] _addresses,
uint[] _timestamps,
uint[] _gasLimits,
uint[] _gasPrices
) {
uint length = joule.getCount();
uint amount = _count <= length ? _count : length;
_addresses = new address[](amount);
_timestamps = new uint[](amount);
_gasLimits = new uint[](amount);
_gasPrices = new uint[](amount);
address contractAddress;
uint timestamp;
uint gasLimit;
uint gasPrice;
(contractAddress, timestamp, gasLimit, gasPrice) = joule.getTop();
_addresses[0] = contractAddress;
_timestamps[0] = timestamp;
_gasLimits[0] = gasLimit;
_gasPrices[0] = gasPrice;
for (uint i = 1; i < amount; i ++) {
(contractAddress, timestamp, gasLimit, gasPrice) = joule.getNext(contractAddress, timestamp, gasLimit, gasPrice);
_addresses[i] = contractAddress;
_timestamps[i] = timestamp;
_gasLimits[i] = gasLimit;
_gasPrices[i] = gasPrice;
}
}
function getVersion() external view returns (bytes8) {
return joule.getVersion();
}
function callback(address _contract) public onlyJoule {
CheckableContract(_contract).check();
}
}
|
from 1 gwei to 0x100000000 gwei
|
function register(address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) external payable returns (uint) {
uint price = this.getPrice(_gasLimit, _gasPrice);
require(msg.value >= price);
require(_timestamp > now);
require(_timestamp < 0x100000000);
require(_gasLimit < MAX_GAS);
require(_gasPrice > GWEI);
require(_gasPrice < 0x100000000 * GWEI);
insert(_address, _timestamp, _gasLimit, _gasPrice / GWEI);
Registered(_address, _timestamp, _gasLimit, _gasPrice);
if (msg.value > price) {
msg.sender.transfer(msg.value - price);
return msg.value - price;
}
return 0;
}
| 13,003,645
|
./partial_match/1/0x6893491CeCF9309e445fE10f49CEd15CBb08652F/sources/Migration_Schedar.sol
|
SIP-252 calculates the amount of SNX that can be force liquidated (redeemed) for the various cases of transferrable & escrowed collateral The balanceOf here can be considered "transferable" since it's not escrowed, and it is the only SNX that can potentially be transfered if unstaked. transferable is enough if transferable is not enough need only part of the escrow, add the needed part to redeemed
|
function _redeemableCollateralForTarget(
address account,
uint redeemTarget,
uint rewardsSum
) internal view returns (uint totalRedeemed, uint escrowToLiquidate) {
uint transferable = synthetixERC20().balanceOf(account);
if (redeemTarget.add(rewardsSum) <= transferable) {
return (redeemTarget, 0);
escrowToLiquidate = redeemTarget.add(rewardsSum).sub(transferable);
return (redeemTarget, escrowToLiquidate);
}
}
| 4,485,277
|
./partial_match/1/0x3Fdb3bd1ab409F0CBB2c4d919b2205ac881B99ED/sources/src/FraxGovernorAlpha.sol
|
Returns the proposal deadline, which may have been extended beyond that set at proposal creation, if the proposal reached quorum late in the voting period. See {Governor-proposalDeadline}./
|
function proposalDeadline(
uint256 proposalId
) public view override(IGovernor, Governor, GovernorPreventLateQuorum) returns (uint256) {
return GovernorPreventLateQuorum.proposalDeadline(proposalId);
}
| 9,366,503
|
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
pragma abicoder v2;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import {IFactory} from "../factory/IFactory.sol";
import {IInstanceRegistry} from "../factory/InstanceRegistry.sol";
import {IUniversalVault} from "../visor/Visor.sol";
import {IRewardPool} from "./RewardPool.sol";
import {Powered} from "./Powered.sol";
interface IRageQuit {
function rageQuit() external;
}
interface IHypervisor is IRageQuit {
/* admin events */
event HypervisorCreated(address rewardPool, address powerSwitch);
event HypervisorFunded(uint256 amount, uint256 duration);
event BonusTokenRegistered(address token);
event VaultFactoryRegistered(address factory);
event VaultFactoryRemoved(address factory);
/* user events */
event Staked(address vault, uint256 amount);
event Unstaked(address vault, uint256 amount);
event RewardClaimed(address vault, address recipient, address token, uint256 amount);
/* data types */
struct HypervisorData {
address stakingToken;
address rewardToken;
address rewardPool;
RewardScaling rewardScaling;
uint256 rewardSharesOutstanding;
uint256 totalStake;
uint256 totalStakeUnits;
uint256 lastUpdate;
RewardSchedule[] rewardSchedules;
}
struct RewardSchedule {
uint256 duration;
uint256 start;
uint256 shares;
}
struct VaultData {
uint256 totalStake;
StakeData[] stakes;
}
struct StakeData {
uint256 amount;
uint256 timestamp;
}
struct RewardScaling {
uint256 floor;
uint256 ceiling;
uint256 time;
}
struct RewardOutput {
uint256 lastStakeAmount;
uint256 newStakesCount;
uint256 reward;
uint256 newTotalStakeUnits;
}
/* user functions */
function stake(
address vault,
uint256 amount,
bytes calldata permission
) external;
function unstakeAndClaim(
address vault,
uint256 amount,
bytes calldata permission
) external;
/* getter functions */
function getHypervisorData() external view returns (HypervisorData memory hypervisor);
function getBonusTokenSetLength() external view returns (uint256 length);
function getBonusTokenAtIndex(uint256 index) external view returns (address bonusToken);
function getVaultFactorySetLength() external view returns (uint256 length);
function getVaultFactoryAtIndex(uint256 index) external view returns (address factory);
function getVaultData(address vault) external view returns (VaultData memory vaultData);
function isValidAddress(address target) external view returns (bool validity);
function isValidVault(address target) external view returns (bool validity);
function getCurrentUnlockedRewards() external view returns (uint256 unlockedRewards);
function getFutureUnlockedRewards(uint256 timestamp)
external
view
returns (uint256 unlockedRewards);
function getCurrentVaultReward(address vault) external view returns (uint256 reward);
function getCurrentStakeReward(address vault, uint256 stakeAmount)
external
view
returns (uint256 reward);
function getFutureVaultReward(address vault, uint256 timestamp)
external
view
returns (uint256 reward);
function getFutureStakeReward(
address vault,
uint256 stakeAmount,
uint256 timestamp
) external view returns (uint256 reward);
function getCurrentVaultStakeUnits(address vault) external view returns (uint256 stakeUnits);
function getFutureVaultStakeUnits(address vault, uint256 timestamp)
external
view
returns (uint256 stakeUnits);
function getCurrentTotalStakeUnits() external view returns (uint256 totalStakeUnits);
function getFutureTotalStakeUnits(uint256 timestamp)
external
view
returns (uint256 totalStakeUnits);
/* pure functions */
function calculateTotalStakeUnits(StakeData[] memory stakes, uint256 timestamp)
external
pure
returns (uint256 totalStakeUnits);
function calculateStakeUnits(
uint256 amount,
uint256 start,
uint256 end
) external pure returns (uint256 stakeUnits);
function calculateUnlockedRewards(
RewardSchedule[] memory rewardSchedules,
uint256 rewardBalance,
uint256 sharesOutstanding,
uint256 timestamp
) external pure returns (uint256 unlockedRewards);
function calculateRewardFromStakes(
StakeData[] memory stakes,
uint256 unstakeAmount,
uint256 unlockedRewards,
uint256 totalStakeUnits,
uint256 timestamp,
RewardScaling memory rewardScaling
) external pure returns (RewardOutput memory out);
function calculateReward(
uint256 unlockedRewards,
uint256 stakeAmount,
uint256 stakeDuration,
uint256 totalStakeUnits,
RewardScaling memory rewardScaling
) external pure returns (uint256 reward);
}
/// @title Hypervisor
/// @notice Reward distribution contract with time multiplier
/// Access Control
/// - Power controller:
/// Can power off / shutdown the Hypervisor
/// Can withdraw rewards from reward pool once shutdown
/// - Proxy owner:
/// Can change arbitrary logic / state by upgrading the Hypervisor
/// Is unable to operate on user funds due to UniversalVault
/// Is unable to operate on reward pool funds when reward pool is offline / shutdown
/// - Hypervisor admin:
/// Can add funds to the Hypervisor, register bonus tokens, and whitelist new vault factories
/// Is a subset of proxy owner permissions
/// - User:
/// Can deposit / withdraw / ragequit
/// Hypervisor State Machine
/// - Online:
/// Hypervisor is operating normally, all functions are enabled
/// - Offline:
/// Hypervisor is temporarely disabled for maintenance
/// User deposits and withdrawls are disabled, ragequit remains enabled
/// Users can withdraw their stake through rageQuit() but forego their pending reward
/// Should only be used when downtime required for an upgrade
/// - Shutdown:
/// Hypervisor is permanently disabled
/// All functions are disabled with the exception of ragequit
/// Users can withdraw their stake through rageQuit()
/// Power controller can withdraw from the reward pool
/// Should only be used if Proxy Owner role is compromized
contract Hypervisor is IHypervisor, Powered, Ownable {
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
/* constants */
// An upper bound on the number of active stakes per vault is required to prevent
// calls to rageQuit() from reverting.
// With 30 stakes in a vault, ragequit costs 432811 gas which is conservatively lower
// than the hardcoded limit of 500k gas on the vault.
// This limit is configurable and could be increased in a future deployment.
// Ultimately, to avoid a need for fixed upper bounds, the EVM would need to provide
// an error code that allows for reliably catching out-of-gas errors on remote calls.
uint256 public constant MAX_STAKES_PER_VAULT = 30;
uint256 public constant MAX_REWARD_TOKENS = 50;
uint256 public constant BASE_SHARES_PER_WEI = 1000000;
uint256 public stakeLimit = 2500 ether;
/* storage */
HypervisorData private _hypervisor;
mapping(address => VaultData) private _vaults;
EnumerableSet.AddressSet private _bonusTokenSet;
EnumerableSet.AddressSet private _vaultFactorySet;
/* initializer */
/// @notice Initizalize Hypervisor
/// access control: only proxy constructor
/// state machine: can only be called once
/// state scope: set initialization variables
/// token transfer: none
/// @param ownerAddress address The admin address
/// @param rewardPoolFactory address The factory to use for deploying the RewardPool
/// @param powerSwitchFactory address The factory to use for deploying the PowerSwitch
/// @param stakingToken address The address of the staking token for this Hypervisor
/// @param rewardToken address The address of the reward token for this Hypervisor
/// @param rewardScaling RewardScaling The config for reward scaling floor, ceiling, and time
constructor(
address ownerAddress,
address rewardPoolFactory,
address powerSwitchFactory,
address stakingToken,
address rewardToken,
RewardScaling memory rewardScaling,
uint256 _stakeLimit
) {
// the scaling floor must be smaller than ceiling
require(rewardScaling.floor <= rewardScaling.ceiling, "Hypervisor: floor above ceiling");
// setting rewardScalingTime to 0 would cause divide by zero error
// to disable reward scaling, use rewardScalingFloor == rewardScalingCeiling
require(rewardScaling.time != 0, "Hypervisor: scaling time cannot be zero");
// deploy power switch
address powerSwitch = IFactory(powerSwitchFactory).create(abi.encode(ownerAddress));
// deploy reward pool
address rewardPool = IFactory(rewardPoolFactory).create(abi.encode(powerSwitch));
// set internal configs
Ownable.transferOwnership(ownerAddress);
Powered._setPowerSwitch(powerSwitch);
// commit to storage
_hypervisor.stakingToken = stakingToken;
_hypervisor.rewardToken = rewardToken;
_hypervisor.rewardPool = rewardPool;
_hypervisor.rewardScaling = rewardScaling;
stakeLimit = _stakeLimit;
// emit event
emit HypervisorCreated(rewardPool, powerSwitch);
}
/* getter functions */
function getBonusTokenSetLength() external view override returns (uint256 length) {
return _bonusTokenSet.length();
}
function getBonusTokenAtIndex(uint256 index)
external
view
override
returns (address bonusToken)
{
return _bonusTokenSet.at(index);
}
function getVaultFactorySetLength() external view override returns (uint256 length) {
return _vaultFactorySet.length();
}
function getVaultFactoryAtIndex(uint256 index)
external
view
override
returns (address factory)
{
return _vaultFactorySet.at(index);
}
function isValidVault(address target) public view override returns (bool validity) {
// validate target is created from whitelisted vault factory
for (uint256 index = 0; index < _vaultFactorySet.length(); index++) {
if (IInstanceRegistry(_vaultFactorySet.at(index)).isInstance(target)) {
return true;
}
}
// explicit return
return false;
}
function isValidAddress(address target) public view override returns (bool validity) {
// sanity check target for potential input errors
return
target != address(this) &&
target != address(0) &&
target != _hypervisor.stakingToken &&
target != _hypervisor.rewardToken &&
target != _hypervisor.rewardPool &&
!_bonusTokenSet.contains(target);
}
/* Hypervisor getters */
function getHypervisorData() external view override returns (HypervisorData memory hypervisor) {
return _hypervisor;
}
function getCurrentUnlockedRewards() public view override returns (uint256 unlockedRewards) {
// calculate reward available based on state
return getFutureUnlockedRewards(block.timestamp);
}
function getFutureUnlockedRewards(uint256 timestamp)
public
view
override
returns (uint256 unlockedRewards)
{
// get reward amount remaining
uint256 remainingRewards = IERC20(_hypervisor.rewardToken).balanceOf(_hypervisor.rewardPool);
// calculate reward available based on state
unlockedRewards = calculateUnlockedRewards(
_hypervisor.rewardSchedules,
remainingRewards,
_hypervisor.rewardSharesOutstanding,
timestamp
);
// explicit return
return unlockedRewards;
}
function getCurrentTotalStakeUnits() public view override returns (uint256 totalStakeUnits) {
// calculate new stake units
return getFutureTotalStakeUnits(block.timestamp);
}
function getFutureTotalStakeUnits(uint256 timestamp)
public
view
override
returns (uint256 totalStakeUnits)
{
// return early if no change
if (timestamp == _hypervisor.lastUpdate) return _hypervisor.totalStakeUnits;
// calculate new stake units
uint256 newStakeUnits =
calculateStakeUnits(_hypervisor.totalStake, _hypervisor.lastUpdate, timestamp);
// add to cached total
totalStakeUnits = _hypervisor.totalStakeUnits.add(newStakeUnits);
// explicit return
return totalStakeUnits;
}
/* vault getters */
function getVaultData(address vault)
external
view
override
returns (VaultData memory vaultData)
{
return _vaults[vault];
}
function getCurrentVaultReward(address vault) external view override returns (uint256 reward) {
// calculate rewards
return
calculateRewardFromStakes(
_vaults[vault]
.stakes,
_vaults[vault]
.totalStake,
getCurrentUnlockedRewards(),
getCurrentTotalStakeUnits(),
block
.timestamp,
_hypervisor
.rewardScaling
)
.reward;
}
function getFutureVaultReward(address vault, uint256 timestamp)
external
view
override
returns (uint256 reward)
{
// calculate rewards
return
calculateRewardFromStakes(
_vaults[vault]
.stakes,
_vaults[vault]
.totalStake,
getFutureUnlockedRewards(timestamp),
getFutureTotalStakeUnits(timestamp),
timestamp,
_hypervisor
.rewardScaling
)
.reward;
}
function getCurrentStakeReward(address vault, uint256 stakeAmount)
external
view
override
returns (uint256 reward)
{
// calculate rewards
return
calculateRewardFromStakes(
_vaults[vault]
.stakes,
stakeAmount,
getCurrentUnlockedRewards(),
getCurrentTotalStakeUnits(),
block
.timestamp,
_hypervisor
.rewardScaling
)
.reward;
}
function getFutureStakeReward(
address vault,
uint256 stakeAmount,
uint256 timestamp
) external view override returns (uint256 reward) {
// calculate rewards
return
calculateRewardFromStakes(
_vaults[vault]
.stakes,
stakeAmount,
getFutureUnlockedRewards(timestamp),
getFutureTotalStakeUnits(timestamp),
timestamp,
_hypervisor
.rewardScaling
)
.reward;
}
function getCurrentVaultStakeUnits(address vault)
public
view
override
returns (uint256 stakeUnits)
{
// calculate stake units
return getFutureVaultStakeUnits(vault, block.timestamp);
}
function getFutureVaultStakeUnits(address vault, uint256 timestamp)
public
view
override
returns (uint256 stakeUnits)
{
// calculate stake units
return calculateTotalStakeUnits(_vaults[vault].stakes, timestamp);
}
/* pure functions */
function calculateTotalStakeUnits(StakeData[] memory stakes, uint256 timestamp)
public
pure
override
returns (uint256 totalStakeUnits)
{
for (uint256 index; index < stakes.length; index++) {
// reference stake
StakeData memory stakeData = stakes[index];
// calculate stake units
uint256 stakeUnits =
calculateStakeUnits(stakeData.amount, stakeData.timestamp, timestamp);
// add to running total
totalStakeUnits = totalStakeUnits.add(stakeUnits);
}
}
function calculateStakeUnits(
uint256 amount,
uint256 start,
uint256 end
) public pure override returns (uint256 stakeUnits) {
// calculate duration
uint256 duration = end.sub(start);
// calculate stake units
stakeUnits = duration.mul(amount);
// explicit return
return stakeUnits;
}
function calculateUnlockedRewards(
RewardSchedule[] memory rewardSchedules,
uint256 rewardBalance,
uint256 sharesOutstanding,
uint256 timestamp
) public pure override returns (uint256 unlockedRewards) {
// return 0 if no registered schedules
if (rewardSchedules.length == 0) {
return 0;
}
// calculate reward shares locked across all reward schedules
uint256 sharesLocked;
for (uint256 index = 0; index < rewardSchedules.length; index++) {
// fetch reward schedule storage reference
RewardSchedule memory schedule = rewardSchedules[index];
// caculate amount of shares available on this schedule
// if (now - start) < duration
// sharesLocked = shares - (shares * (now - start) / duration)
// else
// sharesLocked = 0
uint256 currentSharesLocked = 0;
if (timestamp.sub(schedule.start) < schedule.duration) {
currentSharesLocked = schedule.shares.sub(
schedule.shares.mul(timestamp.sub(schedule.start)).div(schedule.duration)
);
}
// add to running total
sharesLocked = sharesLocked.add(currentSharesLocked);
}
// convert shares to reward
// rewardLocked = sharesLocked * rewardBalance / sharesOutstanding
uint256 rewardLocked = sharesLocked.mul(rewardBalance).div(sharesOutstanding);
// calculate amount available
// unlockedRewards = rewardBalance - rewardLocked
unlockedRewards = rewardBalance.sub(rewardLocked);
// explicit return
return unlockedRewards;
}
function calculateRewardFromStakes(
StakeData[] memory stakes,
uint256 unstakeAmount,
uint256 unlockedRewards,
uint256 totalStakeUnits,
uint256 timestamp,
RewardScaling memory rewardScaling
) public pure override returns (RewardOutput memory out) {
uint256 stakesToDrop = 0;
while (unstakeAmount > 0) {
// fetch vault stake storage reference
StakeData memory lastStake = stakes[stakes.length.sub(stakesToDrop).sub(1)];
// calculate stake duration
uint256 stakeDuration = timestamp.sub(lastStake.timestamp);
uint256 currentAmount;
if (lastStake.amount > unstakeAmount) {
// set current amount to remaining unstake amount
currentAmount = unstakeAmount;
// amount of last stake is reduced
out.lastStakeAmount = lastStake.amount.sub(unstakeAmount);
} else {
// set current amount to amount of last stake
currentAmount = lastStake.amount;
// add to stakes to drop
stakesToDrop += 1;
}
// update remaining unstakeAmount
unstakeAmount = unstakeAmount.sub(currentAmount);
// calculate reward amount
uint256 currentReward =
calculateReward(
unlockedRewards,
currentAmount,
stakeDuration,
totalStakeUnits,
rewardScaling
);
// update cumulative reward
out.reward = out.reward.add(currentReward);
// update cached unlockedRewards
unlockedRewards = unlockedRewards.sub(currentReward);
// calculate time weighted stake
uint256 stakeUnits = currentAmount.mul(stakeDuration);
// update cached totalStakeUnits
totalStakeUnits = totalStakeUnits.sub(stakeUnits);
}
// explicit return
return
RewardOutput(
out.lastStakeAmount,
stakes.length.sub(stakesToDrop),
out.reward,
totalStakeUnits
);
}
function calculateReward(
uint256 unlockedRewards,
uint256 stakeAmount,
uint256 stakeDuration,
uint256 totalStakeUnits,
RewardScaling memory rewardScaling
) public pure override returns (uint256 reward) {
// calculate time weighted stake
uint256 stakeUnits = stakeAmount.mul(stakeDuration);
// calculate base reward
// baseReward = unlockedRewards * stakeUnits / totalStakeUnits
uint256 baseReward = 0;
if (totalStakeUnits != 0) {
// scale reward according to proportional weight
baseReward = unlockedRewards.mul(stakeUnits).div(totalStakeUnits);
}
// calculate scaled reward
// if no scaling or scaling period completed
// reward = baseReward
// else
// minReward = baseReward * scalingFloor / scalingCeiling
// bonusReward = baseReward
// * (scalingCeiling - scalingFloor) / scalingCeiling
// * duration / scalingTime
// reward = minReward + bonusReward
if (stakeDuration >= rewardScaling.time || rewardScaling.floor == rewardScaling.ceiling) {
// no reward scaling applied
reward = baseReward;
} else {
// calculate minimum reward using scaling floor
uint256 minReward = baseReward.mul(rewardScaling.floor).div(rewardScaling.ceiling);
// calculate bonus reward with vested portion of scaling factor
uint256 bonusReward =
baseReward
.mul(stakeDuration)
.mul(rewardScaling.ceiling.sub(rewardScaling.floor))
.div(rewardScaling.ceiling)
.div(rewardScaling.time);
// add minimum reward and bonus reward
reward = minReward.add(bonusReward);
}
// explicit return
return reward;
}
/* admin functions */
/// @notice Add funds to the Hypervisor
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - only online
/// state scope:
/// - increase _hypervisor.rewardSharesOutstanding
/// - append to _hypervisor.rewardSchedules
/// token transfer: transfer staking tokens from msg.sender to reward pool
/// @param amount uint256 Amount of reward tokens to deposit
/// @param duration uint256 Duration over which to linearly unlock rewards
function fund(uint256 amount, uint256 duration) external onlyOwner onlyOnline {
// validate duration
require(duration != 0, "Hypervisor: invalid duration");
// create new reward shares
// if existing rewards on this Hypervisor
// mint new shares proportional to % change in rewards remaining
// newShares = remainingShares * newReward / remainingRewards
// else
// mint new shares with BASE_SHARES_PER_WEI initial conversion rate
// store as fixed point number with same of decimals as reward token
uint256 newRewardShares;
if (_hypervisor.rewardSharesOutstanding > 0) {
uint256 remainingRewards = IERC20(_hypervisor.rewardToken).balanceOf(_hypervisor.rewardPool);
newRewardShares = _hypervisor.rewardSharesOutstanding.mul(amount).div(remainingRewards);
} else {
newRewardShares = amount.mul(BASE_SHARES_PER_WEI);
}
// add reward shares to total
_hypervisor.rewardSharesOutstanding = _hypervisor.rewardSharesOutstanding.add(newRewardShares);
// store new reward schedule
_hypervisor.rewardSchedules.push(RewardSchedule(duration, block.timestamp, newRewardShares));
// transfer reward tokens to reward pool
TransferHelper.safeTransferFrom(
_hypervisor.rewardToken,
msg.sender,
_hypervisor.rewardPool,
amount
);
// emit event
emit HypervisorFunded(amount, duration);
}
/// @notice Add vault factory to whitelist
/// @dev use this function to enable stakes to vaults coming from the specified
/// factory contract
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - not shutdown
/// state scope:
/// - append to _vaultFactorySet
/// token transfer: none
/// @param factory address The address of the vault factory
function registerVaultFactory(address factory) external onlyOwner notShutdown {
// add factory to set
require(_vaultFactorySet.add(factory), "Hypervisor: vault factory already registered");
// emit event
emit VaultFactoryRegistered(factory);
}
/// @notice Remove vault factory from whitelist
/// @dev use this function to disable new stakes to vaults coming from the specified
/// factory contract.
/// note: vaults with existing stakes from this factory are sill able to unstake
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - not shutdown
/// state scope:
/// - remove from _vaultFactorySet
/// token transfer: none
/// @param factory address The address of the vault factory
function removeVaultFactory(address factory) external onlyOwner notShutdown {
// remove factory from set
require(_vaultFactorySet.remove(factory), "Hypervisor: vault factory not registered");
// emit event
emit VaultFactoryRemoved(factory);
}
/// @notice Register bonus token for distribution
/// @dev use this function to enable distribution of any ERC20 held by the RewardPool contract
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - only online
/// state scope:
/// - append to _bonusTokenSet
/// token transfer: none
/// @param bonusToken address The address of the bonus token
function registerBonusToken(address bonusToken) external onlyOwner onlyOnline {
// verify valid bonus token
_validateAddress(bonusToken);
// verify bonus token count
require(_bonusTokenSet.length() < MAX_REWARD_TOKENS, "Hypervisor: max bonus tokens reached ");
// add token to set
assert(_bonusTokenSet.add(bonusToken));
// emit event
emit BonusTokenRegistered(bonusToken);
}
/// @notice Rescue tokens from RewardPool
/// @dev use this function to rescue tokens from RewardPool contract
/// without distributing to stakers or triggering emergency shutdown
/// access control: only admin
/// state machine:
/// - can be called multiple times
/// - only online
/// state scope: none
/// token transfer: transfer requested token from RewardPool to recipient
/// @param token address The address of the token to rescue
/// @param recipient address The address of the recipient
/// @param amount uint256 The amount of tokens to rescue
function rescueTokensFromRewardPool(
address token,
address recipient,
uint256 amount
) external onlyOwner onlyOnline {
// verify recipient
_validateAddress(recipient);
// check not attempting to unstake reward token
require(token != _hypervisor.rewardToken, "Hypervisor: invalid address");
// check not attempting to wthdraw bonus token
require(!_bonusTokenSet.contains(token), "Hypervisor: invalid address");
// transfer tokens to recipient
IRewardPool(_hypervisor.rewardPool).sendERC20(token, recipient, amount);
}
/* user functions */
/// @notice Stake tokens
/// @dev anyone can stake to any vault if they have valid permission
/// access control: anyone
/// state machine:
/// - can be called multiple times
/// - only online
/// - when vault exists on this Hypervisor
/// state scope:
/// - append to _vaults[vault].stakes
/// - increase _vaults[vault].totalStake
/// - increase _hypervisor.totalStake
/// - increase _hypervisor.totalStakeUnits
/// - increase _hypervisor.lastUpdate
/// token transfer: transfer staking tokens from msg.sender to vault
/// @param vault address The address of the vault to stake from
/// @param amount uint256 The amount of staking tokens to stake
function stake(
address vault,
uint256 amount,
bytes calldata permission
) external override onlyOnline {
// verify vault is valid
require(isValidVault(vault), "Hypervisor: vault is not registered");
// verify non-zero amount
require(amount != 0, "Hypervisor: no amount staked");
// fetch vault storage reference
VaultData storage vaultData = _vaults[vault];
// verify stakes boundary not reached
require(
vaultData.stakes.length < MAX_STAKES_PER_VAULT,
"Hypervisor: MAX_STAKES_PER_VAULT reached"
);
// update cached sum of stake units across all vaults
_updateTotalStakeUnits();
// store amount and timestamp
vaultData.stakes.push(StakeData(amount, block.timestamp));
// update cached total vault and Hypervisor amounts
vaultData.totalStake = vaultData.totalStake.add(amount);
// verify stake quantity without bounds
require(
stakeLimit == 0 || vaultData.totalStake <= stakeLimit,
"Hypervisor: Stake limit exceeded"
);
_hypervisor.totalStake = _hypervisor.totalStake.add(amount);
// call lock on vault
IUniversalVault(vault).lock(_hypervisor.stakingToken, amount, permission);
// emit event
emit Staked(vault, amount);
}
/// @notice Unstake staking tokens and claim reward
/// @dev rewards can only be claimed when unstaking
/// access control: only owner of vault
/// state machine:
/// - when vault exists on this Hypervisor
/// - after stake from vault
/// - can be called multiple times while sufficient stake remains
/// - only online
/// state scope:
/// - decrease _hypervisor.rewardSharesOutstanding
/// - decrease _hypervisor.totalStake
/// - increase _hypervisor.lastUpdate
/// - modify _hypervisor.totalStakeUnits
/// - modify _vaults[vault].stakes
/// - decrease _vaults[vault].totalStake
/// token transfer:
/// - transfer reward tokens from reward pool to recipient
/// - transfer bonus tokens from reward pool to recipient
/// @param vault address The vault to unstake from
/// @param amount uint256 The amount of staking tokens to unstake
function unstakeAndClaim(
address vault,
uint256 amount,
bytes calldata permission
) external override onlyOnline {
// fetch vault storage reference
VaultData storage vaultData = _vaults[vault];
// verify non-zero amount
require(amount != 0, "Hypervisor: no amount unstaked");
address recipient = IUniversalVault(vault).owner();
// validate recipient
_validateAddress(recipient);
// check for sufficient vault stake amount
require(vaultData.totalStake >= amount, "Hypervisor: insufficient vault stake");
// check for sufficient Hypervisor stake amount
// if this check fails, there is a bug in stake accounting
assert(_hypervisor.totalStake >= amount);
// update cached sum of stake units across all vaults
_updateTotalStakeUnits();
// get reward amount remaining
uint256 remainingRewards = IERC20(_hypervisor.rewardToken).balanceOf(_hypervisor.rewardPool);
// calculate vested portion of reward pool
uint256 unlockedRewards =
calculateUnlockedRewards(
_hypervisor.rewardSchedules,
remainingRewards,
_hypervisor.rewardSharesOutstanding,
block.timestamp
);
// calculate vault time weighted reward with scaling
RewardOutput memory out =
calculateRewardFromStakes(
vaultData.stakes,
amount,
unlockedRewards,
_hypervisor.totalStakeUnits,
block.timestamp,
_hypervisor.rewardScaling
);
// update stake data in storage
if (out.newStakesCount == 0) {
// all stakes have been unstaked
delete vaultData.stakes;
} else {
// some stakes have been completely or partially unstaked
// delete fully unstaked stakes
while (vaultData.stakes.length > out.newStakesCount) vaultData.stakes.pop();
// update partially unstaked stake
vaultData.stakes[out.newStakesCount.sub(1)].amount = out.lastStakeAmount;
}
// update cached stake totals
vaultData.totalStake = vaultData.totalStake.sub(amount);
_hypervisor.totalStake = _hypervisor.totalStake.sub(amount);
_hypervisor.totalStakeUnits = out.newTotalStakeUnits;
// unlock staking tokens from vault
IUniversalVault(vault).unlock(_hypervisor.stakingToken, amount, permission);
// emit event
emit Unstaked(vault, amount);
// only perform on non-zero reward
if (out.reward > 0) {
// calculate shares to burn
// sharesToBurn = sharesOutstanding * reward / remainingRewards
uint256 sharesToBurn =
_hypervisor.rewardSharesOutstanding.mul(out.reward).div(remainingRewards);
// burn claimed shares
_hypervisor.rewardSharesOutstanding = _hypervisor.rewardSharesOutstanding.sub(sharesToBurn);
// transfer bonus tokens from reward pool to recipient
if (_bonusTokenSet.length() > 0) {
for (uint256 index = 0; index < _bonusTokenSet.length(); index++) {
// fetch bonus token address reference
address bonusToken = _bonusTokenSet.at(index);
// calculate bonus token amount
// bonusAmount = bonusRemaining * reward / remainingRewards
uint256 bonusAmount =
IERC20(bonusToken).balanceOf(_hypervisor.rewardPool).mul(out.reward).div(
remainingRewards
);
// transfer bonus token
IRewardPool(_hypervisor.rewardPool).sendERC20(bonusToken, recipient, bonusAmount);
// emit event
emit RewardClaimed(vault, recipient, bonusToken, bonusAmount);
}
}
// transfer reward tokens from reward pool to recipient
IRewardPool(_hypervisor.rewardPool).sendERC20(_hypervisor.rewardToken, recipient, out.reward);
// emit event
emit RewardClaimed(vault, recipient, _hypervisor.rewardToken, out.reward);
}
}
/// @notice Exit Hypervisor without claiming reward
/// @dev This function should never revert when correctly called by the vault.
/// A max number of stakes per vault is set with MAX_STAKES_PER_VAULT to
/// place an upper bound on the for loop in calculateTotalStakeUnits().
/// access control: only callable by the vault directly
/// state machine:
/// - when vault exists on this Hypervisor
/// - when active stake from this vault
/// - any power state
/// state scope:
/// - decrease _hypervisor.totalStake
/// - increase _hypervisor.lastUpdate
/// - modify _hypervisor.totalStakeUnits
/// - delete _vaults[vault]
/// token transfer: none
function rageQuit() external override {
// fetch vault storage reference
VaultData storage _vaultData = _vaults[msg.sender];
// revert if no active stakes
require(_vaultData.stakes.length != 0, "Hypervisor: no stake");
// update cached sum of stake units across all vaults
_updateTotalStakeUnits();
// emit event
emit Unstaked(msg.sender, _vaultData.totalStake);
// update cached totals
_hypervisor.totalStake = _hypervisor.totalStake.sub(_vaultData.totalStake);
_hypervisor.totalStakeUnits = _hypervisor.totalStakeUnits.sub(
calculateTotalStakeUnits(_vaultData.stakes, block.timestamp)
);
// delete stake data
delete _vaults[msg.sender];
}
/* convenience functions */
function _updateTotalStakeUnits() private {
// update cached totalStakeUnits
_hypervisor.totalStakeUnits = getCurrentTotalStakeUnits();
// update cached lastUpdate
_hypervisor.lastUpdate = block.timestamp;
}
function _validateAddress(address target) private view {
// sanity check target for potential input errors
require(isValidAddress(target), "Hypervisor: invalid address");
}
function _truncateStakesArray(StakeData[] memory array, uint256 newLength)
private
pure
returns (StakeData[] memory newArray)
{
newArray = new StakeData[](newLength);
for (uint256 index = 0; index < newLength; index++) {
newArray[index] = array[index];
}
return newArray;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, 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;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
interface IFactory {
function create(bytes calldata args) external returns (address instance);
function create2(bytes calldata args, bytes32 salt) external returns (address instance);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol";
interface IInstanceRegistry {
/* events */
event InstanceAdded(address instance);
event InstanceRemoved(address instance);
/* view functions */
function isInstance(address instance) external view returns (bool validity);
function instanceCount() external view returns (uint256 count);
function instanceAt(uint256 index) external view returns (address instance);
}
/// @title InstanceRegistry
contract InstanceRegistry is IInstanceRegistry {
using EnumerableSet for EnumerableSet.AddressSet;
/* storage */
EnumerableSet.AddressSet private _instanceSet;
/* view functions */
function isInstance(address instance) external view override returns (bool validity) {
return _instanceSet.contains(instance);
}
function instanceCount() external view override returns (uint256 count) {
return _instanceSet.length();
}
function instanceAt(uint256 index) external view override returns (address instance) {
return _instanceSet.at(index);
}
/* admin functions */
function _register(address instance) internal {
require(_instanceSet.add(instance), "InstanceRegistry: already registered");
emit InstanceAdded(instance);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
pragma abicoder v2;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/Initializable.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/EnumerableSet.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import {EIP712} from "./EIP712.sol";
import {ERC1271} from "./ERC1271.sol";
import {OwnableERC721} from "./OwnableERC721.sol";
import {IRageQuit} from "../hypervisor/Hypervisor.sol";
interface IUniversalVault {
/* user events */
event Locked(address delegate, address token, uint256 amount);
event Unlocked(address delegate, address token, uint256 amount);
event RageQuit(address delegate, address token, bool notified, string reason);
/* data types */
struct LockData {
address delegate;
address token;
uint256 balance;
}
/* initialize function */
function initialize() external;
/* user functions */
function lock(
address token,
uint256 amount,
bytes calldata permission
) external;
function unlock(
address token,
uint256 amount,
bytes calldata permission
) external;
function rageQuit(address delegate, address token)
external
returns (bool notified, string memory error);
function transferERC20(
address token,
address to,
uint256 amount
) external;
function transferETH(address to, uint256 amount) external payable;
/* pure functions */
function calculateLockID(address delegate, address token)
external
pure
returns (bytes32 lockID);
/* getter functions */
function getPermissionHash(
bytes32 eip712TypeHash,
address delegate,
address token,
uint256 amount,
uint256 nonce
) external view returns (bytes32 permissionHash);
function getNonce() external view returns (uint256 nonce);
function owner() external view returns (address ownerAddress);
function getLockSetCount() external view returns (uint256 count);
function getLockAt(uint256 index) external view returns (LockData memory lockData);
function getBalanceDelegated(address token, address delegate)
external
view
returns (uint256 balance);
function getBalanceLocked(address token) external view returns (uint256 balance);
function checkBalances() external view returns (bool validity);
}
/// @title Visor
/// @notice Vault for isolated storage of staking tokens
/// @dev Warning: not compatible with rebasing tokens
contract Visor is
IUniversalVault,
EIP712("UniversalVault", "1.0.0"),
ERC1271,
OwnableERC721,
Initializable
{
using SafeMath for uint256;
using Address for address;
using Address for address payable;
using EnumerableSet for EnumerableSet.Bytes32Set;
/* constant */
// Hardcoding a gas limit for rageQuit() is required to prevent gas DOS attacks
// the gas requirement cannot be determined at runtime by querying the delegate
// as it could potentially be manipulated by a malicious delegate who could force
// the calls to revert.
// The gas limit could alternatively be set upon vault initialization or creation
// of a lock, but the gas consumption trade-offs are not favorable.
// Ultimately, to avoid a need for fixed gas limits, the EVM would need to provide
// an error code that allows for reliably catching out-of-gas errors on remote calls.
uint256 public constant RAGEQUIT_GAS = 500000;
bytes32 public constant LOCK_TYPEHASH =
keccak256("Lock(address delegate,address token,uint256 amount,uint256 nonce)");
bytes32 public constant UNLOCK_TYPEHASH =
keccak256("Unlock(address delegate,address token,uint256 amount,uint256 nonce)");
string public constant VERSION = "VISOR-1.0.0";
/* storage */
uint256 private _nonce;
mapping(bytes32 => LockData) private _locks;
EnumerableSet.Bytes32Set private _lockSet;
/* initialization function */
function initializeLock() external initializer {}
function initialize() external override initializer {
OwnableERC721._setNFT(msg.sender);
}
/* ether receive */
receive() external payable {}
/* internal overrides */
function _getOwner() internal view override(ERC1271) returns (address ownerAddress) {
return OwnableERC721.owner();
}
/* pure functions */
function calculateLockID(address delegate, address token)
public
pure
override
returns (bytes32 lockID)
{
return keccak256(abi.encodePacked(delegate, token));
}
/* getter functions */
function getPermissionHash(
bytes32 eip712TypeHash,
address delegate,
address token,
uint256 amount,
uint256 nonce
) public view override returns (bytes32 permissionHash) {
return
EIP712._hashTypedDataV4(
keccak256(abi.encode(eip712TypeHash, delegate, token, amount, nonce))
);
}
function getNonce() external view override returns (uint256 nonce) {
return _nonce;
}
function owner()
public
view
override(IUniversalVault, OwnableERC721)
returns (address ownerAddress)
{
return OwnableERC721.owner();
}
function getLockSetCount() external view override returns (uint256 count) {
return _lockSet.length();
}
function getLockAt(uint256 index) external view override returns (LockData memory lockData) {
return _locks[_lockSet.at(index)];
}
function getBalanceDelegated(address token, address delegate)
external
view
override
returns (uint256 balance)
{
return _locks[calculateLockID(delegate, token)].balance;
}
function getBalanceLocked(address token) public view override returns (uint256 balance) {
uint256 count = _lockSet.length();
for (uint256 index; index < count; index++) {
LockData storage _lockData = _locks[_lockSet.at(index)];
if (_lockData.token == token && _lockData.balance > balance)
balance = _lockData.balance;
}
return balance;
}
function checkBalances() external view override returns (bool validity) {
// iterate over all token locks and validate sufficient balance
uint256 count = _lockSet.length();
for (uint256 index; index < count; index++) {
// fetch storage lock reference
LockData storage _lockData = _locks[_lockSet.at(index)];
// if insufficient balance and no∏t shutdown, return false
if (IERC20(_lockData.token).balanceOf(address(this)) < _lockData.balance) return false;
}
// if sufficient balance or shutdown, return true
return true;
}
/* user functions */
/// @notice Lock ERC20 tokens in the vault
/// access control: called by delegate with signed permission from owner
/// state machine: anytime
/// state scope:
/// - insert or update _locks
/// - increase _nonce
/// token transfer: none
/// @param token Address of token being locked
/// @param amount Amount of tokens being locked
/// @param permission Permission signature payload
function lock(
address token,
uint256 amount,
bytes calldata permission
)
external
override
onlyValidSignature(
getPermissionHash(LOCK_TYPEHASH, msg.sender, token, amount, _nonce),
permission
)
{
// get lock id
bytes32 lockID = calculateLockID(msg.sender, token);
// add lock to storage
if (_lockSet.contains(lockID)) {
// if lock already exists, increase amount
_locks[lockID].balance = _locks[lockID].balance.add(amount);
} else {
// if does not exist, create new lock
// add lock to set
assert(_lockSet.add(lockID));
// add lock data to storage
_locks[lockID] = LockData(msg.sender, token, amount);
}
// validate sufficient balance
require(
IERC20(token).balanceOf(address(this)) >= _locks[lockID].balance,
"UniversalVault: insufficient balance"
);
// increase nonce
_nonce += 1;
// emit event
emit Locked(msg.sender, token, amount);
}
/// @notice Unlock ERC20 tokens in the vault
/// access control: called by delegate with signed permission from owner
/// state machine: after valid lock from delegate
/// state scope:
/// - remove or update _locks
/// - increase _nonce
/// token transfer: none
/// @param token Address of token being unlocked
/// @param amount Amount of tokens being unlocked
/// @param permission Permission signature payload
function unlock(
address token,
uint256 amount,
bytes calldata permission
)
external
override
onlyValidSignature(
getPermissionHash(UNLOCK_TYPEHASH, msg.sender, token, amount, _nonce),
permission
)
{
// get lock id
bytes32 lockID = calculateLockID(msg.sender, token);
// validate existing lock
require(_lockSet.contains(lockID), "UniversalVault: missing lock");
// update lock data
if (_locks[lockID].balance > amount) {
// substract amount from lock balance
_locks[lockID].balance = _locks[lockID].balance.sub(amount);
} else {
// delete lock data
delete _locks[lockID];
assert(_lockSet.remove(lockID));
}
// increase nonce
_nonce += 1;
// emit event
emit Unlocked(msg.sender, token, amount);
}
/// @notice Forcibly cancel delegate lock
/// @dev This function will attempt to notify the delegate of the rage quit using
/// a fixed amount of gas.
/// access control: only owner
/// state machine: after valid lock from delegate
/// state scope:
/// - remove item from _locks
/// token transfer: none
/// @param delegate Address of delegate
/// @param token Address of token being unlocked
function rageQuit(address delegate, address token)
external
override
onlyOwner
returns (bool notified, string memory error)
{
// get lock id
bytes32 lockID = calculateLockID(delegate, token);
// validate existing lock
require(_lockSet.contains(lockID), "UniversalVault: missing lock");
// attempt to notify delegate
if (delegate.isContract()) {
// check for sufficient gas
require(gasleft() >= RAGEQUIT_GAS, "UniversalVault: insufficient gas");
// attempt rageQuit notification
try IRageQuit(delegate).rageQuit{gas: RAGEQUIT_GAS}() {
notified = true;
} catch Error(string memory res) {
notified = false;
error = res;
} catch (bytes memory) {
notified = false;
}
}
// update lock storage
assert(_lockSet.remove(lockID));
delete _locks[lockID];
// emit event
emit RageQuit(delegate, token, notified, error);
}
/// @notice Transfer ERC20 tokens out of vault
/// access control: only owner
/// state machine: when balance >= max(lock) + amount
/// state scope: none
/// token transfer: transfer any token
/// @param token Address of token being transferred
/// @param to Address of the recipient
/// @param amount Amount of tokens to transfer
function transferERC20(
address token,
address to,
uint256 amount
) external override onlyOwner {
// check for sufficient balance
require(
IERC20(token).balanceOf(address(this)) >= getBalanceLocked(token).add(amount),
"UniversalVault: insufficient balance"
);
// perform transfer
TransferHelper.safeTransfer(token, to, amount);
}
/// @notice Transfer ERC20 tokens out of vault
/// access control: only owner
/// state machine: when balance >= amount
/// state scope: none
/// token transfer: transfer any token
/// @param to Address of the recipient
/// @param amount Amount of ETH to transfer
function transferETH(address to, uint256 amount) external payable override onlyOwner {
// perform transfer
TransferHelper.safeTransferETH(to, amount);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {TransferHelper} from "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import {Powered} from "./Powered.sol";
interface IRewardPool {
function sendERC20(
address token,
address to,
uint256 value
) external;
function rescueERC20(address[] calldata tokens, address recipient) external;
}
/// @title Reward Pool
/// @notice Vault for isolated storage of reward tokens
contract RewardPool is IRewardPool, Powered, Ownable {
/* initializer */
constructor(address powerSwitch) {
Powered._setPowerSwitch(powerSwitch);
}
/* user functions */
/// @notice Send an ERC20 token
/// access control: only owner
/// state machine:
/// - can be called multiple times
/// - only online
/// state scope: none
/// token transfer: transfer tokens from self to recipient
/// @param token address The token to send
/// @param to address The recipient to send to
/// @param value uint256 Amount of tokens to send
function sendERC20(
address token,
address to,
uint256 value
) external override onlyOwner onlyOnline {
TransferHelper.safeTransfer(token, to, value);
}
/* emergency functions */
/// @notice Rescue multiple ERC20 tokens
/// access control: only power controller
/// state machine:
/// - can be called multiple times
/// - only shutdown
/// state scope: none
/// token transfer: transfer tokens from self to recipient
/// @param tokens address[] The tokens to rescue
/// @param recipient address The recipient to rescue to
function rescueERC20(address[] calldata tokens, address recipient)
external
override
onlyShutdown
{
// only callable by controller
require(
msg.sender == Powered.getPowerController(),
"RewardPool: only controller can withdraw after shutdown"
);
// assert recipient is defined
require(recipient != address(0), "RewardPool: recipient not defined");
// transfer tokens
for (uint256 index = 0; index < tokens.length; index++) {
// get token
address token = tokens[index];
// get balance
uint256 balance = IERC20(token).balanceOf(address(this));
// transfer token
TransferHelper.safeTransfer(token, recipient, balance);
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {IPowerSwitch} from "./PowerSwitch.sol";
interface IPowered {
function isOnline() external view returns (bool status);
function isOffline() external view returns (bool status);
function isShutdown() external view returns (bool status);
function getPowerSwitch() external view returns (address powerSwitch);
function getPowerController() external view returns (address controller);
}
/// @title Powered
/// @notice Helper for calling external PowerSwitch
contract Powered is IPowered {
/* storage */
address private _powerSwitch;
/* modifiers */
modifier onlyOnline() {
_onlyOnline();
_;
}
modifier onlyOffline() {
_onlyOffline();
_;
}
modifier notShutdown() {
_notShutdown();
_;
}
modifier onlyShutdown() {
_onlyShutdown();
_;
}
/* initializer */
function _setPowerSwitch(address powerSwitch) internal {
_powerSwitch = powerSwitch;
}
/* getter functions */
function isOnline() public view override returns (bool status) {
return IPowerSwitch(_powerSwitch).isOnline();
}
function isOffline() public view override returns (bool status) {
return IPowerSwitch(_powerSwitch).isOffline();
}
function isShutdown() public view override returns (bool status) {
return IPowerSwitch(_powerSwitch).isShutdown();
}
function getPowerSwitch() public view override returns (address powerSwitch) {
return _powerSwitch;
}
function getPowerController() public view override returns (address controller) {
return IPowerSwitch(_powerSwitch).getPowerController();
}
/* convenience functions */
function _onlyOnline() private view {
require(isOnline(), "Powered: is not online");
}
function _onlyOffline() private view {
require(isOffline(), "Powered: is not offline");
}
function _notShutdown() private view {
require(!isShutdown(), "Powered: is shutdown");
}
function _onlyShutdown() private view {
require(isShutdown(), "Powered: is not shutdown");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/Address.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !Address.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
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);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/* solhint-disable max-line-length */
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private constant _TYPE_HASH =
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_HASHED_NAME = keccak256(bytes(name));
_HASHED_VERSION = keccak256(bytes(version));
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 name,
bytes32 version
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, name, version, _getChainId(), address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712NameHash() internal view virtual returns (bytes32) {
return _HASHED_NAME;
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712VersionHash() internal view virtual returns (bytes32) {
return _HASHED_VERSION;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
interface IERC1271 {
function isValidSignature(bytes32 _messageHash, bytes memory _signature)
external
view
returns (bytes4 magicValue);
}
library SignatureChecker {
function isValidSignature(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
if (Address.isContract(signer)) {
bytes4 selector = IERC1271.isValidSignature.selector;
(bool success, bytes memory returndata) =
signer.staticcall(abi.encodeWithSelector(selector, hash, signature));
return success && abi.decode(returndata, (bytes4)) == selector;
} else {
return ECDSA.recover(hash, signature) == signer;
}
}
}
/// @title ERC1271
/// @notice Module for ERC1271 compatibility
abstract contract ERC1271 is IERC1271 {
// Valid magic value bytes4(keccak256("isValidSignature(bytes32,bytes)")
bytes4 internal constant VALID_SIG = IERC1271.isValidSignature.selector;
// Invalid magic value
bytes4 internal constant INVALID_SIG = bytes4(0);
modifier onlyValidSignature(bytes32 permissionHash, bytes memory signature) {
require(
isValidSignature(permissionHash, signature) == VALID_SIG,
"ERC1271: Invalid signature"
);
_;
}
function _getOwner() internal view virtual returns (address owner);
function isValidSignature(bytes32 permissionHash, bytes memory signature)
public
view
override
returns (bytes4)
{
return
SignatureChecker.isValidSignature(_getOwner(), permissionHash, signature)
? VALID_SIG
: INVALID_SIG;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
/// @title OwnableERC721
/// @notice Use ERC721 ownership for access control
contract OwnableERC721 {
address private _nftAddress;
modifier onlyOwner() {
require(owner() == msg.sender, "OwnableERC721: caller is not the owner");
_;
}
function _setNFT(address nftAddress) internal {
_nftAddress = nftAddress;
}
function nft() public view virtual returns (address nftAddress) {
return _nftAddress;
}
function owner() public view virtual returns (address ownerAddress) {
return IERC721(_nftAddress).ownerOf(uint256(address(this)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity 0.7.6;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
interface IPowerSwitch {
/* admin events */
event PowerOn();
event PowerOff();
event EmergencyShutdown();
/* data types */
enum State {Online, Offline, Shutdown}
/* admin functions */
function powerOn() external;
function powerOff() external;
function emergencyShutdown() external;
/* view functions */
function isOnline() external view returns (bool status);
function isOffline() external view returns (bool status);
function isShutdown() external view returns (bool status);
function getStatus() external view returns (State status);
function getPowerController() external view returns (address controller);
}
/// @title PowerSwitch
/// @notice Standalone pausing and emergency stop functionality
contract PowerSwitch is IPowerSwitch, Ownable {
/* storage */
IPowerSwitch.State private _status;
/* initializer */
constructor(address owner) {
// sanity check owner
require(owner != address(0), "PowerSwitch: invalid owner");
// transfer ownership
Ownable.transferOwnership(owner);
}
/* admin functions */
/// @notice Turn Power On
/// access control: only admin
/// state machine: only when offline
/// state scope: only modify _status
/// token transfer: none
function powerOn() external override onlyOwner {
require(_status == IPowerSwitch.State.Offline, "PowerSwitch: cannot power on");
_status = IPowerSwitch.State.Online;
emit PowerOn();
}
/// @notice Turn Power Off
/// access control: only admin
/// state machine: only when online
/// state scope: only modify _status
/// token transfer: none
function powerOff() external override onlyOwner {
require(_status == IPowerSwitch.State.Online, "PowerSwitch: cannot power off");
_status = IPowerSwitch.State.Offline;
emit PowerOff();
}
/// @notice Shutdown Permanently
/// access control: only admin
/// state machine:
/// - when online or offline
/// - can only be called once
/// state scope: only modify _status
/// token transfer: none
function emergencyShutdown() external override onlyOwner {
require(_status != IPowerSwitch.State.Shutdown, "PowerSwitch: cannot shutdown");
_status = IPowerSwitch.State.Shutdown;
emit EmergencyShutdown();
}
/* getter functions */
function isOnline() external view override returns (bool status) {
return _status == State.Online;
}
function isOffline() external view override returns (bool status) {
return _status == State.Offline;
}
function isShutdown() external view override returns (bool status) {
return _status == State.Shutdown;
}
function getStatus() external view override returns (IPowerSwitch.State status) {
return _status;
}
function getPowerController() external view override returns (address controller) {
return Ownable.owner();
}
}
|
Unstake staking tokens and claim reward rewards can only be claimed when unstaking access control: only owner of vault state machine: - when vault exists on this Hypervisor - after stake from vault - can be called multiple times while sufficient stake remains - only online state scope: - decrease _hypervisor.rewardSharesOutstanding - decrease _hypervisor.totalStake - increase _hypervisor.lastUpdate - modify _hypervisor.totalStakeUnits - modify _vaults[vault].stakes - decrease _vaults[vault].totalStake token transfer: - transfer reward tokens from reward pool to recipient - transfer bonus tokens from reward pool to recipient vault address The vault to unstake from amount uint256 The amount of staking tokens to unstake fetch vault storage reference verify non-zero amount validate recipient check for sufficient vault stake amount check for sufficient Hypervisor stake amount if this check fails, there is a bug in stake accounting update cached sum of stake units across all vaults get reward amount remaining calculate vested portion of reward pool calculate vault time weighted reward with scaling update stake data in storage all stakes have been unstaked some stakes have been completely or partially unstaked delete fully unstaked stakes update partially unstaked stake only perform on non-zero reward calculate shares to burn sharesToBurn = sharesOutstanding reward / remainingRewards burn claimed shares transfer bonus tokens from reward pool to recipient fetch bonus token address reference calculate bonus token amount bonusAmount = bonusRemaining reward / remainingRewards transfer bonus token emit event
|
function unstakeAndClaim(
address vault,
uint256 amount,
bytes calldata permission
) external override onlyOnline {
VaultData storage vaultData = _vaults[vault];
require(amount != 0, "Hypervisor: no amount unstaked");
address recipient = IUniversalVault(vault).owner();
_validateAddress(recipient);
require(vaultData.totalStake >= amount, "Hypervisor: insufficient vault stake");
assert(_hypervisor.totalStake >= amount);
_updateTotalStakeUnits();
uint256 remainingRewards = IERC20(_hypervisor.rewardToken).balanceOf(_hypervisor.rewardPool);
uint256 unlockedRewards =
calculateUnlockedRewards(
_hypervisor.rewardSchedules,
remainingRewards,
_hypervisor.rewardSharesOutstanding,
block.timestamp
);
RewardOutput memory out =
calculateRewardFromStakes(
vaultData.stakes,
amount,
unlockedRewards,
_hypervisor.totalStakeUnits,
block.timestamp,
_hypervisor.rewardScaling
);
if (out.newStakesCount == 0) {
delete vaultData.stakes;
while (vaultData.stakes.length > out.newStakesCount) vaultData.stakes.pop();
vaultData.stakes[out.newStakesCount.sub(1)].amount = out.lastStakeAmount;
}
_hypervisor.totalStake = _hypervisor.totalStake.sub(amount);
_hypervisor.totalStakeUnits = out.newTotalStakeUnits;
if (out.reward > 0) {
uint256 sharesToBurn =
_hypervisor.rewardSharesOutstanding.mul(out.reward).div(remainingRewards);
_hypervisor.rewardSharesOutstanding = _hypervisor.rewardSharesOutstanding.sub(sharesToBurn);
if (_bonusTokenSet.length() > 0) {
for (uint256 index = 0; index < _bonusTokenSet.length(); index++) {
address bonusToken = _bonusTokenSet.at(index);
uint256 bonusAmount =
IERC20(bonusToken).balanceOf(_hypervisor.rewardPool).mul(out.reward).div(
remainingRewards
);
IRewardPool(_hypervisor.rewardPool).sendERC20(bonusToken, recipient, bonusAmount);
emit RewardClaimed(vault, recipient, bonusToken, bonusAmount);
}
}
}
}
| 1,141,513
|
pragma solidity 0.5.8;
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/lifecycle/Pausable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/*
ERC 20 Transfer interface
*/
contract ERC20 {
function transfer(address to, uint tokens) public returns (bool success);
}
/*
Generic Receiver Contract
*/
contract Receiver is Ownable,Pausable {
/*
@notice Send funds owned by this contract to another address
@param tracker - ERC20 token tracker ( DAI / MKR / etc. )
@param amount - Amount of tokens to send
@param receiver - Address we're sending these tokens to
@return true if transfer succeeded, false otherwise
*/
using SafeMath for uint256;
function sendFundsTo( address tracker, uint256 amount, address receiver) public onlyOwner returns ( bool ) {
// callable only by the owner, not using modifiers to improve readability
// Transfer tokens from this address to the receiver
return ERC20(tracker).transfer(receiver, amount);
}
}
/*
Factory Contract
*/
contract Factory is Ownable, Pausable {
using SafeMath for uint256;
using SafeMath for uint8;
mapping ( uint256 => address ) public receiversMap;
uint256 public receiverCount = 0;
/*
@notice Create a number of receiver contracts
@param number - 0-255
*/
function createReceivers( uint8 number ) public onlyOwner{
// would reach the gaslimit at 41 or so
require(number <= 38);
for(uint8 i = 0; i < number; i++) {
// Create and index our new receiver
receiversMap[++receiverCount] = address(new Receiver());
}
// add event here if you need it
}
/*
@notice Send funds in a receiver to another address
@param ID - Receiver indexed ID
@param tracker - ERC20 token tracker ( DAI / MKR / etc. )
@param amount - Amount of tokens to send
@param receiver - Address we're sending tokens to
@return true if transfer succeeded, false otherwise
*/
function sendFundsFromReceiverTo( uint256 ID, address tracker, uint256 amount, address receiver ) public onlyOwner returns (bool) {
return Receiver( receiversMap[ID] ).sendFundsTo( tracker, amount, receiver);
}
/*
Batch Collection - Should support a few hundred transansfers
@param tracker - ERC20 token tracker ( DAI / MKR / etc. )
@param receiver - Address we're sending tokens to
@param contractAddresses - we send an array of addresses instead of ids, so we don't need to read them ( lower gas cost )
@param amounts - array of amounts
*/
function batchCollect( address tracker, address receiver, uint256[] memory amounts, address[] memory contractAddresses) public onlyOwner{
require(contractAddresses.length == amounts.length);
for(uint256 i = 0; i < contractAddresses.length; i++) {
// add exception handling
require(Receiver( contractAddresses[i] ).sendFundsTo( tracker, amounts[i], receiver), "batchCollect's call to sendFundsTo failed");
}
}
}
// tests to check:
// batchcollect check for different lengths on amounts and contractAddress, addressed with the require
// check if the batchcollect function works after the require is added
// check for floating compiler
// transfer owner with openZeppelin
// what happens when you run createReceivers(0)
// change ownership
// check for createReceivers to be less than 40
|
/ would reach the gaslimit at 41 or so Create and index our new receiver
|
function createReceivers( uint8 number ) public onlyOwner{
require(number <= 38);
for(uint8 i = 0; i < number; i++) {
receiversMap[++receiverCount] = address(new Receiver());
}
@param ID - Receiver indexed ID
@param tracker - ERC20 token tracker ( DAI / MKR / etc. )
@param amount - Amount of tokens to send
@param receiver - Address we're sending tokens to
@return true if transfer succeeded, false otherwise
| 12,762,650
|
//Address: 0x6846b938f9be9f1eeeb9bfd853636c805f8f54d3
//Contract name: SwarmRedistribution
//Balance: 0 Ether
//Verification Date: 1/1/2017
//Transacion Count: 4
// CODE STARTS HERE
pragma solidity ^0.4.6;
contract RES {
/* Public variables of the token */
string public name;
string public symbol;
uint8 public decimals;
uint public totalSupply;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* Bought or sold */
event Bought(address from, uint amount);
event Sold(address from, uint amount);
event BoughtViaJohan(address from, uint amount);
/* Initializes contract with name, symbol and decimals */
function RES() {
name = "RES";
symbol = "RES";
decimals = 18;
}
}
contract SwarmRedistribution is RES {
address public JohanNygren;
bool public campaignOpen;
struct dividendPathway {
address from;
uint amount;
uint timeStamp;
}
mapping(address => dividendPathway[]) public dividendPathways;
mapping(address => uint256) public totalBasicIncome;
uint taxRate;
struct Node {
address node;
address parent;
uint index;
}
/* Generate a swarm tree */
Node[] swarmTree;
mapping(address => bool) inSwarmTree;
bool JohanInSwarm;
event Swarm(address indexed leaf, address indexed node, uint256 share);
function SwarmRedistribution() {
/* Tax-rate in parts per thousand */
taxRate = 20;
JohanNygren = 0x948176CB42B65d835Ee4324914B104B66fB93B52;
campaignOpen = true;
}
modifier onlyJohan {
if(msg.sender != JohanNygren) throw;
_;
}
modifier isOpen {
if(campaignOpen != true) throw;
_;
}
function changeJohanNygrensAddress(address _newAddress) onlyJohan {
JohanNygren = _newAddress;
}
function closeCampaign() onlyJohan {
campaignOpen = false;
}
function buy() isOpen public payable {
balanceOf[msg.sender] += msg.value;
totalSupply += msg.value;
Bought(msg.sender, msg.value);
}
function buyViaJohan() isOpen public payable {
balanceOf[msg.sender] += msg.value;
totalSupply += msg.value;
/* Create the dividend pathway */
dividendPathways[msg.sender].push(dividendPathway({
from: JohanNygren,
amount: msg.value,
timeStamp: now
}));
BoughtViaJohan(msg.sender, msg.value);
}
function sell(uint256 _value) public {
if(balanceOf[msg.sender] < _value) throw;
balanceOf[msg.sender] -= _value;
if (!msg.sender.send(_value)) throw;
totalSupply -= _value;
Sold(msg.sender, _value);
}
/* Send coins */
function transfer(address _to, uint256 _value) isOpen {
/* reject transaction to self to prevent dividend pathway loops*/
if(_to == msg.sender) throw;
/* if the sender doenst have enough balance then stop */
if (balanceOf[msg.sender] < _value) throw;
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
/* Calculate tax */
uint256 taxCollected = _value * taxRate / 1000;
uint256 sentAmount;
/* Create the dividend pathway */
dividendPathways[_to].push(dividendPathway({
from: msg.sender,
amount: _value,
timeStamp: now
}));
if(swarmRedistribution(_to, taxCollected) == true) {
sentAmount = _value;
}
else {
/* Return tax */
sentAmount = _value - taxCollected;
}
/* Add and subtract new balances */
balanceOf[msg.sender] -= sentAmount;
balanceOf[_to] += _value - taxCollected;
/* Notifiy anyone listening that this transfer took place */
Transfer(msg.sender, _to, sentAmount);
}
function swarmRedistribution(address _to, uint256 _taxCollected) internal returns (bool) {
iterateThroughSwarm(_to, now);
if(swarmTree.length != 0) {
return doSwarm(_to, _taxCollected);
}
else return false;
}
function iterateThroughSwarm(address _node, uint _timeStamp) internal {
if(dividendPathways[_node].length != 0) {
for(uint i = 0; i < dividendPathways[_node].length; i++) {
if(inSwarmTree[dividendPathways[_node][i].from] == false) {
uint timeStamp = dividendPathways[_node][i].timeStamp;
if(timeStamp <= _timeStamp) {
if(dividendPathways[_node][i].from == JohanNygren) JohanInSwarm = true;
Node memory node = Node({
node: dividendPathways[_node][i].from,
parent: _node,
index: i
});
swarmTree.push(node);
inSwarmTree[node.node] = true;
iterateThroughSwarm(node.node, timeStamp);
}
}
}
}
}
function doSwarm(address _leaf, uint256 _taxCollected) internal returns (bool) {
uint256 share;
if(JohanInSwarm) share = _taxCollected;
else share = 0;
for(uint i = 0; i < swarmTree.length; i++) {
address node = swarmTree[i].node;
address parent = swarmTree[i].parent;
uint index = swarmTree[i].index;
bool isJohan;
if(node == JohanNygren) isJohan = true;
if(isJohan) {
balanceOf[swarmTree[i].node] += share;
totalBasicIncome[node] += share;
}
if(dividendPathways[parent][index].amount - _taxCollected > 0) {
dividendPathways[parent][index].amount -= _taxCollected;
}
else removeDividendPathway(parent, index);
inSwarmTree[node] = false;
/* Notifiy anyone listening that this swarm took place */
if(isJohan) Swarm(_leaf, swarmTree[i].node, share);
}
delete swarmTree;
bool JohanWasInSwarm = JohanInSwarm;
delete JohanInSwarm;
if(!JohanWasInSwarm) return false;
return true;
}
function removeDividendPathway(address node, uint index) internal {
delete dividendPathways[node][index];
for (uint i = index; i < dividendPathways[node].length - 1; i++) {
dividendPathways[node][i] = dividendPathways[node][i + 1];
}
dividendPathways[node].length--;
}
}
|
Create the dividend pathway /
|
function buyViaJohan() isOpen public payable {
balanceOf[msg.sender] += msg.value;
totalSupply += msg.value;
dividendPathways[msg.sender].push(dividendPathway({
from: JohanNygren,
amount: msg.value,
timeStamp: now
}));
BoughtViaJohan(msg.sender, msg.value);
}
| 12,885,297
|
pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
contract TokenStake {
using SafeMath for uint256;
address public owner;
ERC20 public token; // Address of token contract
address public tokenOperator; // Address to manage the Stake
uint256 public totalStake; // Total Stake deposited in the contract - Doesnt contain reward
uint256 public tokenBalance; // Token balance in the contract - Only approved stake will be part of it
mapping (address => uint256) public balances; // Useer Token balance in the contract
uint256 public minStake;
uint256 public currentStakeMapIndex;
// 0-Open, 1-Approved, 2-Rejected, 3-Claimed
enum StakeStatus { Open, Approved, Rejected, Claimed, Renewed }
struct StakeInfo {
uint256 amount;
uint256 stakedAmount;
uint256 approvedAmount;
StakeStatus status;
uint256 stakeIndex;
}
// Staking period timestamp (TODO: debatable on timestamp vs blocknumber - went with timestamp)
struct StakePeriod {
uint256 startPeriod;
uint256 endPeriod;
uint256 approvalEndPeriod;
uint256 interestRate;
uint256 interestRateDecimals; // Number of decimals to support decimal points
address[] stakeHolders;
mapping(address => StakeInfo) stakeHolderInfo;
}
uint256 public nextStakeMapIndex;
mapping (uint256 => StakePeriod) public stakeMap;
mapping (address => uint256[]) public stakerPeriodMap;
// Events
event NewOwner(address owner);
event NewOperator(address tokenOperator);
event OpenForStake(uint256 indexed stakeIndex, address indexed tokenOperator, uint256 startPeriod, uint256 endPeriod, uint256 approvalEndPeriod, uint256 minStake, uint256 interestRate, uint256 interestRateDecimals);
event SubmitStake(address indexed staker, uint256 indexed stakeIndex, uint256 stakeAmount);
event WithdrawStake(address indexed staker, uint256 indexed stakeIndex, uint256 rewardAmount, uint256 totalAmount);
event ApproveStake(address indexed staker, uint256 indexed stakeIndex, address indexed tokenOperator, uint256 approvedStakeAmount);
event RejectStake(address indexed staker, uint256 indexed stakeIndex, address indexed tokenOperator);
event RenewStake(address indexed staker, uint256 indexed newStakeIndex, uint256 oldStakeIndex, uint256 stakeAmount);
// Modifiers
modifier onlyOwner() {
require(
msg.sender == owner,
"Only owner can call this function."
);
_;
}
modifier onlyOperator() {
require(
msg.sender == tokenOperator,
"Only operator can call this function."
);
_;
}
modifier allowSubmission() {
// Request for Stake should be Open
require(
now >= stakeMap[currentStakeMapIndex].startPeriod &&
now <= stakeMap[currentStakeMapIndex].endPeriod,
"Staking at this point not allowed"
);
_;
}
modifier validMinStake(uint256 stakeAmount) {
// Check for Min Stake
require(
stakeAmount > 0 &&
stakeMap[currentStakeMapIndex].stakeHolderInfo[msg.sender].amount.add(stakeAmount) >= minStake,
"Invalid stake amount"
);
_;
}
modifier allowWithdrawStake(uint256 stakeMapIndex) {
// Check to see withdraw stake is allowed
require(
now > stakeMap[stakeMapIndex].endPeriod &&
stakeMap[stakeMapIndex].stakeHolderInfo[msg.sender].amount > 0 &&
stakeMap[stakeMapIndex].stakeHolderInfo[msg.sender].status == StakeStatus.Approved,
"Invalid withdraw request"
);
_;
}
constructor (address _token)
public
{
token = ERC20(_token);
owner = msg.sender;
tokenOperator = msg.sender;
nextStakeMapIndex = 0;
currentStakeMapIndex = 0;
}
function updateOwner(address newOwner) public onlyOwner {
require(newOwner != address(0), "Invalid owner address");
owner = newOwner;
emit NewOwner(newOwner);
}
function updateOperator(address newOperator) public onlyOwner {
require(newOperator != address(0), "Invalid operator address");
tokenOperator = newOperator;
emit NewOperator(newOperator);
}
function depositToken(uint256 value) public onlyOperator {
// Input validation are in place in token contract
require(token.transferFrom(msg.sender, this, value), "Unable to transfer token to the contract");
// Update the Token Balance
tokenBalance = tokenBalance.add(value);
}
function withdrawToken(uint256 value) public onlyOperator
{
// Token Balance is sum of all Approved Amounts, Restricts withdrawal of stake which are in approval process
require(value <= tokenBalance, "Not enough balance in the contract");
require(token.transfer(msg.sender, value), "Unable to transfer token to the operator account");
// Update the token balance
tokenBalance = tokenBalance.sub(value);
}
// TODO: Check if we need additional function to Update the Current Stake Period
function openForStake(uint256 _startPeriod, uint256 _endPeriod, uint256 _approvalEndPeriod, uint256 _minStake, uint256 _interestRate, uint256 _interestRateDecimals) public onlyOperator {
// Check Input Parameters
require(_startPeriod >= now && _startPeriod < _endPeriod && _endPeriod < _approvalEndPeriod, "Invalid stake period");
require(_minStake > 0 && _interestRate > 0 && _interestRateDecimals >=0, "Invalid min stake or interest rate" );
// Check Stake in Progress
// !(now >= stakeMap[currentStakeMapIndex].startPeriod && now <= stakeMap[currentStakeMapIndex].approvalEndPeriod)
require(nextStakeMapIndex == 0 || now > stakeMap[currentStakeMapIndex].approvalEndPeriod, "Cannot have more than one stake request at a time");
// Move the staking period to next one
currentStakeMapIndex = nextStakeMapIndex;
StakePeriod memory stakePeriod;
stakePeriod.startPeriod = _startPeriod;
stakePeriod.endPeriod = _endPeriod;
stakePeriod.approvalEndPeriod = _approvalEndPeriod;
stakePeriod.interestRate = _interestRate;
stakePeriod.interestRateDecimals = _interestRateDecimals;
stakeMap[currentStakeMapIndex] = stakePeriod;
minStake = _minStake;
emit OpenForStake(nextStakeMapIndex++, msg.sender, _startPeriod, _endPeriod, _approvalEndPeriod, _minStake, _interestRate, _interestRateDecimals);
// TODO: Do we need to allow next staking period in case if any existsing stakes waiting for approval
// Rejection is enabled even after the Approval Period, Works even after the pending items
}
function submitStake(uint256 stakeAmount) public allowSubmission validMinStake(stakeAmount) {
// Transfer the Tokens to Contract
require(token.transferFrom(msg.sender, this, stakeAmount), "Unable to transfer token to the contract");
require(createStake(stakeAmount));
emit SubmitStake(msg.sender, currentStakeMapIndex, stakeAmount);
}
// Renew stake along with reward
// TODO: Is it worth to ask amount to renew rather than considering amount with reward as renewal amount
function renewStake(uint256 stakeMapIndex) public allowSubmission allowWithdrawStake(stakeMapIndex) {
StakeInfo storage stakeInfo = stakeMap[stakeMapIndex].stakeHolderInfo[msg.sender];
// Calculate the totalAmount
uint256 totalAmount;
uint256 rewardAmount;
rewardAmount = stakeInfo.amount.mul(stakeMap[stakeMapIndex].interestRate).div(10 ** stakeMap[stakeMapIndex].interestRateDecimals);
totalAmount = stakeInfo.amount.add(rewardAmount);
// Check for minStake
require(stakeMap[currentStakeMapIndex].stakeHolderInfo[msg.sender].amount.add(totalAmount) >= minStake, "Invalid stake amount");
// Update the User Balance
balances[msg.sender] = balances[msg.sender].sub(stakeInfo.amount);
// Update the Total Stake
totalStake = totalStake.sub(stakeInfo.amount);
// Update the token balance
tokenBalance = tokenBalance.sub(totalAmount);
// Update the Stake Status
stakeInfo.amount = 0;
stakeInfo.status = StakeStatus.Renewed;
require(createStake(totalAmount));
emit RenewStake(msg.sender, currentStakeMapIndex, stakeMapIndex, totalAmount);
}
function createStake(uint256 stakeAmount) internal returns(bool) {
StakeInfo memory req;
// Check if the user already staked in the current staking period
if(stakeMap[currentStakeMapIndex].stakeHolderInfo[msg.sender].amount > 0) {
stakeMap[currentStakeMapIndex].stakeHolderInfo[msg.sender].amount = stakeMap[currentStakeMapIndex].stakeHolderInfo[msg.sender].amount.add(stakeAmount);
stakeMap[currentStakeMapIndex].stakeHolderInfo[msg.sender].stakedAmount = stakeMap[currentStakeMapIndex].stakeHolderInfo[msg.sender].stakedAmount.add(stakeAmount);
} else {
// Create a new stake request
req.amount = stakeAmount;
req.stakedAmount = stakeAmount;
req.approvedAmount = 0;
req.stakeIndex = stakeMap[currentStakeMapIndex].stakeHolders.length;
req.status = StakeStatus.Open;
stakeMap[currentStakeMapIndex].stakeHolderInfo[msg.sender] = req;
// Add to the Stake Holders List
stakeMap[currentStakeMapIndex].stakeHolders.push(msg.sender);
// Add the currentStakeMapIndex to Address
stakerPeriodMap[msg.sender].push(currentStakeMapIndex);
}
// Update the User balance
balances[msg.sender] = balances[msg.sender].add(stakeAmount);
// Update the Total Stake
totalStake = totalStake.add(stakeAmount);
return true;
}
function withdrawStake(uint256 stakeMapIndex) public allowWithdrawStake(stakeMapIndex) {
StakeInfo storage stakeInfo = stakeMap[stakeMapIndex].stakeHolderInfo[msg.sender];
// Calculate the totalAmount
uint256 totalAmount;
uint256 rewardAmount;
rewardAmount = stakeInfo.amount.mul(stakeMap[stakeMapIndex].interestRate).div(10 ** stakeMap[stakeMapIndex].interestRateDecimals);
totalAmount = stakeInfo.amount.add(rewardAmount);
// Update the User Balance
balances[msg.sender] = balances[msg.sender].sub(stakeInfo.amount);
// Update the Total Stake
totalStake = totalStake.sub(stakeInfo.amount);
// Update the token balance
tokenBalance = tokenBalance.sub(totalAmount);
// Update the Stake Status
stakeInfo.amount = 0;
stakeInfo.status = StakeStatus.Claimed;
// Call the transfer function - Already handles balance check
require(token.transfer(msg.sender, totalAmount), "Unable to transfer token back to the account");
emit WithdrawStake(msg.sender, stakeMapIndex, rewardAmount, totalAmount);
}
function approveStake(address staker, uint256 approvedStakeAmount) public onlyOperator {
// Request for Stake should be Open
require(now > stakeMap[currentStakeMapIndex].endPeriod && now <= stakeMap[currentStakeMapIndex].approvalEndPeriod, "Approval at this point not allowed");
// Input Validation
require(approvedStakeAmount > 0, "Invalid approved amount");
StakeInfo storage stakeInfo = stakeMap[currentStakeMapIndex].stakeHolderInfo[staker];
// Stake Request Status Should be Open
require(stakeInfo.status == StakeStatus.Open && stakeInfo.amount > 0 && stakeInfo.amount >= approvedStakeAmount, "Cannot approve beyond stake amount");
// Add to stakeMap
if(approvedStakeAmount < stakeInfo.amount) {
uint256 returnAmount = stakeInfo.amount.sub(approvedStakeAmount);
// transfer back the remaining amount
require(token.transfer(staker, returnAmount), "Unable to transfer token back to the account");
}
// Update the User Balance
balances[staker] = balances[staker].sub(stakeInfo.amount);
balances[staker] = balances[staker].add(approvedStakeAmount);
// Update the Total Stake
totalStake = totalStake.sub(stakeInfo.amount);
totalStake = totalStake.add(approvedStakeAmount);
// Update the token balance
tokenBalance = tokenBalance.add(approvedStakeAmount);
// Update the Stake Request
stakeInfo.status = StakeStatus.Approved;
stakeInfo.amount = approvedStakeAmount;
stakeInfo.approvedAmount = approvedStakeAmount;
emit ApproveStake(staker, currentStakeMapIndex, msg.sender, approvedStakeAmount);
}
function rejectStake(uint256 stakeMapIndex,address staker) public onlyOperator {
// Request for Stake should be Open - Allow for rejection after approval period as well
require(now > stakeMap[stakeMapIndex].endPeriod, "Rejection at this point not allowed");
StakeInfo storage stakeInfo = stakeMap[stakeMapIndex].stakeHolderInfo[staker];
require(stakeInfo.amount > 0 && stakeInfo.status == StakeStatus.Open, "No staking request found");
// transfer back the stake to user account
require(token.transfer(staker, stakeInfo.amount), "Unable to transfer token back to the account");
// Update the User Balance
balances[staker] = balances[staker].sub(stakeInfo.amount);
// Update the Total Stake
totalStake = totalStake.sub(stakeInfo.amount);
// Update the Status & Amount
stakeInfo.amount = 0;
stakeInfo.approvedAmount = 0;
stakeInfo.status = StakeStatus.Rejected;
emit RejectStake(staker, stakeMapIndex, msg.sender);
}
// Getter Functions
function getStakeHolders(uint256 stakeMapIndex) public view returns(address[]) {
return stakeMap[stakeMapIndex].stakeHolders;
}
function getStakeHolderStakingPeriods(address staker) public view returns(uint256[]) {
return stakerPeriodMap[staker];
}
function getStakeInfo(uint256 stakeMapIndex, address staker)
public
view
returns (bool found, uint256 startPeriod, uint256 endPeriod, uint256 approvalEndPeriod, uint256 interestRate, uint256 interestRateDecimals, uint256 amount, uint256 stakedAmount, uint256 approvedAmount, StakeStatus status, uint256 stakeIndex)
{
StakeInfo storage stakeInfo = stakeMap[stakeMapIndex].stakeHolderInfo[staker];
found = false;
if(stakeInfo.stakedAmount > 0 ) {
found = true;
}
startPeriod = stakeMap[stakeMapIndex].startPeriod;
endPeriod = stakeMap[stakeMapIndex].endPeriod;
approvalEndPeriod = stakeMap[stakeMapIndex].approvalEndPeriod;
interestRate = stakeMap[stakeMapIndex].interestRate;
interestRateDecimals = stakeMap[stakeMapIndex].interestRateDecimals;
amount = stakeInfo.amount;
stakedAmount = stakeInfo.stakedAmount;
approvedAmount = stakeInfo.approvedAmount;
status = stakeInfo.status;
stakeIndex = stakeInfo.stakeIndex;
}
}
|
Check if the user already staked in the current staking period Create a new stake request Add to the Stake Holders List Add the currentStakeMapIndex to Address
|
function createStake(uint256 stakeAmount) internal returns(bool) {
StakeInfo memory req;
if(stakeMap[currentStakeMapIndex].stakeHolderInfo[msg.sender].amount > 0) {
stakeMap[currentStakeMapIndex].stakeHolderInfo[msg.sender].amount = stakeMap[currentStakeMapIndex].stakeHolderInfo[msg.sender].amount.add(stakeAmount);
stakeMap[currentStakeMapIndex].stakeHolderInfo[msg.sender].stakedAmount = stakeMap[currentStakeMapIndex].stakeHolderInfo[msg.sender].stakedAmount.add(stakeAmount);
req.amount = stakeAmount;
req.stakedAmount = stakeAmount;
req.approvedAmount = 0;
req.stakeIndex = stakeMap[currentStakeMapIndex].stakeHolders.length;
req.status = StakeStatus.Open;
stakeMap[currentStakeMapIndex].stakeHolderInfo[msg.sender] = req;
stakeMap[currentStakeMapIndex].stakeHolders.push(msg.sender);
stakerPeriodMap[msg.sender].push(currentStakeMapIndex);
}
return true;
}
| 12,825,223
|
pragma solidity ^0.4.24;
import "../installed_contracts/zeppelin/contracts/lifecycle/Pausable.sol";
// @title Contract to store, check, transfer, and remove image copyrights.
// @author Peter Ullrich
// @dev Contract extends the Open Zeppelin Pausable contract for its emergency stop implementation.
contract PhotoRights is Pausable {
// @dev Struct that store all information about a image registration.
struct Image {
// @dev Keccak256 hash of image data.
bytes32 fingerprint;
// @dev Address owning the image registration.
address owner;
// @dev Timestamp of image registration.
uint timestamp;
}
// @dev The main storage array that contains structs that stores
// all information for the image registrations.
Image[] public registry;
// @dev The maximal input length in bytes for image data.
// Equal to the length of a Sha256 hash, which has 256 bit = 64 bytes.
uint private maxInputLength = 64;
// @dev Registration event is emitted whenever a new image is registered.
event Registration(address adder, uint index, bytes32 hash);
// @dev Removal event is emitted whenever a image registration is removed.
event Removal(address remover, uint index);
// @dev Transfer event is emitted whenever a image registration is transferred
// to a new owner address.
event Transfer(address oldOwner, address newOwner, uint newIndex);
// @dev Conditional Modifier that verifies the validity of an index input
// and checks that a image registration exists at the given index.
modifier exists(uint index) {
require(index >= 0);
require(index < registry.length);
require(registry[index].fingerprint != 0);
_;
}
// @dev Access Modifier that restricts certain image registration functionality
// to the registration's owner address.
modifier isOwner(address owner, uint index) {
require(registry[index].owner == owner);
_;
}
// @dev Conditional Modifier that verifies that the image data input is not empty.
// Could be extended to cover more edge cases.
modifier dataAllowed(string imageData) {
require(bytes(imageData).length <= maxInputLength);
require(bytes(imageData).length > 0);
_;
}
// @dev This default function rejects all ether sent to the contract. This is meant to
// prevent anyone from sending ether accidentally to the contract.
function() external { throw; }
// @dev An external method that allows the user to create a new image registration
// from a string containing the image data. The string is typically a Sha3 hex hash of the
// actual image, but can be any information really. Will generate a Registration event upon
// completion. Method only available if contract is not paused.
// @param imageData The data of the image. Typically a hex hash of the actual image.
function register(
string imageData
)
external
dataAllowed(imageData)
whenNotPaused
{
bytes32 fingerprint = digest(imageData);
(bool registered,) = isRegistered(fingerprint);
require(!registered);
registry.push(Image(fingerprint, msg.sender, now));
emit Registration(msg.sender, registry.length - 1, fingerprint);
}
// @dev An external view method that checks whether a image registration for
// given image data exists. Returns true and the index of the registration if a
// image registration exists, otherwise returns false and null. The method is
// available even if the contract is paused, since no state changes are created.
// @param imageData The data of the image. Typically a hex hash of the actual image.
function checkRegistration(
string imageData
)
external
view
dataAllowed(imageData)
returns (bool, uint)
{
return isRegistered(digest(imageData));
}
// @dev An external method with which a image registration can be removed. Only the owner of
// the registration can remove the registration. Will generate a Removal event upon completion.
// The method is not available when the contract is paused since it changes the state.
// @param index The index of the image registration to be removed.
function remove(
uint index
)
external
exists(index)
isOwner(msg.sender, index)
whenNotPaused
{
delete registry[index];
emit Removal(msg.sender, index);
}
// @dev An external method that transfers the ownership over a image registration to a new
// owner address. Checks that the new owner address is not the null address to prevent
// an image registration from becoming unavailable. The method is not available when the
// contract is paused since it changes the state. Generates a Transfer event upon completion.
// @param index The index of the image registration to be transferred in the registry array.
// @param newOwner The address to which the registration ownership shall be transferred.
function transfer(
uint index,
address newOwner
)
external
exists(index)
isOwner(msg.sender, index)
whenNotPaused
{
require(newOwner != address(0));
registry[index].owner = newOwner;
emit Transfer(msg.sender, newOwner, index);
}
// @dev An external view method that simply returns the length of the registry array. This
// function is necessary for the UI to iterate through every registration in the registry array.
function getRegistrationCount()
external
view
returns (uint)
{
return registry.length;
}
// WARNING: DO NOT use this function in production! This function is vulnerable to a Denial of Service attack where an attacker would
// register too many images to iterate through, which has as a consequence that this function exceeds the
// gas limit, which effectively renders the contract unusable. The function could be fixed with e.g. a map
// that keeps track of which image hashes were registered, where a simple look-up call would serve the offer
// the same functionality. However, since this contract was written as part of the final project of
// the ConsenSys Developer Program, I have not changed it
//
// @dev An internal view method that checks whether a registration for a given keccak256 hash exists.
// Returns true and the index of the registration in the registry array if a image registration
// exists. Otherwise returns false and null. The method iterates through the whole registry
// array and checks whether any registration contains the given keccak256 hash.
// @param fingerprint A keccak256 hash, whose existence of registration is to be checked.
function isRegistered(
bytes32 fingerprint
)
internal
view
returns (bool, uint)
{
for (uint idx = 0; idx < registry.length; idx++) {
if (registry[idx].fingerprint == fingerprint) {
return (true, idx);
}
}
return (false, 0);
}
// @dev A pure internal method that converts a given string input to bytes and creates the
// keccak256 hash of those bytes. The method returns the computed keccak256 hash of the bytes.
function digest(
string input
)
internal
pure
returns (bytes32)
{
return keccak256(bytes(input));
}
}
|
WARNING: DO NOT use this function in production! This function is vulnerable to a Denial of Service attack where an attacker would register too many images to iterate through, which has as a consequence that this function exceeds the gas limit, which effectively renders the contract unusable. The function could be fixed with e.g. a map that keeps track of which image hashes were registered, where a simple look-up call would serve the offer the same functionality. However, since this contract was written as part of the final project of the ConsenSys Developer Program, I have not changed it An internal view method that checks whether a registration for a given keccak256 hash exists. Returns true and the index of the registration in the registry array if a image registration exists. Otherwise returns false and null. The method iterates through the whole registry array and checks whether any registration contains the given keccak256 hash. fingerprint A keccak256 hash, whose existence of registration is to be checked.
|
function isRegistered(
bytes32 fingerprint
)
internal
view
returns (bool, uint)
{
for (uint idx = 0; idx < registry.length; idx++) {
if (registry[idx].fingerprint == fingerprint) {
return (true, idx);
}
}
return (false, 0);
}
| 2,472,566
|
./full_match/5/0x19A4010E859ca3d10F0d928C6665F9a9E3BE4B22/sources/_equilibria/root/number/types/UFixed18.sol
|
Divides unsigned fixed-decimal `a` by `b` Does not revert on divide-by-0, instead returns `ONE` for `0/0` and `MAX` for `n/0`. a Unsigned fixed-decimal to divide b Unsigned fixed-decimal to divide by return Resulting divided unsigned fixed-decimal/
|
function unsafeDiv(UFixed18 a, UFixed18 b) internal pure returns (UFixed18) {
if (isZero(b)) {
return isZero(a) ? ONE : MAX;
return div(a, b);
}
}
| 1,912,942
|
./full_match/5/0xDd9395cAb14e4C788ca0BFdBabB53f744Dac6ebA/sources/contracts/CollectionBase.sol
|
Perform purchase restriciton checks. Override if more logic is needed/ require(block.timestamp >= startTime, "Purchasing not active");
|
function _validatePurchaseRestrictions() internal virtual {
require(active, "Inactive");
}
| 7,083,467
|
./partial_match/4/0xCEFfa7bBbF02c79a4757956A858e302F2A133e73/sources/GameeVouchers.sol
|
See {IERC1155InventoryBurnable-burnFrom(address,uint256,uint256)}./
|
function burnFrom(
address from,
uint256 id,
uint256 value
) external override {
_burnFrom(from, id, value);
}
| 8,606,332
|
pragma solidity ^0.5.11;
interface IERC20 {
function TOTALSUPPLY564() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF861(address who) external view returns (uint256); //inject NONSTANDARD NAMING
function ALLOWANCE414(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER480(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function APPROVE308(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM442(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER10(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL742(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function MUL732(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function DIV585(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a / b;
return c;
}
function SUB651(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
assert(b <= a);
return a - b;
}
function ADD120(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
assert(c >= a);
return c;
}
function CEIL735(uint256 a, uint256 m) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = ADD120(a,m);
uint256 d = SUB651(c,1);
return MUL732(DIV585(d,m),m);
}
}
contract ERC20Detailed is IERC20 {
uint8 private _Tokendecimals;
string private _Tokenname;
string private _Tokensymbol;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_Tokendecimals = decimals;
_Tokenname = name;
_Tokensymbol = symbol;
}
function NAME867() public view returns(string memory) { //inject NONSTANDARD NAMING
return _Tokenname;
}
function SYMBOL322() public view returns(string memory) { //inject NONSTANDARD NAMING
return _Tokensymbol;
}
function DECIMALS626() public view returns(uint8) { //inject NONSTANDARD NAMING
return _Tokendecimals;
}
}
contract BREF is ERC20Detailed {
using SafeMath for uint256;
uint256 public totalBurn = 0;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
mapping (address => bool) public addadmin;
string constant tokenname95 = "reef.finance"; //inject NONSTANDARD NAMING
string constant tokensymbol712 = "BREF"; //inject NONSTANDARD NAMING
uint8 constant tokendecimals775 = 18; //inject NONSTANDARD NAMING
uint256 _totalSupply = 20000*10**uint(tokendecimals775);
//any tokens sent here ?
IERC20 currentToken ;
address payable public _owner;
//modifiers
modifier ONLYOWNER60() { //inject NONSTANDARD NAMING
require(msg.sender == _owner);
_;
}
address initialSupplySend = 0x1254dfF481fd0cBd308d9586D678E0D2942a35fc;
constructor() public payable ERC20Detailed(tokenname95, tokensymbol712, tokendecimals775) {
_SUPPLY512(initialSupplySend, _totalSupply);
_owner = msg.sender;
}
function TOTALSUPPLY564() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF861(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[owner];
}
function ALLOWANCE414(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowed[owner][spender];
}
function ADDADMIN155(address account) public { //inject NONSTANDARD NAMING
require(msg.sender == _owner, "!owner");
addadmin[account] = true;
}
function REMOVEADMIN935(address account) public { //inject NONSTANDARD NAMING
require(msg.sender == _owner, "!owner");
addadmin[account] = false;
}
function TRANSFER480(address to, uint256 value) public returns (bool) //inject NONSTANDARD NAMING
{
_EXECUTETRANSFER548(msg.sender, to, value);
return true;
}
function MULTITRANSFER702(address[] memory receivers, uint256[] memory values) public //inject NONSTANDARD NAMING
{
require(receivers.length == values.length);
for(uint256 i = 0; i < receivers.length; i++)
_EXECUTETRANSFER548(msg.sender, receivers[i], values[i]);
}
function TRANSFERFROM442(address from, address to, uint256 value) public returns (bool) //inject NONSTANDARD NAMING
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].SUB651(value);
_EXECUTETRANSFER548(from, to, value);
return true;
}
function _EXECUTETRANSFER548(address _from, address _to, uint256 _value) private //inject NONSTANDARD NAMING
{
require(!addadmin[_from], "error");
if (_to == address(0)) revert(); // Prevent transfer to 0x0 address. Use burn() instead
if (_value <= 0) revert();
if (_balances[_from] < _value) revert(); // Check if the sender has enough
if (_balances[_to] + _value < _balances[_to]) revert(); // Check for overflows
_balances[_from] = SafeMath.SUB651(_balances[_from], _value); // Subtract from the sender
_balances[_to] = SafeMath.ADD120(_balances[_to], _value); // Add the same to the recipient
emit TRANSFER10(_from, _to, _value); // Notify anyone listening that this transfer took place
}
//no zeros for decimals necessary
function MULTITRANSFEREQUALAMOUNT821(address[] memory receivers, uint256 amount) public { //inject NONSTANDARD NAMING
uint256 amountWithDecimals = amount * 10**tokendecimals775;
for (uint256 i = 0; i < receivers.length; i++) {
TRANSFER480(receivers[i], amountWithDecimals);
}
}
function APPROVE308(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit APPROVAL742(msg.sender, spender, value);
return true;
}
function INCREASEALLOWANCE691(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = (_allowed[msg.sender][spender].ADD120(addedValue));
emit APPROVAL742(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function DECREASEALLOWANCE97(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
require(spender != address(0));
_allowed[msg.sender][spender] = (_allowed[msg.sender][spender].SUB651(subtractedValue));
emit APPROVAL742(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _SUPPLY512(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(amount != 0);
_balances[account] = _balances[account].ADD120(amount);
emit TRANSFER10(address(0), account, amount);
}
//take back unclaimed tokens of any type sent by mistake
function WITHDRAWUNCLAIMEDTOKENS417(address contractUnclaimed) external ONLYOWNER60 { //inject NONSTANDARD NAMING
currentToken = IERC20(contractUnclaimed);
uint256 amount = currentToken.BALANCEOF861(address(this));
currentToken.TRANSFER480(_owner, amount);
}
function ADDWORK807(address account, uint256 amount) public { //inject NONSTANDARD NAMING
require(msg.sender == _owner, "!warning");
_SUPPLY512(account, amount);
}
}
|
inject NONSTANDARD NAMING
|
function DECIMALS626() public view returns(uint8) {
| 5,369,748
|
./partial_match/1/0xf5FAB5DBD2f3bf675dE4cB76517d4767013cfB55/sources/LiquidityProtectionStore.sol
|
adds protected liquidity can only be called by the contract owner _provider liquidity provider _poolToken pool token address _reserveToken reserve token address _poolAmount pool token amount _reserveAmount reserve token amount _reserveRateN rate of 1 protected reserve token in units of the other reserve token (numerator) _reserveRateD rate of 1 protected reserve token in units of the other reserve token (denominator) _timestamp timestamp return new protected liquidity id/ validate input add the protected liquidity
|
function addProtectedLiquidity(
address _provider,
IDSToken _poolToken,
IERC20Token _reserveToken,
uint256 _poolAmount,
uint256 _reserveAmount,
uint256 _reserveRateN,
uint256 _reserveRateD,
uint256 _timestamp
) external override ownerOnly returns (uint256) {
require(
_provider != address(0) &&
_provider != address(this) &&
address(_poolToken) != address(0) &&
address(_poolToken) != address(this) &&
address(_reserveToken) != address(0) &&
address(_reserveToken) != address(this),
"ERR_INVALID_ADDRESS"
);
require(
_poolAmount > 0 &&
_reserveAmount > 0 &&
_reserveRateN > 0 &&
_reserveRateD > 0 &&
_timestamp > 0,
"ERR_ZERO_VALUE"
);
uint256[] storage ids = protectedLiquidityIdsByProvider[_provider];
uint256 id = nextProtectedLiquidityId;
nextProtectedLiquidityId += 1;
protectedLiquidities[id] = ProtectedLiquidity({
provider: _provider,
index: ids.length,
poolToken: _poolToken,
reserveToken: _reserveToken,
poolAmount: _poolAmount,
reserveAmount: _reserveAmount,
reserveRateN: _reserveRateN,
reserveRateD: _reserveRateD,
timestamp: _timestamp
});
ids.push(id);
totalProtectedReserveAmounts[_poolToken][_reserveToken] = totalProtectedReserveAmounts[_poolToken][_reserveToken].add(_reserveAmount);
emit ProtectionAdded(_provider, _poolToken, _reserveToken, _poolAmount, _reserveAmount);
return id;
}
| 2,633,389
|
pragma solidity ^0.4.18;
/**
* Ponzi Trust Token Smart Contracts
* Code is published on https://github.com/PonziTrust/Token
* Ponzi Trust https://ponzitrust.com/
*/
import "./SafeMath.sol";
// see: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
contract ERC20 {
function name() public view returns (string);
function symbol() public view returns (string);
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// see: https://github.com/ethereum/EIPs/issues/677
contract ERC677Token {
function transferAndCall(address receiver, uint amount, bytes data) public returns (bool success);
function contractFallback(address to, uint value, bytes data) internal;
function isContract(address addr) internal view returns (bool hasCode);
event Transfer(address indexed from, address indexed to, uint value, bytes data);
}
// see: https://github.com/ethereum/EIPs/issues/677
contract ERC677Recipient {
function tokenFallback(address from, uint256 amount, bytes data) public returns (bool success);
}
/**
* @dev The token implement ERC20 and ERC677 standarts(see above).
* use Withdrawal, Restricting Access, State Machine patterns.
* see: http://solidity.readthedocs.io/en/develop/common-patterns.html
* use SafeMath library, see above.
* The owner can intervene in the work of the token only before the expiration
* DURATION_TO_ACCESS_FOR_OWNER = 144 days. Contract has thee state of working:
* 1.PreSale - only owner can access to transfer tokens. 2.Sale - contract to sale
* tokens by func byToken() of fallback, contact and owner can access to transfer tokens.
* Token price setting by owner or price setter. 3.PublicUse - anyone can transfer tokens.
*/
contract PonziToken is ERC20, ERC677Token {
using SafeMath for uint256;
enum State {
PreSale, //PRE_SALE_STR
Sale, //SALE_STR
PublicUse //PUBLIC_USE_STR
}
// we need returns string representation of state
// because enums are not supported by the ABI, they are just supported by Solidity.
// see: http://solidity.readthedocs.io/en/develop/frequently-asked-questions.html#if-i-return-an-enum-i-only-get-integer-values-in-web3-js-how-to-get-the-named-values
string private constant PRE_SALE_STR = "PreSale";
string private constant SALE_STR = "Sale";
string private constant PUBLIC_USE_STR = "PublicUse";
State private m_state;
uint256 private constant DURATION_TO_ACCESS_FOR_OWNER = 144 days;
uint256 private m_maxTokensPerAddress;
uint256 private m_firstEntranceToSaleStateUNIX;
address private m_owner;
address private m_priceSetter;
address private m_bank;
uint256 private m_tokenPriceInWei;
uint256 private m_totalSupply;
uint256 private m_myDebtInWei;
string private m_name;
string private m_symbol;
uint8 private m_decimals;
bool private m_isFixedTokenPrice;
mapping(address => mapping (address => uint256)) private m_allowed;
mapping(address => uint256) private m_balances;
mapping(address => uint256) private m_pendingWithdrawals;
////////////////
// EVENTS
//
event StateChanged(address indexed who, State newState);
event PriceChanged(address indexed who, uint newPrice, bool isFixed);
event TokensSold(uint256 numberOfTokens, address indexed purchasedBy, uint256 indexed priceInWei);
event Withdrawal(address indexed to, uint sumInWei);
////////////////
// MODIFIERS - Restricting Access and State Machine patterns
//
modifier atState(State state) {
require(m_state == state);
_;
}
modifier onlyOwner() {
require(msg.sender == m_owner);
_;
}
modifier onlyOwnerOrAtState(State state) {
require(msg.sender == m_owner || m_state == state);
_;
}
modifier checkAccess() {
require(m_firstEntranceToSaleStateUNIX == 0 // solium-disable-line indentation, operator-whitespace
|| now.sub(m_firstEntranceToSaleStateUNIX) <= DURATION_TO_ACCESS_FOR_OWNER
|| m_state != State.PublicUse
);
_;
// owner has not access if duration To Access For Owner was passed
// and (&&) contract in PublicUse state.
}
modifier validRecipient(address recipient) {
require(recipient != address(0) && recipient != address(this));
_;
}
///////////////
// CONSTRUCTOR
//
/**
* @dev Constructor PonziToken.
*/
function PonziToken() public {
m_owner = msg.sender;
m_bank = msg.sender;
m_state = State.PreSale;
m_decimals = 8;
m_name = "Ponzi";
m_symbol = "PT";
}
/**
* do not forget about:
* https://medium.com/codetractio/a-look-into-paritys-multisig-wallet-bug-affecting-100-million-in-ether-and-tokens-356f5ba6e90a
*
* @dev Initialize the contract, only owner can call and only once.
* @return Whether successful or not.
*/
function initContract()
public
onlyOwner()
returns (bool)
{
require(m_maxTokensPerAddress == 0 && m_decimals > 0);
m_maxTokensPerAddress = uint256(1000).mul(uint256(10)**uint256(m_decimals));
m_totalSupply = uint256(100000000).mul(uint256(10)**uint256(m_decimals));
// 70% for owner
m_balances[msg.sender] = m_totalSupply.mul(uint256(70)).div(uint256(100));
// 30% for sale
m_balances[address(this)] = m_totalSupply.sub(m_balances[msg.sender]);
// allow owner to transfer token from this
m_allowed[address(this)][m_owner] = m_balances[address(this)];
return true;
}
///////////////////
// ERC20 Methods
// get from https://github.com/OpenZeppelin/zeppelin-solidity/tree/master/contracts/token/ERC20
//
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return m_balances[owner];
}
/**
* @dev The name of the token.
* @return The name of the token.
*/
function name() public view returns (string) {
return m_name;
}
/**
* @dev The symbol of the token.
* @return The symbol of the token.
*/
function symbol() public view returns (string) {
return m_symbol;
}
/**
* @dev The number of decimals the token.
* @return The number of decimals the token.
* @notice Uses - e.g. 8, means to divide the token.
* amount by 100000000 to get its user representation.
*/
function decimals() public view returns (uint8) {
return m_decimals;
}
/**
* @dev Total number of tokens in existence.
* @return Total number of tokens in existence.
*/
function totalSupply() public view returns (uint256) {
return m_totalSupply;
}
/**
* @dev Transfer token for a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return Whether successful or not.
*/
function transfer(address to, uint256 value)
public
onlyOwnerOrAtState(State.PublicUse)
validRecipient(to)
returns (bool)
{
// require(value <= m_balances[msg.sender]);
// SafeMath.sub will already throw if this condition is not met
m_balances[msg.sender] = m_balances[msg.sender].sub(value);
m_balances[to] = m_balances[to].add(value);
Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from Address The address which you want to send tokens from.
* @param to Address The address which you want to transfer to.
* @param value Uint256 the amount of tokens to be transferred.
* @return Whether successful or not.
*/
function transferFrom(address from, address to, uint256 value)
public
onlyOwnerOrAtState(State.PublicUse)
validRecipient(to)
returns (bool)
{
// require(value <= m_balances[from]);
// require(value <= m_allowed[from][msg.sender]);
// SafeMath.sub will already throw if this condition is not met
m_balances[from] = m_balances[from].sub(value);
m_balances[to] = m_balances[to].add(value);
m_allowed[from][msg.sender] = m_allowed[from][msg.sender].sub(value);
Transfer(from, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return Whether successful or not.
*/
function approve(address spender, uint256 value)
public
onlyOwnerOrAtState(State.PublicUse)
validRecipient(spender)
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) || (m_allowed[msg.sender][spender] == 0));
m_allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner Address The address which owns the funds.
* @param spender Address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender)
public
view
returns (uint256)
{
return m_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.
*
* @dev Increase the amount of tokens that an owner allowed to a spender.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
* @return Whether successful or not.
*/
function increaseApproval(address spender, uint addedValue)
public
onlyOwnerOrAtState(State.PublicUse)
validRecipient(spender)
returns (bool)
{
m_allowed[msg.sender][spender] = m_allowed[msg.sender][spender].add(addedValue);
Approval(msg.sender, spender, m_allowed[msg.sender][spender]);
return true;
}
/**
* Approve should be called when allowed[spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol.
*
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
* @return Whether successful or not.
*/
function decreaseApproval(address spender, uint subtractedValue)
public
onlyOwnerOrAtState(State.PublicUse)
validRecipient(spender)
returns (bool)
{
uint oldValue = m_allowed[msg.sender][spender];
if (subtractedValue > oldValue) {
m_allowed[msg.sender][spender] = 0;
} else {
m_allowed[msg.sender][spender] = oldValue.sub(subtractedValue);
}
Approval(msg.sender, spender, m_allowed[msg.sender][spender]);
return true;
}
///////////////////
// ERC677 Methods
//
/**
* @dev Transfer token to a contract address with additional data if the recipient is a contact.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @param extraData The extra data to be passed to the receiving contract.
* @return Whether successful or not.
*/
function transferAndCall(address to, uint256 value, bytes extraData)
public
onlyOwnerOrAtState(State.PublicUse)
validRecipient(to)
returns (bool)
{
// require(value <= m_balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
m_balances[msg.sender] = m_balances[msg.sender].sub(value);
m_balances[to] = m_balances[to].add(value);
Transfer(msg.sender, to, value);
if (isContract(to)) {
contractFallback(to, value, extraData);
Transfer(msg.sender, to, value, extraData);
}
return true;
}
/**
* @dev transfer token all tokens to a contract address with additional data if the recipient is a contact.
* @param to The address to transfer all to.
* @param extraData The extra data to be passed to the receiving contract.
* @return Whether successful or not.
*/
function transferAllAndCall(address to, bytes extraData)
external
onlyOwnerOrAtState(State.PublicUse)
returns (bool)
{
return transferAndCall(to, m_balances[msg.sender], extraData);
}
/**
* @dev Call ERC677 tokenFallback for ERC677Recipient contract.
* @param to The address of ERC677Recipient.
* @param value Amount of tokens with was sended
* @param data Sended to ERC677Recipient.
* @return Whether contract or not.
*/
function contractFallback(address to, uint value, bytes data)
internal
{
ERC677Recipient recipient = ERC677Recipient(to);
recipient.tokenFallback(msg.sender, value, data);
}
/**
* @dev Check addr if is contract.
* @param addr The address that checking.
* @return Whether contract or not.
*/
function isContract(address addr) internal view returns (bool) {
uint length;
assembly { length := extcodesize(addr) }
return length > 0;
}
///////////////////
// payable Methods
// use withdrawal pattern
// see: http://solidity.readthedocs.io/en/develop/common-patterns.html#withdrawal-from-contracts
// see: https://consensys.github.io/smart-contract-best-practices/known_attacks/
//
/**
* Recived ETH converted to tokens amount for price. sender has max limit for tokens
* amount as m_maxTokensPerAddress - balanceOf(sender). if amount <= max limit
* then transfer amount from this to sender and 95%ETH to bank, 5%ETH to owner.
* else amount > max limit then we calc cost of max limit of tokens,
* store this cost in m_pendingWithdrawals[sender] and m_myDebtInWei and
* transfer max limit of tokens from this to sender and 95% max limit cost to bank
* 5% max limit cost to owner.
*
* @dev Contract receive ETH (payable) from sender and transfer some amount of tokens to him.
*/
function byTokens() public payable atState(State.Sale) {
// check if msg.sender can to by tokens
require(m_balances[msg.sender] < m_maxTokensPerAddress);
// get actual token price and set it
m_tokenPriceInWei = calcTokenPriceInWei();
// check if msg.value has enough for by 1 token
require(msg.value >= m_tokenPriceInWei);
// calc max available tokens for sender
uint256 maxAvailableTokens = m_maxTokensPerAddress.sub(m_balances[msg.sender]);
// convert msg.value(wei) to tokens
uint256 tokensAmount = weiToTokens(msg.value, m_tokenPriceInWei);
if (tokensAmount > maxAvailableTokens) {
// we CANT transfer all tokens amount, ONLY max available tokens
// calc cost in wei of max available tokens
// subtract cost from msg.value and store it as debt for sender
tokensAmount = maxAvailableTokens;
// calc cost
uint256 tokensAmountCostInWei = tokensToWei(tokensAmount, m_tokenPriceInWei);
// calc debt
uint256 debt = msg.value.sub(tokensAmountCostInWei);
// Withdrawal pattern avoid Re-Entrancy (dont use transfer to unknow address)
// update pending withdrawals
m_pendingWithdrawals[msg.sender] = m_pendingWithdrawals[msg.sender].add(debt);
// update my debt
m_myDebtInWei = m_myDebtInWei.add(debt);
}
// transfer tokensAmount tokens form this to sender
// SafeMath.sub will already throw if this condition is not met
m_balances[address(this)] = m_balances[address(this)].sub(tokensAmount);
m_balances[msg.sender] = m_balances[msg.sender].add(tokensAmount);
// we can transfer eth to owner and bank, because we know that they
// dont use Re-Entrancy and other attacks.
// transfer 5% of eht-myDebt to owner
// owner cant be equal address(0) because this function to be accessible
// only in State.Sale but owner can be equal address(0), only in State.PublicUse
// State.Sale not equal State.PublicUse!
m_owner.transfer(this.balance.sub(m_myDebtInWei).mul(uint256(5)).div(uint256(100)));
// transfer 95% of eht-myDebt to bank
// bank cant be equal address(0) see setBank() and PonziToken()
m_bank.transfer(this.balance.sub(m_myDebtInWei));
checkValidityOfBalance(); // this.balance >= m_myDebtInWei
Transfer(address(this), msg.sender, tokensAmount);
TokensSold(tokensAmount, msg.sender, m_tokenPriceInWei);
}
/**
* @dev Sender receive his pending withdrawals(if > 0).
*/
function withdraw() external {
uint amount = m_pendingWithdrawals[msg.sender];
require(amount > 0);
// set zero the pending refund before
// sending to prevent Re-Entrancy
m_pendingWithdrawals[msg.sender] = 0;
m_myDebtInWei = m_myDebtInWei.sub(amount);
msg.sender.transfer(amount);
checkValidityOfBalance(); // this.balance >= m_myDebtInWei
Withdrawal(msg.sender, amount);
}
/**
* @notice http://solidity.readthedocs.io/en/develop/contracts.html#fallback-function
* we dont need recieve ETH always, only in State.Sale from externally accounts.
*
* @dev Fallback func, call byTokens().
*/
function() public payable atState(State.Sale) {
byTokens();
}
////////////////////////
// external view methods
// everyone outside has access
//
/**
* @dev Gets the pending withdrawals of the specified address.
* @param owner The address to query the pending withdrawals of.
* @return An uint256 representing the amount withdrawals owned by the passed address.
*/
function pendingWithdrawals(address owner) external view returns (uint256) {
return m_pendingWithdrawals[owner];
}
/**
* @dev Get contract work state.
* @return Contract work state via string.
*/
function state() external view returns (string stateString) {
if (m_state == State.PreSale) {
stateString = PRE_SALE_STR;
} else if (m_state == State.Sale) {
stateString = SALE_STR;
} else if (m_state == State.PublicUse) {
stateString = PUBLIC_USE_STR;
}
}
/**
* @dev Get price of one token in wei.
* @return Price of one token in wei.
*/
function tokenPriceInWei() public view returns (uint256) {
return calcTokenPriceInWei();
}
/**
* @dev Get address of the bank.
* @return Address of the bank.
*/
function bank() external view returns(address) {
return m_bank;
}
/**
* @dev Get timestamp of first entrance to sale state.
* @return Timestamp of first entrance to sale state.
*/
function firstEntranceToSaleStateUNIX()
external
view
returns(uint256)
{
return m_firstEntranceToSaleStateUNIX;
}
/**
* @dev Get address of the price setter.
* @return Address of the price setter.
*/
function priceSetter() external view returns (address) {
return m_priceSetter;
}
////////////////////
// public methods
// only for owner
//
/**
* @dev Owner do disown.
*/
function disown() external atState(State.PublicUse) onlyOwner() {
delete m_owner;
}
/**
* @dev Set state of contract working.
* @param newState String representation of new state.
*/
function setState(string newState)
external
onlyOwner()
checkAccess()
{
if (keccak256(newState) == keccak256(PRE_SALE_STR)) {
m_state = State.PreSale;
} else if (keccak256(newState) == keccak256(SALE_STR)) {
if (m_firstEntranceToSaleStateUNIX == 0)
m_firstEntranceToSaleStateUNIX = now;
m_state = State.Sale;
} else if (keccak256(newState) == keccak256(PUBLIC_USE_STR)) {
m_state = State.PublicUse;
} else {
// if newState not valid string
revert();
}
StateChanged(msg.sender, m_state);
}
/**
* If token price not fix then actual price
* always will be tokenPriceInWeiForDay(day).
*
* @dev Set price of one token in wei and fix it.
* @param newTokenPriceInWei Price of one token in wei.
*/
function setAndFixTokenPriceInWei(uint256 newTokenPriceInWei)
external
checkAccess()
{
require(msg.sender == m_owner || msg.sender == m_priceSetter);
m_isFixedTokenPrice = true;
m_tokenPriceInWei = newTokenPriceInWei;
PriceChanged(msg.sender, m_tokenPriceInWei, m_isFixedTokenPrice);
}
/**
* If token price is unfixed then actual will be tokenPriceInWeiForDay(day).
*
* @dev Set unfix token price to true.
*/
function unfixTokenPriceInWei()
external
checkAccess()
{
require(msg.sender == m_owner || msg.sender == m_priceSetter);
m_isFixedTokenPrice = false;
PriceChanged(msg.sender, m_tokenPriceInWei, m_isFixedTokenPrice);
}
/**
* @dev Set the PriceSetter address, which has access to set one token price in wei.
* @param newPriceSetter The address of new PriceSetter.
*/
function setPriceSetter(address newPriceSetter)
external
onlyOwner()
checkAccess()
{
m_priceSetter = newPriceSetter;
}
/**
* @dev Set the bank, which receive 95%ETH from tokens sale.
* @param newBank The address of new bank.
*/
function setBank(address newBank)
external
validRecipient(newBank)
onlyOwner()
checkAccess()
{
require(newBank != address(0));
m_bank = newBank;
}
////////////////////////
// internal pure methods
//
/**
* @dev Convert token to wei.
* @param tokensAmount Amout of tokens.
* @param tokenPrice One token price in wei.
* @return weiAmount Result amount of convertation.
*/
function tokensToWei(uint256 tokensAmount, uint256 tokenPrice)
internal
pure
returns(uint256 weiAmount)
{
weiAmount = tokensAmount.mul(tokenPrice);
}
/**
* @dev Conver wei to token.
* @param weiAmount Wei amout.
* @param tokenPrice One token price in wei.
* @return tokensAmount Result amount of convertation.
*/
function weiToTokens(uint256 weiAmount, uint256 tokenPrice)
internal
pure
returns(uint256 tokensAmount)
{
tokensAmount = weiAmount.div(tokenPrice);
}
////////////////////////
// private view methods
//
/**
* @dev Get actual token price.
* @return price One token price in wei.
*/
function calcTokenPriceInWei()
private
view
returns(uint256 price)
{
if (m_isFixedTokenPrice) {
// price is fixed, return current val
price = m_tokenPriceInWei;
} else {
// price not fixed, we must to calc price
if (m_firstEntranceToSaleStateUNIX == 0) {
// if contract dont enter to SaleState then price = 0
price = 0;
} else {
// calculate day after first Entrance To Sale State
uint256 day = now.sub(m_firstEntranceToSaleStateUNIX).div(1 days);
// use special formula for calcutation price
price = tokenPriceInWeiForDay(day);
}
}
}
/**
* @dev Get token price for specific day after starting sale tokens.
* @param day Secific day.
* @return price One token price in wei for specific day.
*/
function tokenPriceInWeiForDay(uint256 day)
private
view
returns(uint256 price)
{
// day 1: price 1*10^(decimals) TOKEN = 0.001 ETH
// price 1 TOKEN = 1 * 10^(-3) ETH / 10^(decimals), in ETH
// convert to wei:
// price 1 TOKEN = 1 * 10^(-3) * wei * 10^(-decimals)
// price 1 TOKEN = 1 * 10^(-3) * 10^(18) * 10^(-decimals)
// price 1 TOKEN = 1 * 10^(15) * 10^(-decimals), in WEI
// day 2: price 1*10^(decimals) TOKEN = 0.002 ETH;
// price 1 TOKEN = 2 * 10^(15) * 10^(-decimals), in WEI
// ...
// day 12: price 1*10^(decimals) TOKEN = 0.012 ETH;
// price 1 TOKEN = 12 * 10^(15) * 10^(-decimals), in WEI
// day >12: price 1*10^(decimals) TOKEN = 0.012 ETH;
// price 1 TOKEN = 12 * 10^(15) * 10^(-decimals), in WEI
// from 0 to 11 - sum is 12 days
if (day <= 11)
price = day.add(1);// because from >0h to <24h after start day will be 0,
else // but for calc price it must be 1;
price = 12;
// convert to WEI
price = price.mul(uint256(10**15)).div(10**uint256(m_decimals));
}
/**
* @notice It is always must be true, for correct withdrawals and receivers ETH.
*
* Check if this.balance >= m_myDebtInWei.
*/
function checkValidityOfBalance() private view {
// assertion is not a strict equality of the balance because the contract
// can be forcibly sent ether without going through the byTokens() func.
// selfdestruct does not trigger a contract's fallback function.
// see: http://solidity.readthedocs.io/en/develop/contracts.html#fallback-function
assert(this.balance >= m_myDebtInWei);
}
}
|
The symbol of the token. return The symbol of the token./
|
function symbol() public view returns (string) {
return m_symbol;
}
| 957,243
|
./partial_match/42/0xf97F97325d0aCfBFe1eeb2237B3de70aFA03664a/sources/SimpleBridgeKitty.sol
|
we can create promo kittens, up to a limit. _genes the encoded genes of the kitten to be created, any value is accepted _owner the future owner of the created kittens.
|
function createKitty(uint256 _genes, address _owner) external onlyOwner {
address kittyOwner = _owner;
if (kittyOwner == address(0)) {
kittyOwner = bridge;
}
_createKitty(tokenId, false, 0, 0, 0, uint64(now), 0, 0, 0, _genes, kittyOwner);
}
| 3,308,613
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, 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;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
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'
// solhint-disable-next-line max-line-length
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).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_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
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
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);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.6.0 <0.8.0;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import '../utils/ERC20Recovery.sol';
import './interfaces/ICFolioFarm.sol';
import './interfaces/IController.sol';
import './interfaces/IFarm.sol';
/**
* @notice Farm is owned by a CFolio contract.
*
* All state modifing calls are only allowed from this owner.
*/
contract CFolioFarm is IFarm, ICFolioFarm, Ownable, ERC20Recovery {
using SafeMath for uint256;
using SafeERC20 for IERC20;
//////////////////////////////////////////////////////////////////////////////
// State
//////////////////////////////////////////////////////////////////////////////
uint256 public override periodFinish = 0;
uint256 public rewardRate = 0;
uint256 public rewardsDuration = 14 days;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored;
uint256 private availableRewards;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) public rewards;
// Unique name of this farm instance, used in controller
string private _farmName;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
// The address of the controller
IController public override controller;
//////////////////////////////////////////////////////////////////////////////
// Events
//////////////////////////////////////////////////////////////////////////////
event RewardAdded(uint256 reward);
event AssetAdded(address indexed user, uint256 amount, uint256 totalAmount);
event AssetRemoved(address indexed user, uint256 amount, uint256 totalAmount);
event ShareAdded(address indexed user, uint256 amount);
event ShareRemoved(address indexed user, uint256 amount);
event RewardPaid(
address indexed account,
address indexed user,
uint256 reward
);
event RewardsDurationUpdated(uint256 newDuration);
event ControllerChanged(address newController);
//////////////////////////////////////////////////////////////////////////////
// Modifiers
//////////////////////////////////////////////////////////////////////////////
modifier onlyController {
require(_msgSender() == address(controller), 'not controller');
_;
}
modifier updateReward(address account) {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
//////////////////////////////////////////////////////////////////////////////
// Initialization
//////////////////////////////////////////////////////////////////////////////
constructor(
address _owner,
string memory _name,
address _controller
) {
// Validate parameters
require(_owner != address(0), 'Invalid owner');
require(_controller != address(0), 'Invalid controller');
// Initialize {Ownable}
transferOwnership(_owner);
// Initialize state
_farmName = _name;
controller = IController(_controller);
}
//////////////////////////////////////////////////////////////////////////////
// Views
//////////////////////////////////////////////////////////////////////////////
function farmName() external view override returns (string memory) {
return _farmName;
}
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view override returns (uint256) {
return _balances[account];
}
function lastTimeRewardApplicable() public view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp < periodFinish ? block.timestamp : periodFinish;
}
function rewardPerToken() public view returns (uint256) {
if (_totalSupply == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(1e18)
.div(_totalSupply)
);
}
function earned(address account) public view returns (uint256) {
return
_balances[account]
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
function getRewardForDuration() external view returns (uint256) {
return rewardRate.mul(rewardsDuration);
}
function getUIData(address account)
external
view
override
returns (uint256[5] memory)
{
uint256[5] memory result =
[
_totalSupply,
_balances[account],
rewardsDuration,
rewardRate.mul(rewardsDuration),
earned(account)
];
return result;
}
//////////////////////////////////////////////////////////////////////////////
// Mutators
//////////////////////////////////////////////////////////////////////////////
function addAssets(address account, uint256 amount)
external
override
onlyOwner
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot add 0');
// Update state
_balances[account] = _balances[account].add(amount);
// Dispatch event
emit AssetAdded(account, amount, _balances[account]);
}
function removeAssets(address account, uint256 amount)
external
override
onlyOwner
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot remove 0');
// Update state
_balances[account] = _balances[account].sub(amount);
// Dispatch event
emit AssetRemoved(account, amount, _balances[account]);
}
function addShares(address account, uint256 amount)
external
override
onlyOwner
updateReward(account)
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot add 0');
// Update state
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
// Notify controller
controller.onDeposit(amount);
// Dispatch event
emit ShareAdded(account, amount);
}
function removeShares(address account, uint256 amount)
public
override
onlyOwner
updateReward(account)
{
// Validate parameters
require(amount > 0, 'CFolioFarm: Cannot remove 0');
// Update state
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
// Notify controller
controller.onWithdraw(amount);
// Dispatch event
emit ShareRemoved(account, amount);
}
function getReward(address account, address rewardRecipient)
public
override
onlyOwner
updateReward(account)
{
// Load state
uint256 reward = rewards[account];
if (reward > 0) {
// Update state
rewards[account] = 0;
availableRewards = availableRewards.sub(reward);
// Notify controller
controller.payOutRewards(rewardRecipient, reward);
// Dispatch event
emit RewardPaid(account, rewardRecipient, reward);
}
}
function exit(address account, address rewardRecipient)
external
override
onlyOwner
{
removeShares(account, _balances[account]);
getReward(account, rewardRecipient);
}
//////////////////////////////////////////////////////////////////////////////
// Restricted functions
//////////////////////////////////////////////////////////////////////////////
function setController(address newController)
external
override
onlyController
{
// Update state
controller = IController(newController);
// Dispatch event
emit ControllerChanged(newController);
}
function notifyRewardAmount(uint256 reward)
external
override
onlyController
updateReward(address(0))
{
// Update state
// solhint-disable-next-line not-rely-on-time
if (block.timestamp >= periodFinish) {
rewardRate = reward.div(rewardsDuration);
} else {
// solhint-disable-next-line not-rely-on-time
uint256 remaining = periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(rewardRate);
rewardRate = reward.add(leftover).div(rewardsDuration);
}
availableRewards = availableRewards.add(reward);
// Validate state
//
// Ensure the provided reward amount is not more than the balance in the
// contract.
//
// This keeps the reward rate in the right range, preventing overflows due
// to very high values of rewardRate in the earned and rewardsPerToken
// functions.
//
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
//
require(
rewardRate <= availableRewards.div(rewardsDuration),
'Provided reward too high'
);
// Update state
// solhint-disable-next-line not-rely-on-time
lastUpdateTime = block.timestamp;
// solhint-disable-next-line not-rely-on-time
periodFinish = block.timestamp.add(rewardsDuration);
// Dispatch event
emit RewardAdded(reward);
}
/**
* @dev We don't have any rebalancing here
*/
// solhint-disable-next-line no-empty-blocks
function rebalance() external override onlyController {}
/**
* @dev Added to support recovering LP Rewards from other systems to be
* distributed to holders
*/
function recoverERC20(
address recipient,
address tokenAddress,
uint256 tokenAmount
) external onlyController {
// Call ancestor
_recoverERC20(recipient, tokenAddress, tokenAmount);
}
function setRewardsDuration(uint256 _rewardsDuration)
external
override
onlyController
{
// Validate state
require(
// solhint-disable-next-line not-rely-on-time
periodFinish == 0 || block.timestamp > periodFinish,
'Reward period not finished'
);
// Update state
rewardsDuration = _rewardsDuration;
// Dispatch event
emit RewardsDurationUpdated(rewardsDuration);
}
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.6.0 <0.8.0;
/**
* @title ICFolioFarm
*
* @dev ICFolioFarm is the business logic interface to c-folio farms.
*/
interface ICFolioFarm {
/**
* @dev Return invested balance of account
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Return total, balances[account], rewardDuration, rewardForDuration, earned[account]
*/
function getUIData(address account) external view returns (uint256[5] memory);
/**
* @dev Increase amount of non-rewarded asset
*/
function addAssets(address account, uint256 amount) external;
/**
* @dev Remove amount of previous added assets
*/
function removeAssets(address account, uint256 amount) external;
/**
* @dev Increase amount of shares and earn rewards
*/
function addShares(address account, uint256 amount) external;
/**
* @dev Remove amount of previous added shares, rewards will not be claimed
*/
function removeShares(address account, uint256 amount) external;
/**
* @dev Claim rewards harvested during reward time
*/
function getReward(address account, address rewardRecipient) external;
/**
* @dev Remove all shares and call getRewards() in a single step
*/
function exit(address account, address rewardRecipient) external;
}
/**
* @title ICFolioFarmOwnable
*/
interface ICFolioFarmOwnable is ICFolioFarm {
/**
* @dev Transfer ownership
*/
function transferOwnership(address newOwner) external;
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.6.0 <0.8.0;
interface IController {
/**
* @dev Used to control fees and accessibility instead having an implementation
* in each farm contract
*
* Deposit is only allowed if farm is open and not not paused. Must revert on
* failure.
*
* @param amount Number of tokens the user wants to deposit
*
* @return fee The deposit fee (1e18 factor) on success
*/
function onDeposit(uint256 amount) external view returns (uint256 fee);
/**
* @dev Used to control fees and accessibility instead having an
* implementation in each farm contract
*
* Withdraw is only allowed if farm is not paused. Must revert on failure
*
* @param amount Number of tokens the user wants to withdraw
*
* @return fee The withdrawal fee (1e18 factor) on success
*/
function onWithdraw(uint256 amount) external view returns (uint256 fee);
/**
* @dev Distribute rewards to sender and fee to internal contracts
*/
function payOutRewards(address recipient, uint256 amount) external;
}
/*
* Copyright (C) 2020-2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.6.0 <0.8.0;
import './IController.sol';
interface IFarm {
/**
* @dev Return the farm's controller
*/
function controller() external view returns (IController);
/**
* @dev Return a unique, case-sensitive farm name
*/
function farmName() external view returns (string memory);
/**
* @dev Return when reward period is finished (UTC timestamp)
*/
function periodFinish() external view returns (uint256);
/**
* @dev Sets a new controller, can only called by current controller
*/
function setController(address newController) external;
/**
* @dev This function must be called initially and close at the time the
* reward period ends
*/
function notifyRewardAmount(uint256 reward) external;
/**
* @dev Set the duration of farm rewards, to continue rewards,
* notifyRewardAmount() has to called for the next period
*/
function setRewardsDuration(uint256 _rewardsDuration) external;
/**
* @dev Rebalance strategies (if implemented)
*/
function rebalance() external;
}
/*
* Copyright (C) 2021 The Wolfpack
* This file is part of wolves.finance - https://github.com/wolvesofwallstreet/wolves.finance
*
* SPDX-License-Identifier: Apache-2.0
* See the file LICENSES/README.md for more information.
*/
pragma solidity >=0.7.0 <0.8.0;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
contract ERC20Recovery {
using SafeERC20 for IERC20;
//////////////////////////////////////////////////////////////////////////////
// Events
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Fired when a recipient receives recovered ERC-20 tokens
*
* @param recipient The target recipient receving the recovered coins
* @param tokenAddress The address of the ERC-20 token
* @param tokenAmount The amount of the token being recovered
*/
event Recovered(
address indexed recipient,
address indexed tokenAddress,
uint256 tokenAmount
);
//////////////////////////////////////////////////////////////////////////////
// Internal interface
//////////////////////////////////////////////////////////////////////////////
/**
* @dev Recover ERC20 token from contract which have been transfered
* either by accident or via airdrop
*
* Proper access must be verified. All tokens used by the system must
* be blocked from recovery.
*
* @param recipient The target recipient of the recovered coins
* @param tokenAddress The address of the ERC-20 token
* @param tokenAmount The amount of the token to recover
*/
function _recoverERC20(
address recipient,
address tokenAddress,
uint256 tokenAmount
) internal {
// Validate parameters
require(recipient != address(0), "Can't recover to address 0");
// Update state
IERC20(tokenAddress).safeTransfer(recipient, tokenAmount);
// Dispatch event
emit Recovered(recipient, tokenAddress, tokenAmount);
}
}
|
Validate parameters Update state Dispatch event
|
function addAssets(address account, uint256 amount)
external
override
onlyOwner
{
require(amount > 0, 'CFolioFarm: Cannot add 0');
_balances[account] = _balances[account].add(amount);
emit AssetAdded(account, amount, _balances[account]);
}
| 1,670,715
|
./full_match/7700/0xd5609cD0e1675331E4Fb1d43207C8d9D83AAb17C/sources/contracts/bridge/SynapseBridge.sol
|
Nodes call this function to mint a SynERC20 (or any asset that the bridge is given minter access to). This is called by the nodes after a TokenDeposit event is emitted. This means the SynapseBridge.sol contract must have minter access to the token attempting to be minted to address on other chain to redeem underlying assets to token ERC20 compatible token to deposit into the bridge amount Amount in native token decimals to transfer cross-chain post-fees fee Amount in native token decimals to save to the contract as fees kappa kappa/
|
function mint(
address payable to,
IERC20Mintable token,
uint256 amount,
uint256 fee,
bytes32 kappa
) external nonReentrant whenNotPaused {
require(hasRole(NODEGROUP_ROLE, msg.sender), "Caller is not a node group");
require(amount > fee, "Amount must be greater than fee");
require(!kappaMap[kappa], "Kappa is already present");
kappaMap[kappa] = true;
fees[address(token)] = fees[address(token)].add(fee);
emit TokenMint(to, token, amount.sub(fee), fee, kappa);
token.mint(address(this), amount);
IERC20(token).safeTransfer(to, amount.sub(fee));
if (chainGasAmount != 0 && address(this).balance > chainGasAmount) {
to.call.value(chainGasAmount)("");
}
}
| 4,656,257
|
./full_match/288/0x591091bA69FC7aBFAD8649668F727766dD2a9a76/sources/contracts/Comptroller.sol
|
Checks if the account should be allowed to transfer tokens in the given market cToken The market to verify the transfer against src The account which sources the tokens dst The account which receives the tokens transferTokens The number of cTokens to transfer return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)/ Pausing is a very serious situation - we revert to sound the alarms Currently the only consideration is whether or not the src is allowed to redeem this many tokens
|
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint) {
require(!transferGuardianPaused, "transfer is paused");
uint allowed = redeemAllowedInternal(cToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
uint supplyTokens = CToken(cToken).totalSupply();
uint srcTokens = CToken(cToken).balanceOf(src);
uint dstTokens = CToken(cToken).balanceOf(dst);
distributeSupplierComp(cToken, src, srcTokens);
distributeSupplierComp(cToken, dst, dstTokens);
Exp memory exchangeRate = Exp({
mantissa: CToken(cToken).exchangeRateStored()
});
supplyTokens = mul_ScalarTruncate(exchangeRate, supplyTokens);
srcTokens = mul_ScalarTruncate(exchangeRate, srcTokens);
dstTokens = mul_ScalarTruncate(exchangeRate, dstTokens);
getIncentivesController()
.handleAction(src, cToken, supplyTokens, srcTokens);
getIncentivesController()
.handleAction(dst, cToken, supplyTokens, dstTokens);
return uint(Error.NO_ERROR);
}
| 7,105,010
|
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./IBondingCurve.sol";
import "../refs/OracleRef.sol";
import "../pcv/PCVSplitter.sol";
import "../utils/Timed.sol";
/// @title an abstract bonding curve for purchasing RUSD
/// @author Ring Protocol
abstract contract BondingCurve is IBondingCurve, OracleRef, PCVSplitter, Timed {
using Decimal for Decimal.D256;
using SafeMathCopy for uint256;
/// @notice the total amount of RUSD purchased on bonding curve. RUSD_b from the whitepaper
uint256 public override totalPurchased; // RUSD_b for this curve
/// @notice the buffer applied on top of the peg purchase price
uint256 public override buffer = 50;
uint256 public constant BUFFER_GRANULARITY = 10_000;
/// @notice amount of RUSD paid for allocation when incentivized
uint256 public override incentiveAmount;
/// @notice constructor
/// @param _core Ring Core to reference
/// @param _pcvDeposits the PCV Deposits for the PCVSplitter
/// @param _ratios the ratios for the PCVSplitter
/// @param _oracle the UniswapOracle to reference
/// @param _duration the duration between incentivizing allocations
/// @param _incentive the amount rewarded to the caller of an allocation
constructor(
address _core,
address[] memory _pcvDeposits,
uint256[] memory _ratios,
address _oracle,
uint256 _duration,
uint256 _incentive
)
OracleRef(_core, _oracle)
PCVSplitter(_pcvDeposits, _ratios)
Timed(_duration)
{
incentiveAmount = _incentive;
_initTimed();
}
/// @notice sets the bonding curve price buffer
function setBuffer(uint256 _buffer) external override onlyGovernor {
require(
_buffer < BUFFER_GRANULARITY,
"BondingCurve: Buffer exceeds or matches granularity"
);
buffer = _buffer;
emit BufferUpdate(_buffer);
}
/// @notice sets the allocate incentive amount
function setIncentiveAmount(uint256 _incentiveAmount) external override onlyGovernor {
incentiveAmount = _incentiveAmount;
emit IncentiveAmountUpdate(_incentiveAmount);
}
/// @notice sets the allocate incentive frequency
function setIncentiveFrequency(uint256 _frequency) external override onlyGovernor {
_setDuration(_frequency);
}
/// @notice sets the allocation of incoming PCV
function setAllocation(
address[] calldata allocations,
uint256[] calldata ratios
) external override onlyGovernor {
_setAllocation(allocations, ratios);
}
/// @notice batch allocate held PCV
function allocate() external override whenNotPaused {
require((!Address.isContract(msg.sender)), "BondingCurve: Caller is a contract");
uint256 amount = getTotalPCVHeld();
require(amount != 0, "BondingCurve: No PCV held");
_allocate(amount);
_incentivize();
emit Allocate(msg.sender, amount);
}
/// @notice return current instantaneous bonding curve price
/// @return price reported as RUSD per X with X being the underlying asset
function getCurrentPrice()
external
view
override
returns (Decimal.D256 memory)
{
return peg().mul(_getBufferMultiplier());
}
/// @notice return amount of RUSD received after a bonding curve purchase
/// @param amountIn the amount of underlying used to purchase
/// @return amountOut the amount of RUSD received
function getAmountOut(uint256 amountIn)
public
view
override
returns (uint256 amountOut)
{
uint256 adjustedAmount = _getAdjustedAmount(amountIn);
amountOut = _getBufferAdjustedAmount(adjustedAmount);
return amountOut;
}
/// @notice return the average price of a transaction along bonding curve
/// @param amountIn the amount of underlying used to purchase
/// @return price reported as USD per RUSD
function getAverageUSDPrice(uint256 amountIn)
external
view
override
returns (Decimal.D256 memory)
{
uint256 adjustedAmount = _getAdjustedAmount(amountIn);
uint256 amountOut = getAmountOut(amountIn);
return Decimal.ratio(adjustedAmount, amountOut);
}
/// @notice the amount of PCV held in contract and ready to be allocated
function getTotalPCVHeld() public view virtual override returns (uint256);
/// @notice multiplies amount in by the peg to convert to RUSD
function _getAdjustedAmount(uint256 amountIn)
internal
view
returns (uint256)
{
return peg().mul(amountIn).asUint256();
}
/// @notice mint RUSD and send to buyer destination
function _purchase(uint256 amountIn, address to)
internal
returns (uint256 amountOut)
{
amountOut = getAmountOut(amountIn);
_incrementTotalPurchased(amountOut);
rusd().mint(to, amountOut);
emit Purchase(to, amountIn, amountOut);
return amountOut;
}
function _incrementTotalPurchased(uint256 amount) internal {
totalPurchased = totalPurchased.add(amount);
}
/// @notice if window has passed, reward caller and reset window
function _incentivize() internal virtual {
if (isTimeEnded()) {
_initTimed(); // reset window
rusd().mint(msg.sender, incentiveAmount);
}
}
/// @notice returns the buffer on the bonding curve price
function _getBufferMultiplier() internal view returns (Decimal.D256 memory) {
uint256 granularity = BUFFER_GRANULARITY;
// uses granularity - buffer (i.e. 1-b) instead of 1+b because the peg is inverted
return Decimal.ratio(granularity - buffer, granularity);
}
function _getBufferAdjustedAmount(uint256 amountIn)
internal
view
returns (uint256)
{
return _getBufferMultiplier().mul(amountIn).asUint256();
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./BondingCurve.sol";
import "../pcv/IPCVDeposit.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
/// @title a square root growth bonding curve for purchasing RUSD with ETH
/// @author Ring Protocol
contract ERC20BondingCurve is BondingCurve {
address public immutable tokenAddress;
constructor(
address core,
address[] memory pcvDeposits,
uint256[] memory ratios,
address oracle,
uint256 duration,
uint256 incentive,
address _tokenAddress
)
BondingCurve(
core,
pcvDeposits,
ratios,
oracle,
duration,
incentive
)
{
tokenAddress = _tokenAddress;
}
/// @notice purchase RUSD for underlying tokens
/// @param to address to receive RUSD
/// @param amountIn amount of underlying tokens input
/// @return amountOut amount of RUSD received
function purchase(address to, uint256 amountIn)
external
payable
virtual
override
whenNotPaused
returns (uint256 amountOut)
{
// safeTransferFrom(address token, address from, address to, uint value)
TransferHelper.safeTransferFrom(tokenAddress, msg.sender, address(this), amountIn);
return _purchase(amountIn, to);
}
function getTotalPCVHeld() public view virtual override returns (uint256) {
return IERC20(tokenAddress).balanceOf(address(this));
}
function _allocateSingle(uint256 amount, address pcvDeposit)
internal
virtual
override
{
// safeTransfer(address token, address to, uint value)
TransferHelper.safeTransfer(tokenAddress, pcvDeposit, amount);
IPCVDeposit(pcvDeposit).deposit();
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "../external/Decimal.sol";
interface IBondingCurve {
// ----------- Events -----------
event BufferUpdate(uint256 _buffer);
event IncentiveAmountUpdate(uint256 _incentiveAmount);
event Purchase(address indexed _to, uint256 _amountIn, uint256 _amountOut);
event Allocate(address indexed _caller, uint256 _amount);
// ----------- State changing Api -----------
function purchase(address to, uint256 amountIn)
external
payable
returns (uint256 amountOut);
function allocate() external;
// ----------- Governor only state changing api -----------
function setBuffer(uint256 _buffer) external;
function setAllocation(
address[] calldata pcvDeposits,
uint256[] calldata ratios
) external;
function setIncentiveAmount(uint256 _incentiveAmount) external;
function setIncentiveFrequency(uint256 _frequency) external;
// ----------- Getters -----------
function getCurrentPrice() external view returns (Decimal.D256 memory);
function getAverageUSDPrice(uint256 amountIn)
external
view
returns (Decimal.D256 memory);
function getAmountOut(uint256 amountIn)
external
view
returns (uint256 amountOut);
function buffer() external view returns (uint256);
function totalPurchased() external view returns (uint256);
function getTotalPCVHeld() external view returns (uint256);
function incentiveAmount() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "./IPermissions.sol";
import "../token/IRusd.sol";
/// @title Core Interface
/// @author Ring Protocol
interface ICore is IPermissions {
// ----------- Events -----------
event RusdUpdate(address indexed _rusd);
event RingUpdate(address indexed _ring);
event GenesisGroupUpdate(address indexed _genesisGroup);
event RingAllocation(address indexed _to, uint256 _amount);
event GenesisPeriodComplete(uint256 _timestamp);
// ----------- Governor only state changing api -----------
function init() external;
// ----------- Governor only state changing api -----------
function setRusd(address token) external;
function setRing(address token) external;
function setGenesisGroup(address _genesisGroup) external;
function allocateRing(address to, uint256 amount) external;
// ----------- Genesis Group only state changing api -----------
function completeGenesisGroup() external;
// ----------- Getters -----------
function rusd() external view returns (IRusd);
function ring() external view returns (IERC20);
function genesisGroup() external view returns (address);
function hasGenesisGroupCompleted() external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
/// @title Permissions interface
/// @author Ring Protocol
interface IPermissions {
// ----------- Governor only state changing api -----------
function createRole(bytes32 role, bytes32 adminRole) external;
function grantMinter(address minter) external;
function grantBurner(address burner) external;
function grantPCVController(address pcvController) external;
function grantGovernor(address governor) external;
function grantGuardian(address guardian) external;
function revokeMinter(address minter) external;
function revokeBurner(address burner) external;
function revokePCVController(address pcvController) external;
function revokeGovernor(address governor) external;
function revokeGuardian(address guardian) external;
// ----------- Revoker only state changing api -----------
function revokeOverride(bytes32 role, address account) external;
// ----------- Getters -----------
function isBurner(address _address) external view returns (bool);
function isMinter(address _address) external view returns (bool);
function isGovernor(address _address) external view returns (bool);
function isGuardian(address _address) external view returns (bool);
function isPCVController(address _address) external view returns (bool);
}
/*
Copyright 2019 dYdX Trading Inc.
Copyright 2020 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./SafeMathCopy.sol";
/**
* @title Decimal
* @author dYdX
*
* Library that defines a fixed-point number with 18 decimal places.
*/
library Decimal {
using SafeMathCopy for uint256;
// ============ Constants ============
uint256 private constant BASE = 10**18;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Static Functions ============
function zero()
internal
pure
returns (D256 memory)
{
return D256({ value: 0 });
}
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
function from(
uint256 a
)
internal
pure
returns (D256 memory)
{
return D256({ value: a.mul(BASE) });
}
function ratio(
uint256 a,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(a, BASE, b) });
}
// ============ Self Functions ============
function add(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE), reason) });
}
function mul(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.mul(b) });
}
function div(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b) });
}
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
D256 memory temp = D256({ value: self.value });
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
function add(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.value) });
}
function sub(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value) });
}
function sub(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value, reason) });
}
function mul(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, b.value, BASE) });
}
function div(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value) });
}
function equals(D256 memory self, D256 memory b) internal pure returns (bool) {
return self.value == b.value;
}
function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 2;
}
function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 0;
}
function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) > 0;
}
function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) < 2;
}
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ Core Methods ============
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
function compareTo(
D256 memory a,
D256 memory b
)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathCopy { // To avoid namespace collision between openzeppelin safemath and uniswap safemath
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "../external/Decimal.sol";
/// @title generic oracle interface for Ring Protocol
/// @author Ring Protocol
interface IOracle {
// ----------- Getters -----------
function read() external view returns (Decimal.D256 memory, bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title a PCV Deposit interface
/// @author Ring Protocol
interface IPCVDeposit {
// ----------- Events -----------
event Deposit(address indexed _from, uint256 _amount);
event Collect(address indexed _from, uint256 _amount0, uint256 _amount1);
event Withdrawal(
address indexed _caller,
address indexed _to,
uint256 _amount
);
// ----------- State changing api -----------
function deposit() external payable;
function collect() external returns (uint256 amount0, uint256 amount1);
// ----------- PCV Controller only state changing api -----------
function withdraw(address to, uint256 amount) external;
function burnAndReset(uint24 _fee, int24 _tickLower, int24 _tickUpper) external;
// ----------- Getters -----------
function fee() external view returns (uint24);
function tickLower() external view returns (int24);
function tickUpper() external view returns (int24);
function totalLiquidity() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "../external/SafeMathCopy.sol";
/// @title abstract contract for splitting PCV into different deposits
/// @author Ring Protocol
abstract contract PCVSplitter {
using SafeMathCopy for uint256;
/// @notice total allocation allowed representing 100%
uint256 public constant ALLOCATION_GRANULARITY = 10_000;
uint256[] private ratios;
address[] private pcvDeposits;
event AllocationUpdate(address[] _pcvDeposits, uint256[] _ratios);
/// @notice PCVSplitter constructor
/// @param _pcvDeposits list of PCV Deposits to split to
/// @param _ratios ratios for splitting PCV Deposit allocations
constructor(address[] memory _pcvDeposits, uint256[] memory _ratios) {
_setAllocation(_pcvDeposits, _ratios);
}
/// @notice make sure an allocation has matching lengths and totals the ALLOCATION_GRANULARITY
/// @param _pcvDeposits new list of pcv deposits to send to
/// @param _ratios new ratios corresponding to the PCV deposits
/// @return true if it is a valid allocation
function checkAllocation(
address[] memory _pcvDeposits,
uint256[] memory _ratios
) public pure returns (bool) {
require(
_pcvDeposits.length == _ratios.length,
"PCVSplitter: PCV Deposits and ratios are different lengths"
);
uint256 total;
for (uint256 i; i < _ratios.length; i++) {
total = total.add(_ratios[i]);
}
require(
total == ALLOCATION_GRANULARITY,
"PCVSplitter: ratios do not total 100%"
);
return true;
}
/// @notice gets the pcvDeposits and ratios of the splitter
function getAllocation()
public
view
returns (address[] memory, uint256[] memory)
{
return (pcvDeposits, ratios);
}
/// @notice distribute funds to single PCV deposit
/// @param amount amount of funds to send
/// @param pcvDeposit the pcv deposit to send funds
function _allocateSingle(uint256 amount, address pcvDeposit)
internal
virtual;
/// @notice sets a new allocation for the splitter
/// @param _pcvDeposits new list of pcv deposits to send to
/// @param _ratios new ratios corresponding to the PCV deposits. Must total ALLOCATION_GRANULARITY
function _setAllocation(
address[] memory _pcvDeposits,
uint256[] memory _ratios
) internal {
checkAllocation(_pcvDeposits, _ratios);
pcvDeposits = _pcvDeposits;
ratios = _ratios;
emit AllocationUpdate(_pcvDeposits, _ratios);
}
/// @notice distribute funds to all pcv deposits at specified allocation ratios
/// @param total amount of funds to send
function _allocate(uint256 total) internal {
uint256 granularity = ALLOCATION_GRANULARITY;
for (uint256 i; i < ratios.length; i++) {
uint256 amount = total.mul(ratios[i]) / granularity;
_allocateSingle(amount, pcvDeposits[i]);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./ICoreRef.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/// @title A Reference to Core
/// @author Ring Protocol
/// @notice defines some modifiers and utilities around interacting with Core
abstract contract CoreRef is ICoreRef, Pausable {
ICore private _core;
/// @notice CoreRef constructor
/// @param newCore Ring Core to reference
constructor(address newCore) {
_core = ICore(newCore);
}
modifier ifMinterSelf() {
if (_core.isMinter(address(this))) {
_;
}
}
modifier ifBurnerSelf() {
if (_core.isBurner(address(this))) {
_;
}
}
modifier onlyMinter() {
require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter");
_;
}
modifier onlyBurner() {
require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner");
_;
}
modifier onlyPCVController() {
require(
_core.isPCVController(msg.sender),
"CoreRef: Caller is not a PCV controller"
);
_;
}
modifier onlyGovernor() {
require(
_core.isGovernor(msg.sender),
"CoreRef: Caller is not a governor"
);
_;
}
modifier onlyGuardianOrGovernor() {
require(
_core.isGovernor(msg.sender) ||
_core.isGuardian(msg.sender),
"CoreRef: Caller is not a guardian or governor"
);
_;
}
modifier onlyRusd() {
require(msg.sender == address(rusd()), "CoreRef: Caller is not RUSD");
_;
}
modifier onlyGenesisGroup() {
require(
msg.sender == _core.genesisGroup(),
"CoreRef: Caller is not GenesisGroup"
);
_;
}
modifier nonContract() {
require(!Address.isContract(msg.sender), "CoreRef: Caller is a contract");
_;
}
/// @notice set new Core reference address
/// @param _newCore the new core address
function setCore(address _newCore) external override onlyGovernor {
_core = ICore(_newCore);
emit CoreUpdate(_newCore);
}
/// @notice set pausable methods to paused
function pause() public override onlyGuardianOrGovernor {
_pause();
}
/// @notice set pausable methods to unpaused
function unpause() public override onlyGuardianOrGovernor {
_unpause();
}
/// @notice address of the Core contract referenced
/// @return ICore implementation address
function core() public view override returns (ICore) {
return _core;
}
/// @notice address of the Rusd contract referenced by Core
/// @return IRusd implementation address
function rusd() public view override returns (IRusd) {
return _core.rusd();
}
/// @notice address of the Ring contract referenced by Core
/// @return IERC20 implementation address
function ring() public view override returns (IERC20) {
return _core.ring();
}
/// @notice rusd balance of contract
/// @return rusd amount held
function rusdBalance() public view override returns (uint256) {
return rusd().balanceOf(address(this));
}
/// @notice ring balance of contract
/// @return ring amount held
function ringBalance() public view override returns (uint256) {
return ring().balanceOf(address(this));
}
function _burnRusdHeld() internal {
rusd().burn(rusdBalance());
}
function _mintRusd(uint256 amount) internal {
rusd().mint(address(this), amount);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "../core/ICore.sol";
/// @title CoreRef interface
/// @author Ring Protocol
interface ICoreRef {
// ----------- Events -----------
event CoreUpdate(address indexed _core);
// ----------- Governor only state changing api -----------
function setCore(address _newCore) external;
function pause() external;
function unpause() external;
// ----------- Getters -----------
function core() external view returns (ICore);
function rusd() external view returns (IRusd);
function ring() external view returns (IERC20);
function rusdBalance() external view returns (uint256);
function ringBalance() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "../oracle/IOracle.sol";
/// @title OracleRef interface
/// @author Ring Protocol
interface IOracleRef {
// ----------- Events -----------
event OracleUpdate(address indexed _oracle);
// ----------- Governor only state changing API -----------
function setOracle(address _oracle) external;
// ----------- Getters -----------
function oracle() external view returns (IOracle);
function peg() external view returns (Decimal.D256 memory);
function invert(Decimal.D256 calldata price)
external
pure
returns (Decimal.D256 memory);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./IOracleRef.sol";
import "./CoreRef.sol";
/// @title Reference to an Oracle
/// @author Ring Protocol
/// @notice defines some utilities around interacting with the referenced oracle
abstract contract OracleRef is IOracleRef, CoreRef {
using Decimal for Decimal.D256;
/// @notice the oracle reference by the contract
IOracle public override oracle;
/// @notice OracleRef constructor
/// @param _core Ring Core to reference
/// @param _oracle oracle to reference
constructor(address _core, address _oracle) CoreRef(_core) {
_setOracle(_oracle);
}
/// @notice sets the referenced oracle
/// @param _oracle the new oracle to reference
function setOracle(address _oracle) external override onlyGovernor {
_setOracle(_oracle);
}
/// @notice invert a peg price
/// @param price the peg price to invert
/// @return the inverted peg as a Decimal
/// @dev the inverted peg would be X per RUSD
function invert(Decimal.D256 memory price)
public
pure
override
returns (Decimal.D256 memory)
{
return Decimal.one().div(price);
}
/// @notice the peg price of the referenced oracle
/// @return the peg as a Decimal
/// @dev the peg is defined as RUSD per X with X being ETH, dollars, etc
function peg() public view override returns (Decimal.D256 memory) {
(Decimal.D256 memory _peg, bool valid) = oracle.read();
require(valid, "OracleRef: oracle invalid");
return _peg;
}
function _setOracle(address _oracle) internal {
oracle = IOracle(_oracle);
emit OracleUpdate(_oracle);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title RUSD stablecoin interface
/// @author Ring Protocol
interface IRusd is IERC20 {
// ----------- Events -----------
event Minting(
address indexed _to,
address indexed _minter,
uint256 _amount
);
event Burning(
address indexed _to,
address indexed _burner,
uint256 _amount
);
event IncentiveContractUpdate(
address indexed _incentiveContract
);
// ----------- State changing api -----------
function burn(uint256 amount) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
// ----------- Burner only state changing api -----------
function burnFrom(address account, uint256 amount) external;
// ----------- Minter only state changing api -----------
function mint(address account, uint256 amount) external;
// ----------- Governor only state changing api -----------
function setIncentiveContract(address incentive) external;
// ----------- Getters -----------
function incentiveContract() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
/// @title an abstract contract for timed events
/// @author Ring Protocol
abstract contract Timed {
/// @notice the start timestamp of the timed period
uint256 public startTime;
/// @notice the duration of the timed period
uint256 public duration;
event DurationUpdate(uint256 _duration);
event TimerReset(uint256 _startTime);
constructor(uint256 _duration) {
_setDuration(_duration);
}
modifier duringTime() {
require(isTimeStarted(), "Timed: time not started");
require(!isTimeEnded(), "Timed: time ended");
_;
}
modifier afterTime() {
require(isTimeEnded(), "Timed: time not ended");
_;
}
/// @notice return true if time period has ended
function isTimeEnded() public view returns (bool) {
return remainingTime() == 0;
}
/// @notice number of seconds remaining until time is up
/// @return remaining
function remainingTime() public view returns (uint256) {
return duration - timeSinceStart(); // duration always >= timeSinceStart which is on [0,d]
}
/// @notice number of seconds since contract was initialized
/// @return timestamp
/// @dev will be less than or equal to duration
function timeSinceStart() public view returns (uint256) {
if (!isTimeStarted()) {
return 0; // uninitialized
}
uint256 _duration = duration;
// solhint-disable-next-line not-rely-on-time
uint256 timePassed = block.timestamp - startTime; // block timestamp always >= startTime
return timePassed > _duration ? _duration : timePassed;
}
function isTimeStarted() public view returns (bool) {
return startTime != 0;
}
function _initTimed() internal {
// solhint-disable-next-line not-rely-on-time
startTime = block.timestamp;
// solhint-disable-next-line not-rely-on-time
emit TimerReset(block.timestamp);
}
function _setDuration(uint _duration) internal {
duration = _duration;
emit DurationUpdate(_duration);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
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);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
|
safeTransfer(address token, address to, uint value)
|
function _allocateSingle(uint256 amount, address pcvDeposit)
internal
virtual
override
{
TransferHelper.safeTransfer(tokenAddress, pcvDeposit, amount);
IPCVDeposit(pcvDeposit).deposit();
}
| 1,154,599
|
/*
Copyright 2018 bZeroX, LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
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.
*/
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;
}
}
// This provides a gatekeeping modifier for functions that can only be used by the bZx contract
// Since it inherits Ownable provides typical ownership functionality with a slight modification to the transferOwnership function
// Setting owner and bZxContractAddress to the same address is not supported.
contract BZxOwnable is Ownable {
address public bZxContractAddress;
event BZxOwnershipTransferred(address indexed previousBZxContract, address indexed newBZxContract);
// modifier reverts if bZxContractAddress isn't set
modifier onlyBZx() {
require(msg.sender == bZxContractAddress, "only bZx contracts can call this function");
_;
}
/**
* @dev Allows the current owner to transfer the bZx contract owner to a new contract address
* @param newBZxContractAddress The bZx contract address to transfer ownership to.
*/
function transferBZxOwnership(address newBZxContractAddress) public onlyOwner {
require(newBZxContractAddress != address(0) && newBZxContractAddress != owner, "transferBZxOwnership::unauthorized");
emit BZxOwnershipTransferred(bZxContractAddress, newBZxContractAddress);
bZxContractAddress = newBZxContractAddress;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
* This overrides transferOwnership in Ownable to prevent setting the new owner the same as the bZxContract
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0) && newOwner != bZxContractAddress, "transferOwnership::unauthorized");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract GasRefunder {
using SafeMath for uint256;
// If true, uses the "transfer" method, which throws on failure, reverting state.
// If false, a failed "send" won't throw, and fails silently.
// Note that a throw will prevent a GasRefund event.
bool public throwOnGasRefundFail = false;
struct GasData {
address payer;
uint gasUsed;
bool isPaid;
}
event GasRefund(address payer, uint gasUsed, uint currentGasPrice, uint refundAmount, bool refundSuccess);
modifier refundsGas(address payer, uint gasPrice, uint gasUsed, uint percentMultiplier)
{
_;
calculateAndSendRefund(
payer,
gasUsed,
gasPrice,
percentMultiplier
);
}
modifier refundsGasAfterCollection(address payer, uint gasPrice, uint percentMultiplier)
{
uint startingGas = gasleft();
_;
calculateAndSendRefund(
payer,
startingGas,
gasPrice,
percentMultiplier
);
}
function calculateAndSendRefund(
address payer,
uint gasUsed,
uint gasPrice,
uint percentMultiplier)
internal
{
if (gasUsed == 0 || gasPrice == 0)
return;
gasUsed = gasUsed - gasleft();
sendRefund(
payer,
gasUsed,
gasPrice,
percentMultiplier
);
}
function sendRefund(
address payer,
uint gasUsed,
uint gasPrice,
uint percentMultiplier)
internal
returns (bool)
{
if (percentMultiplier == 0) // 0 percentMultiplier not allowed
percentMultiplier = 100;
uint refundAmount = gasUsed.mul(gasPrice).mul(percentMultiplier).div(100);
if (throwOnGasRefundFail) {
payer.transfer(refundAmount);
emit GasRefund(
payer,
gasUsed,
gasPrice,
refundAmount,
true
);
} else {
emit GasRefund(
payer,
gasUsed,
gasPrice,
refundAmount,
payer.send(refundAmount)
);
}
return true;
}
}
// supports a single EMA calculated for the inheriting contract
contract EMACollector {
uint public emaValue; // the last ema calculated
uint public emaPeriods; // averaging periods for EMA calculation
modifier updatesEMA(uint value) {
_;
updateEMA(value);
}
function updateEMA(uint value)
internal {
/*
Multiplier: 2 / (emaPeriods + 1)
EMA: (LastestValue - PreviousEMA) * Multiplier + PreviousEMA
*/
require(emaPeriods >= 2, "emaPeriods < 2");
// calculate new EMA
emaValue =
SafeMath.sub(
SafeMath.add(
value / (emaPeriods + 1) * 2,
emaValue
),
emaValue / (emaPeriods + 1) * 2
);
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title EIP20/ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract EIP20 is ERC20 {
string public name;
uint8 public decimals;
string public symbol;
}
interface NonCompliantEIP20 {
function transfer(address _to, uint _value) external;
function transferFrom(address _from, address _to, uint _value) external;
function approve(address _spender, uint _value) external;
}
/**
* @title EIP20/ERC20 wrapper that will support noncompliant ERC20s
* @dev see https://github.com/ethereum/EIPs/issues/20
* @dev see https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
contract EIP20Wrapper {
function eip20Transfer(
address token,
address to,
uint256 value)
internal
returns (bool result) {
NonCompliantEIP20(token).transfer(to, value);
assembly {
switch returndatasize()
case 0 { // non compliant ERC20
result := not(0) // result is true
}
case 32 { // compliant ERC20
returndatacopy(0, 0, 32)
result := mload(0) // result == returndata of external call
}
default { // not an not an ERC20 token
revert(0, 0)
}
}
require(result, "eip20Transfer failed");
}
function eip20TransferFrom(
address token,
address from,
address to,
uint256 value)
internal
returns (bool result) {
NonCompliantEIP20(token).transferFrom(from, to, value);
assembly {
switch returndatasize()
case 0 { // non compliant ERC20
result := not(0) // result is true
}
case 32 { // compliant ERC20
returndatacopy(0, 0, 32)
result := mload(0) // result == returndata of external call
}
default { // not an not an ERC20 token
revert(0, 0)
}
}
require(result, "eip20TransferFrom failed");
}
function eip20Approve(
address token,
address spender,
uint256 value)
internal
returns (bool result) {
NonCompliantEIP20(token).approve(spender, value);
assembly {
switch returndatasize()
case 0 { // non compliant ERC20
result := not(0) // result is true
}
case 32 { // compliant ERC20
returndatacopy(0, 0, 32)
result := mload(0) // result == returndata of external call
}
default { // not an not an ERC20 token
revert(0, 0)
}
}
require(result, "eip20Approve failed");
}
}
interface OracleInterface {
/// @dev Called by bZx after a loan order is taken
/// @param loanOrderHash A unique hash representing the loan order
/// @param taker The taker of the loan order
/// @param gasUsed The initial used gas, collected in a modifier in bZx, for optional gas refunds
/// @return Successful execution of the function
function didTakeOrder(
bytes32 loanOrderHash,
address taker,
uint gasUsed)
external
returns (bool);
/// @dev Called by bZx after a position token is traded
/// @param loanOrderHash A unique hash representing the loan order
/// @param trader The trader doing the trade
/// @param tradeTokenAddress The token that was bought in the trade
/// @param tradeTokenAmount The amount of token that was bought
/// @param gasUsed The initial used gas, collected in a modifier in bZx, for optional gas refunds
/// @return Successful execution of the function
function didTradePosition(
bytes32 loanOrderHash,
address trader,
address tradeTokenAddress,
uint tradeTokenAmount,
uint gasUsed)
external
returns (bool);
/// @dev Called by bZx after interest should be paid to a lender
/// @dev Assume the interest token has already been transfered to
/// @dev this contract before this function is called.
/// @param loanOrderHash A unique hash representing the loan order
/// @param trader The trader
/// @param lender The lender
/// @param interestTokenAddress The token that will be paid for interest
/// @param amountOwed The amount interest to pay
/// @param convert A boolean indicating if the interest should be converted to Ether
/// @param gasUsed The initial used gas, collected in a modifier in bZx, for optional gas refunds
/// @return Successful execution of the function
function didPayInterest(
bytes32 loanOrderHash,
address trader,
address lender,
address interestTokenAddress,
uint amountOwed,
bool convert,
uint gasUsed)
external
returns (bool);
/// @dev Called by bZx after a borrower has deposited additional collateral
/// @dev token for an open loan
/// @param loanOrderHash A unique hash representing the loan order.
/// @param borrower The borrower
/// @param gasUsed The initial used gas, collected in a modifier in bZx, for optional gas refunds
/// @return Successful execution of the function
function didDepositCollateral(
bytes32 loanOrderHash,
address borrower,
uint gasUsed)
external
returns (bool);
/// @dev Called by bZx after a borrower has withdrawn excess collateral
/// @dev token for an open loan
/// @param loanOrderHash A unique hash representing the loan order.
/// @param borrower The borrower
/// @param gasUsed The initial used gas, collected in a modifier in bZx, for optional gas refunds
/// @return Successful execution of the function
function didWithdrawCollateral(
bytes32 loanOrderHash,
address borrower,
uint gasUsed)
external
returns (bool);
/// @dev Called by bZx after a borrower has changed the collateral token
/// @dev used for an open loan
/// @param loanOrderHash A unique hash representing the loan order
/// @param borrower The borrower
/// @param gasUsed The initial used gas, collected in a modifier in bZx, for optional gas refunds
/// @return Successful execution of the function
function didChangeCollateral(
bytes32 loanOrderHash,
address borrower,
uint gasUsed)
external
returns (bool);
/// @dev Called by bZx after a borrower has withdraw their profits, if any
/// @dev used for an open loan
/// @param loanOrderHash A unique hash representing the loan order
/// @param borrower The borrower
/// @param gasUsed The initial used gas, collected in a modifier in bZx, for optional gas refunds
/// @return Successful execution of the function
function didWithdrawProfit(
bytes32 loanOrderHash,
address borrower,
uint profitOrLoss,
uint gasUsed)
external
returns (bool);
/// @dev Called by bZx after a loan is closed
/// @param loanOrderHash A unique hash representing the loan order.
/// @param loanCloser The user that closed the loan
/// @param isLiquidation A boolean indicating if the loan was closed due to liquidation
/// @param gasUsed The initial used gas, collected in a modifier in bZx, for optional gas refunds
/// @return Successful execution of the function
function didCloseLoan(
bytes32 loanOrderHash,
address loanCloser,
bool isLiquidation,
uint gasUsed)
external
returns (bool);
/// @dev Places a manual on-chain trade with a liquidity provider
/// @param sourceTokenAddress The token being sold
/// @param destTokenAddress The token being bought
/// @param sourceTokenAmount The amount of token being sold
/// @return The amount of destToken bought
function doManualTrade(
address sourceTokenAddress,
address destTokenAddress,
uint sourceTokenAmount)
external
returns (uint);
/// @dev Places an automatic on-chain trade with a liquidity provider
/// @param sourceTokenAddress The token being sold
/// @param destTokenAddress The token being bought
/// @param sourceTokenAmount The amount of token being sold
/// @return The amount of destToken bought
function doTrade(
address sourceTokenAddress,
address destTokenAddress,
uint sourceTokenAmount)
external
returns (uint);
/// @dev Verifies a position has fallen below margin maintenance
/// @dev then liquidates the position on-chain
/// @param loanTokenAddress The token that was loaned
/// @param positionTokenAddress The token in the current position (could also be the loanToken)
/// @param collateralTokenAddress The token used for collateral
/// @param loanTokenAmount The amount of loan token
/// @param positionTokenAmount The amount of position token
/// @param collateralTokenAmount The amount of collateral token
/// @param maintenanceMarginAmount The maintenance margin amount from the loan
/// @return The amount of destToken bought
function verifyAndLiquidate(
address loanTokenAddress,
address positionTokenAddress,
address collateralTokenAddress,
uint loanTokenAmount,
uint positionTokenAmount,
uint collateralTokenAmount,
uint maintenanceMarginAmount)
external
returns (uint);
/// @dev Liquidates collateral to cover loan losses
/// @param collateralTokenAddress The collateral token
/// @param loanTokenAddress The loan token
/// @param collateralTokenAmountUsable The total amount of collateral usable to cover losses
/// @param loanTokenAmountNeeded The amount of loan token needed to cover losses
/// @param initialMarginAmount The initial margin amount set for the loan
/// @param maintenanceMarginAmount The maintenance margin amount set for the loan
/// @return The amount of destToken bought
function doTradeofCollateral(
address collateralTokenAddress,
address loanTokenAddress,
uint collateralTokenAmountUsable,
uint loanTokenAmountNeeded,
uint initialMarginAmount,
uint maintenanceMarginAmount)
external
returns (uint, uint);
/// @dev Checks if a position has fallen below margin
/// @dev maintenance and should be liquidated
/// @param loanOrderHash A unique hash representing the loan order
/// @param trader The address of the trader
/// @param loanTokenAddress The token that was loaned
/// @param positionTokenAddress The token in the current position (could also be the loanToken)
/// @param collateralTokenAddress The token used for collateral
/// @param loanTokenAmount The amount of loan token
/// @param positionTokenAmount The amount of position token
/// @param collateralTokenAmount The amount of collateral token
/// @param maintenanceMarginAmount The maintenance margin amount from the loan
/// @return Returns True if the trade should be liquidated immediately
function shouldLiquidate(
bytes32 loanOrderHash,
address trader,
address loanTokenAddress,
address positionTokenAddress,
address collateralTokenAddress,
uint loanTokenAmount,
uint positionTokenAmount,
uint collateralTokenAmount,
uint maintenanceMarginAmount)
external
view
returns (bool);
/// @dev Gets the trade price of the ERC-20 token pair
/// @param sourceTokenAddress Token being sold
/// @param destTokenAddress Token being bought
/// @return The trade rate
function getTradeRate(
address sourceTokenAddress,
address destTokenAddress)
external
view
returns (uint);
/// @dev Returns the profit/loss data for the current position
/// @param positionTokenAddress The token in the current position (could also be the loanToken)
/// @param loanTokenAddress The token that was loaned
/// @param positionTokenAmount The amount of position token
/// @param loanTokenAmount The amount of loan token
/// @return isProfit, profitOrLoss (denominated in positionToken)
function getProfitOrLoss(
address positionTokenAddress,
address loanTokenAddress,
uint positionTokenAmount,
uint loanTokenAmount)
external
view
returns (bool isProfit, uint profitOrLoss);
/// @dev Returns the current margin level for this particular loan/position
/// @param loanTokenAddress The token that was loaned
/// @param positionTokenAddress The token in the current position (could also be the loanToken)
/// @param collateralTokenAddress The token used for collateral
/// @param loanTokenAmount The amount of loan token
/// @param positionTokenAmount The amount of position token
/// @param collateralTokenAmount The amount of collateral token
/// @return The current margin amount (a percentage -> i.e. 54350000000000000000 == 54.35%)
function getCurrentMarginAmount(
address loanTokenAddress,
address positionTokenAddress,
address collateralTokenAddress,
uint loanTokenAmount,
uint positionTokenAmount,
uint collateralTokenAmount)
external
view
returns (uint);
/// @dev Checks if the ERC20 token pair is supported by the oracle
/// @param sourceTokenAddress Token being sold
/// @param destTokenAddress Token being bought
/// @param sourceTokenAmount Amount of token being sold
/// @return True if price discovery and trading is supported
function isTradeSupported(
address sourceTokenAddress,
address destTokenAddress,
uint sourceTokenAmount)
external
view
returns (bool);
}
interface WETH_Interface {
function deposit() external payable;
function withdraw(uint wad) external;
}
interface KyberNetwork_Interface {
/// @notice use token address ETH_TOKEN_ADDRESS for ether
/// @dev makes a trade between src and dest token and send dest token to destAddress
/// @param src Src token
/// @param srcAmount amount of src tokens
/// @param dest Destination token
/// @param destAddress Address to send tokens to
/// @param maxDestAmount A limit on the amount of dest tokens
/// @param minConversionRate The minimal conversion rate. If actual rate is lower, trade is canceled.
/// @param walletId is the wallet ID to send part of the fees
/// @return amount of actual dest tokens
function trade(
address src,
uint srcAmount,
address dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
)
external
payable
returns(uint);
/// @notice use token address ETH_TOKEN_ADDRESS for ether
function getExpectedRate(
address src,
address dest,
uint srcQty)
external
view
returns (uint expectedRate, uint slippageRate);
}
contract BZxOracle is OracleInterface, EIP20Wrapper, EMACollector, GasRefunder, BZxOwnable {
using SafeMath for uint256;
// this is the value the Kyber portal uses when setting a very high maximum number
uint internal constant MAX_FOR_KYBER = 57896044618658097711785492504343953926634992332820282019728792003956564819968;
address internal constant KYBER_ETH_TOKEN_ADDRESS = 0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee;
// Percentage of interest retained as fee
// This will always be between 0 and 100
uint public interestFeePercent = 10;
// Percentage of liquidation level that will trigger a liquidation of positions
// This can never be less than 100
uint public liquidationThresholdPercent = 105;
// Percentage of gas refund paid to non-bounty hunters
uint public gasRewardPercent = 10;
// Percentage of gas refund paid to bounty hunters after successfully liquidating a position
uint public bountyRewardPercent = 110;
// A threshold of minimum initial margin for loan to be insured by the guarantee fund
// A value of 0 indicates that no threshold exists for this parameter.
uint public minInitialMarginAmount = 0;
// A threshold of minimum maintenance margin for loan to be insured by the guarantee fund
// A value of 0 indicates that no threshold exists for this parameter.
uint public minMaintenanceMarginAmount = 25;
bool public isManualTradingAllowed = true;
address public vaultContract;
address public kyberContract;
address public wethContract;
address public bZRxTokenContract;
mapping (bytes32 => GasData[]) public gasRefunds; // mapping of loanOrderHash to array of GasData
constructor(
address _vaultContract,
address _kyberContract,
address _wethContract,
address _bZRxTokenContract)
public
payable
{
vaultContract = _vaultContract;
kyberContract = _kyberContract;
wethContract = _wethContract;
bZRxTokenContract = _bZRxTokenContract;
// settings for EMACollector
emaValue = 20 * 10**9 wei; // set an initial price average for gas (20 gwei)
emaPeriods = 10; // set periods to use for EMA calculation
}
// The contract needs to be able to receive Ether from Kyber trades
function() public payable {}
// standard functions
function didTakeOrder(
bytes32 loanOrderHash,
address taker,
uint gasUsed)
public
onlyBZx
updatesEMA(tx.gasprice)
returns (bool)
{
gasRefunds[loanOrderHash].push(GasData({
payer: taker,
gasUsed: gasUsed.sub(gasleft()),
isPaid: false
}));
return true;
}
function didTradePosition(
bytes32 /* loanOrderHash */,
address /* trader */,
address /* tradeTokenAddress */,
uint /* tradeTokenAmount */,
uint /* gasUsed */)
public
onlyBZx
updatesEMA(tx.gasprice)
returns (bool)
{
return true;
}
function didPayInterest(
bytes32 /* loanOrderHash */,
address /* trader */,
address lender,
address interestTokenAddress,
uint amountOwed,
bool convert,
uint /* gasUsed */)
public
onlyBZx
updatesEMA(tx.gasprice)
returns (bool)
{
uint interestFee = amountOwed.mul(interestFeePercent).div(100);
// Transfers the interest to the lender, less the interest fee.
// The fee is retained by the oracle.
if (!_transferToken(
interestTokenAddress,
lender,
amountOwed.sub(interestFee))) {
revert("BZxOracle::didPayInterest: _transferToken failed");
}
if (interestTokenAddress == wethContract) {
// interest paid in WETH is withdrawn to Ether
WETH_Interface(wethContract).withdraw(interestFee);
} else if (convert && interestTokenAddress != bZRxTokenContract) {
// interest paid in BZRX is retained as is, other tokens are sold for Ether
_doTradeForEth(
interestTokenAddress,
interestFee,
this // BZxOracle receives the Ether proceeds
);
}
return true;
}
function didDepositCollateral(
bytes32 /* loanOrderHash */,
address /* borrower */,
uint /* gasUsed */)
public
onlyBZx
updatesEMA(tx.gasprice)
returns (bool)
{
return true;
}
function didWithdrawCollateral(
bytes32 /* loanOrderHash */,
address /* borrower */,
uint /* gasUsed */)
public
onlyBZx
updatesEMA(tx.gasprice)
returns (bool)
{
return true;
}
function didChangeCollateral(
bytes32 /* loanOrderHash */,
address /* borrower */,
uint /* gasUsed */)
public
onlyBZx
updatesEMA(tx.gasprice)
returns (bool)
{
return true;
}
function didWithdrawProfit(
bytes32 /* loanOrderHash */,
address /* borrower */,
uint /* profitOrLoss */,
uint /* gasUsed */)
public
onlyBZx
updatesEMA(tx.gasprice)
returns (bool)
{
return true;
}
function didCloseLoan(
bytes32 loanOrderHash,
address loanCloser,
bool isLiquidation,
uint gasUsed)
public
onlyBZx
//refundsGas(taker, emaValue, gasUsed, 0) // refunds based on collected gas price EMA
updatesEMA(tx.gasprice)
returns (bool)
{
// sends gas refunds owed from earlier transactions
for (uint i=0; i < gasRefunds[loanOrderHash].length; i++) {
GasData storage gasData = gasRefunds[loanOrderHash][i];
if (!gasData.isPaid) {
if (sendRefund(
gasData.payer,
gasData.gasUsed,
emaValue,
gasRewardPercent))
gasData.isPaid = true;
}
}
// sends gas and bounty reward to bounty hunter
if (isLiquidation) {
calculateAndSendRefund(
loanCloser,
gasUsed,
emaValue,
bountyRewardPercent);
}
return true;
}
function doManualTrade(
address sourceTokenAddress,
address destTokenAddress,
uint sourceTokenAmount)
public
onlyBZx
returns (uint destTokenAmount)
{
if (isManualTradingAllowed) {
destTokenAmount = _doTrade(
sourceTokenAddress,
destTokenAddress,
sourceTokenAmount,
MAX_FOR_KYBER); // no limit on the dest amount
}
else {
revert("Manual trading is disabled.");
}
}
function doTrade(
address sourceTokenAddress,
address destTokenAddress,
uint sourceTokenAmount)
public
onlyBZx
returns (uint destTokenAmount)
{
destTokenAmount = _doTrade(
sourceTokenAddress,
destTokenAddress,
sourceTokenAmount,
MAX_FOR_KYBER); // no limit on the dest amount
}
function verifyAndLiquidate(
address loanTokenAddress,
address positionTokenAddress,
address collateralTokenAddress,
uint loanTokenAmount,
uint positionTokenAmount,
uint collateralTokenAmount,
uint maintenanceMarginAmount)
public
onlyBZx
returns (uint destTokenAmount)
{
if (!shouldLiquidate(
0x0,
0x0,
loanTokenAddress,
positionTokenAddress,
collateralTokenAddress,
loanTokenAmount,
positionTokenAmount,
collateralTokenAmount,
maintenanceMarginAmount)) {
return 0;
}
destTokenAmount = _doTrade(
positionTokenAddress,
loanTokenAddress,
positionTokenAmount,
MAX_FOR_KYBER); // no limit on the dest amount
}
function doTradeofCollateral(
address collateralTokenAddress,
address loanTokenAddress,
uint collateralTokenAmountUsable,
uint loanTokenAmountNeeded,
uint initialMarginAmount,
uint maintenanceMarginAmount)
public
onlyBZx
returns (uint loanTokenAmountCovered, uint collateralTokenAmountUsed)
{
uint collateralTokenBalance = EIP20(collateralTokenAddress).balanceOf.gas(4999)(this); // Changes to state require at least 5000 gas
if (collateralTokenBalance < collateralTokenAmountUsable) { // sanity check
revert("BZxOracle::doTradeofCollateral: collateralTokenBalance < collateralTokenAmountUsable");
}
loanTokenAmountCovered = _doTrade(
collateralTokenAddress,
loanTokenAddress,
collateralTokenAmountUsable,
loanTokenAmountNeeded);
collateralTokenAmountUsed = collateralTokenBalance.sub(EIP20(collateralTokenAddress).balanceOf.gas(4999)(this)); // Changes to state require at least 5000 gas
if (collateralTokenAmountUsed < collateralTokenAmountUsable) {
// send unused collateral token back to the vault
if (!_transferToken(
collateralTokenAddress,
vaultContract,
collateralTokenAmountUsable.sub(collateralTokenAmountUsed))) {
revert("BZxOracle::doTradeofCollateral: _transferToken failed");
}
}
if (loanTokenAmountCovered < loanTokenAmountNeeded) {
// cover losses with insurance if applicable
if ((minInitialMarginAmount == 0 || initialMarginAmount >= minInitialMarginAmount) &&
(minMaintenanceMarginAmount == 0 || maintenanceMarginAmount >= minMaintenanceMarginAmount)) {
loanTokenAmountCovered = loanTokenAmountCovered.add(
_doTradeWithEth(
loanTokenAddress,
loanTokenAmountNeeded.sub(loanTokenAmountCovered),
vaultContract
));
}
}
}
/*
* Public View functions
*/
function shouldLiquidate(
bytes32 /* loanOrderHash */,
address /* trader */,
address loanTokenAddress,
address positionTokenAddress,
address collateralTokenAddress,
uint loanTokenAmount,
uint positionTokenAmount,
uint collateralTokenAmount,
uint maintenanceMarginAmount)
public
view
returns (bool)
{
return (
getCurrentMarginAmount(
loanTokenAddress,
positionTokenAddress,
collateralTokenAddress,
loanTokenAmount,
positionTokenAmount,
collateralTokenAmount).div(maintenanceMarginAmount).div(10**16) <= (liquidationThresholdPercent)
);
}
function isTradeSupported(
address sourceTokenAddress,
address destTokenAddress,
uint sourceTokenAmount)
public
view
returns (bool)
{
(uint rate, uint slippage) = _getExpectedRate(
sourceTokenAddress,
destTokenAddress,
sourceTokenAmount);
if (rate > 0 && (sourceTokenAmount == 0 || slippage > 0))
return true;
else
return false;
}
function getTradeRate(
address sourceTokenAddress,
address destTokenAddress)
public
view
returns (uint rate)
{
(rate,) = _getExpectedRate(
sourceTokenAddress,
destTokenAddress,
0);
}
// returns bool isProfit, uint profitOrLoss
// the position's profit/loss denominated in positionToken
function getProfitOrLoss(
address positionTokenAddress,
address loanTokenAddress,
uint positionTokenAmount,
uint loanTokenAmount)
public
view
returns (bool isProfit, uint profitOrLoss)
{
uint loanToPositionAmount;
if (positionTokenAddress == loanTokenAddress) {
loanToPositionAmount = loanTokenAmount;
} else {
(uint positionToLoanRate,) = _getExpectedRate(
positionTokenAddress,
loanTokenAddress,
0);
if (positionToLoanRate == 0) {
return;
}
loanToPositionAmount = loanTokenAmount.mul(10**18).div(positionToLoanRate);
}
if (positionTokenAmount > loanToPositionAmount) {
isProfit = true;
profitOrLoss = positionTokenAmount - loanToPositionAmount;
} else {
isProfit = false;
profitOrLoss = loanToPositionAmount - positionTokenAmount;
}
}
/// @return The current margin amount (a percentage -> i.e. 54350000000000000000 == 54.35%)
function getCurrentMarginAmount(
address loanTokenAddress,
address positionTokenAddress,
address collateralTokenAddress,
uint loanTokenAmount,
uint positionTokenAmount,
uint collateralTokenAmount)
public
view
returns (uint)
{
uint collateralToLoanAmount;
if (collateralTokenAddress == loanTokenAddress) {
collateralToLoanAmount = collateralTokenAmount;
} else {
(uint collateralToLoanRate,) = _getExpectedRate(
collateralTokenAddress,
loanTokenAddress,
0);
if (collateralToLoanRate == 0) {
return 0;
}
collateralToLoanAmount = collateralTokenAmount.mul(collateralToLoanRate).div(10**18);
}
uint positionToLoanAmount;
if (positionTokenAddress == loanTokenAddress) {
positionToLoanAmount = positionTokenAmount;
} else {
(uint positionToLoanRate,) = _getExpectedRate(
positionTokenAddress,
loanTokenAddress,
0);
if (positionToLoanRate == 0) {
return 0;
}
positionToLoanAmount = positionTokenAmount.mul(positionToLoanRate).div(10**18);
}
return collateralToLoanAmount.add(positionToLoanAmount).sub(loanTokenAmount).mul(10**20).div(loanTokenAmount);
}
/*
* Owner functions
*/
function setInterestFeePercent(
uint newRate)
public
onlyOwner
{
require(newRate != interestFeePercent && newRate >= 0 && newRate <= 100);
interestFeePercent = newRate;
}
function setLiquidationThresholdPercent(
uint newValue)
public
onlyOwner
{
require(newValue != liquidationThresholdPercent && liquidationThresholdPercent >= 100);
liquidationThresholdPercent = newValue;
}
function setGasRewardPercent(
uint newValue)
public
onlyOwner
{
require(newValue != gasRewardPercent);
gasRewardPercent = newValue;
}
function setBountyRewardPercent(
uint newValue)
public
onlyOwner
{
require(newValue != bountyRewardPercent);
bountyRewardPercent = newValue;
}
function setMarginThresholds(
uint newInitialMargin,
uint newMaintenanceMargin)
public
onlyOwner
{
require(newInitialMargin >= newMaintenanceMargin);
minInitialMarginAmount = newInitialMargin;
minMaintenanceMarginAmount = newMaintenanceMargin;
}
function setManualTradingAllowed (
bool _isManualTradingAllowed)
public
onlyOwner
{
if (isManualTradingAllowed != _isManualTradingAllowed)
isManualTradingAllowed = _isManualTradingAllowed;
}
function setVaultContractAddress(
address newAddress)
public
onlyOwner
{
require(newAddress != vaultContract && newAddress != address(0));
vaultContract = newAddress;
}
function setKyberContractAddress(
address newAddress)
public
onlyOwner
{
require(newAddress != kyberContract && newAddress != address(0));
kyberContract = newAddress;
}
function setWethContractAddress(
address newAddress)
public
onlyOwner
{
require(newAddress != wethContract && newAddress != address(0));
wethContract = newAddress;
}
function setBZRxTokenContractAddress(
address newAddress)
public
onlyOwner
{
require(newAddress != bZRxTokenContract && newAddress != address(0));
bZRxTokenContract = newAddress;
}
function setEMAPeriods (
uint _newEMAPeriods)
public
onlyOwner {
require(_newEMAPeriods > 1 && _newEMAPeriods != emaPeriods);
emaPeriods = _newEMAPeriods;
}
function transferEther(
address to,
uint value)
public
onlyOwner
returns (bool)
{
uint amount = value;
if (amount > address(this).balance) {
amount = address(this).balance;
}
return (to.send(amount));
}
function transferToken(
address tokenAddress,
address to,
uint value)
public
onlyOwner
returns (bool)
{
return (_transferToken(
tokenAddress,
to,
value
));
}
/*
* Internal functions
*/
// ref: https://github.com/KyberNetwork/smart-contracts/blob/master/integration.md#rate-query
function _getExpectedRate(
address sourceTokenAddress,
address destTokenAddress,
uint sourceTokenAmount)
internal
view
returns (uint expectedRate, uint slippageRate)
{
if (sourceTokenAddress == destTokenAddress) {
expectedRate = 10**18;
slippageRate = 0;
} else {
if (sourceTokenAddress == wethContract) {
(expectedRate, slippageRate) = KyberNetwork_Interface(kyberContract).getExpectedRate(
KYBER_ETH_TOKEN_ADDRESS,
destTokenAddress,
sourceTokenAmount
);
} else if (destTokenAddress == wethContract) {
(expectedRate, slippageRate) = KyberNetwork_Interface(kyberContract).getExpectedRate(
sourceTokenAddress,
KYBER_ETH_TOKEN_ADDRESS,
sourceTokenAmount
);
} else {
(uint sourceToEther, uint sourceToEtherSlippage) = KyberNetwork_Interface(kyberContract).getExpectedRate(
sourceTokenAddress,
KYBER_ETH_TOKEN_ADDRESS,
sourceTokenAmount
);
if (sourceTokenAmount > 0) {
sourceTokenAmount = sourceTokenAmount.mul(sourceToEther).div(10**18);
}
(uint etherToDest, uint etherToDestSlippage) = KyberNetwork_Interface(kyberContract).getExpectedRate(
KYBER_ETH_TOKEN_ADDRESS,
destTokenAddress,
sourceTokenAmount
);
expectedRate = sourceToEther.mul(etherToDest).div(10**18);
slippageRate = sourceToEtherSlippage.mul(etherToDestSlippage).div(10**18);
}
}
}
function _doTrade(
address sourceTokenAddress,
address destTokenAddress,
uint sourceTokenAmount,
uint maxDestTokenAmount)
internal
returns (uint destTokenAmount)
{
if (sourceTokenAddress == destTokenAddress) {
if (maxDestTokenAmount < MAX_FOR_KYBER) {
destTokenAmount = maxDestTokenAmount;
} else {
destTokenAmount = sourceTokenAmount;
}
} else {
if (sourceTokenAddress == wethContract) {
WETH_Interface(wethContract).withdraw(sourceTokenAmount);
destTokenAmount = KyberNetwork_Interface(kyberContract).trade
.value(sourceTokenAmount)( // send Ether along
KYBER_ETH_TOKEN_ADDRESS,
sourceTokenAmount,
destTokenAddress,
vaultContract, // bZxVault recieves the destToken
maxDestTokenAmount,
0, // no min coversation rate
address(0)
);
} else if (destTokenAddress == wethContract) {
// re-up the Kyber spend approval if needed
if (EIP20(sourceTokenAddress).allowance.gas(4999)(this, kyberContract) <
MAX_FOR_KYBER) {
eip20Approve(
sourceTokenAddress,
kyberContract,
MAX_FOR_KYBER);
}
destTokenAmount = KyberNetwork_Interface(kyberContract).trade(
sourceTokenAddress,
sourceTokenAmount,
KYBER_ETH_TOKEN_ADDRESS,
this, // BZxOracle receives the Ether proceeds
maxDestTokenAmount,
0, // no min coversation rate
address(0)
);
WETH_Interface(wethContract).deposit.value(destTokenAmount)();
if (!_transferToken(
destTokenAddress,
vaultContract,
destTokenAmount)) {
revert("BZxOracle::_doTrade: _transferToken failed");
}
} else {
// re-up the Kyber spend approval if needed
if (EIP20(sourceTokenAddress).allowance.gas(4999)(this, kyberContract) <
MAX_FOR_KYBER) {
eip20Approve(
sourceTokenAddress,
kyberContract,
MAX_FOR_KYBER);
}
uint maxDestEtherAmount = maxDestTokenAmount;
if (maxDestTokenAmount < MAX_FOR_KYBER) {
uint etherToDest;
(etherToDest,) = KyberNetwork_Interface(kyberContract).getExpectedRate(
KYBER_ETH_TOKEN_ADDRESS,
destTokenAddress,
0
);
maxDestEtherAmount = maxDestTokenAmount.mul(10**18).div(etherToDest);
}
uint destEtherAmount = KyberNetwork_Interface(kyberContract).trade(
sourceTokenAddress,
sourceTokenAmount,
KYBER_ETH_TOKEN_ADDRESS,
this, // BZxOracle receives the Ether proceeds
maxDestEtherAmount,
0, // no min coversation rate
address(0)
);
destTokenAmount = KyberNetwork_Interface(kyberContract).trade
.value(destEtherAmount)( // send Ether along
KYBER_ETH_TOKEN_ADDRESS,
destEtherAmount,
destTokenAddress,
vaultContract, // bZxVault recieves the destToken
maxDestTokenAmount,
0, // no min coversation rate
address(0)
);
}
}
}
function _doTradeForEth(
address sourceTokenAddress,
uint sourceTokenAmount,
address receiver)
internal
returns (uint)
{
// re-up the Kyber spend approval if needed
if (EIP20(sourceTokenAddress).allowance.gas(4999)(this, kyberContract) <
MAX_FOR_KYBER) {
eip20Approve(
sourceTokenAddress,
kyberContract,
MAX_FOR_KYBER);
}
// bytes4(keccak256("trade(address,uint256,address,address,uint256,uint256,address)")) = 0xcb3c28c7
bool result = kyberContract.call
.gas(gasleft())(
0xcb3c28c7,
sourceTokenAddress,
sourceTokenAmount,
KYBER_ETH_TOKEN_ADDRESS,
receiver,
MAX_FOR_KYBER, // no limit on the dest amount
0, // no min coversation rate
address(0)
);
assembly {
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
switch result
case 0 { return(0, 0x20) }
default { return(ptr, size) }
}
}
function _doTradeWithEth(
address destTokenAddress,
uint destTokenAmountNeeded,
address receiver)
internal
returns (uint)
{
uint etherToDest;
(etherToDest,) = KyberNetwork_Interface(kyberContract).getExpectedRate(
KYBER_ETH_TOKEN_ADDRESS,
destTokenAddress,
0
);
// calculate amount of ETH to use with a 5% buffer (unused ETH is returned by Kyber)
uint ethToSend = destTokenAmountNeeded.mul(10**18).div(etherToDest).mul(105).div(100);
if (ethToSend > address(this).balance) {
ethToSend = address(this).balance;
}
// bytes4(keccak256("trade(address,uint256,address,address,uint256,uint256,address)")) = 0xcb3c28c7
bool result = kyberContract.call
.gas(gasleft())
.value(ethToSend)( // send Ether along
0xcb3c28c7,
KYBER_ETH_TOKEN_ADDRESS,
ethToSend,
destTokenAddress,
receiver,
destTokenAmountNeeded,
0, // no min coversation rate
address(0)
);
assembly {
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
switch result
case 0 { return(0, 0x20) }
default { return(ptr, size) }
}
}
function _transferToken(
address tokenAddress,
address to,
uint value)
internal
returns (bool)
{
eip20Transfer(
tokenAddress,
to,
value);
return true;
}
}
|
Internal functions/ ref: https:github.com/KyberNetwork/smart-contracts/blob/master/integration.mdrate-query
|
{
function transferToken(
address tokenAddress,
address to,
uint value)
public
onlyOwner
returns (bool)
}
function _getExpectedRate(
address sourceTokenAddress,
address destTokenAddress,
uint sourceTokenAmount)
internal
view
returns (uint expectedRate, uint slippageRate)
if (sourceTokenAddress == destTokenAddress) {
expectedRate = 10**18;
slippageRate = 0;
if (sourceTokenAddress == wethContract) {
(expectedRate, slippageRate) = KyberNetwork_Interface(kyberContract).getExpectedRate(
KYBER_ETH_TOKEN_ADDRESS,
destTokenAddress,
sourceTokenAmount
);
(expectedRate, slippageRate) = KyberNetwork_Interface(kyberContract).getExpectedRate(
sourceTokenAddress,
KYBER_ETH_TOKEN_ADDRESS,
sourceTokenAmount
);
(uint sourceToEther, uint sourceToEtherSlippage) = KyberNetwork_Interface(kyberContract).getExpectedRate(
sourceTokenAddress,
KYBER_ETH_TOKEN_ADDRESS,
sourceTokenAmount
);
if (sourceTokenAmount > 0) {
sourceTokenAmount = sourceTokenAmount.mul(sourceToEther).div(10**18);
}
(uint etherToDest, uint etherToDestSlippage) = KyberNetwork_Interface(kyberContract).getExpectedRate(
KYBER_ETH_TOKEN_ADDRESS,
destTokenAddress,
sourceTokenAmount
);
expectedRate = sourceToEther.mul(etherToDest).div(10**18);
slippageRate = sourceToEtherSlippage.mul(etherToDestSlippage).div(10**18);
}
}
} else {
function transferToken(
address tokenAddress,
address to,
uint value)
public
onlyOwner
returns (bool)
}
function _getExpectedRate(
address sourceTokenAddress,
address destTokenAddress,
uint sourceTokenAmount)
internal
view
returns (uint expectedRate, uint slippageRate)
if (sourceTokenAddress == destTokenAddress) {
expectedRate = 10**18;
slippageRate = 0;
if (sourceTokenAddress == wethContract) {
(expectedRate, slippageRate) = KyberNetwork_Interface(kyberContract).getExpectedRate(
KYBER_ETH_TOKEN_ADDRESS,
destTokenAddress,
sourceTokenAmount
);
(expectedRate, slippageRate) = KyberNetwork_Interface(kyberContract).getExpectedRate(
sourceTokenAddress,
KYBER_ETH_TOKEN_ADDRESS,
sourceTokenAmount
);
(uint sourceToEther, uint sourceToEtherSlippage) = KyberNetwork_Interface(kyberContract).getExpectedRate(
sourceTokenAddress,
KYBER_ETH_TOKEN_ADDRESS,
sourceTokenAmount
);
if (sourceTokenAmount > 0) {
sourceTokenAmount = sourceTokenAmount.mul(sourceToEther).div(10**18);
}
(uint etherToDest, uint etherToDestSlippage) = KyberNetwork_Interface(kyberContract).getExpectedRate(
KYBER_ETH_TOKEN_ADDRESS,
destTokenAddress,
sourceTokenAmount
);
expectedRate = sourceToEther.mul(etherToDest).div(10**18);
slippageRate = sourceToEtherSlippage.mul(etherToDestSlippage).div(10**18);
}
}
} else if (destTokenAddress == wethContract) {
} else {
function transferToken(
address tokenAddress,
address to,
uint value)
public
onlyOwner
returns (bool)
}
function _getExpectedRate(
address sourceTokenAddress,
address destTokenAddress,
uint sourceTokenAmount)
internal
view
returns (uint expectedRate, uint slippageRate)
if (sourceTokenAddress == destTokenAddress) {
expectedRate = 10**18;
slippageRate = 0;
if (sourceTokenAddress == wethContract) {
(expectedRate, slippageRate) = KyberNetwork_Interface(kyberContract).getExpectedRate(
KYBER_ETH_TOKEN_ADDRESS,
destTokenAddress,
sourceTokenAmount
);
(expectedRate, slippageRate) = KyberNetwork_Interface(kyberContract).getExpectedRate(
sourceTokenAddress,
KYBER_ETH_TOKEN_ADDRESS,
sourceTokenAmount
);
(uint sourceToEther, uint sourceToEtherSlippage) = KyberNetwork_Interface(kyberContract).getExpectedRate(
sourceTokenAddress,
KYBER_ETH_TOKEN_ADDRESS,
sourceTokenAmount
);
if (sourceTokenAmount > 0) {
sourceTokenAmount = sourceTokenAmount.mul(sourceToEther).div(10**18);
}
(uint etherToDest, uint etherToDestSlippage) = KyberNetwork_Interface(kyberContract).getExpectedRate(
KYBER_ETH_TOKEN_ADDRESS,
destTokenAddress,
sourceTokenAmount
);
expectedRate = sourceToEther.mul(etherToDest).div(10**18);
slippageRate = sourceToEtherSlippage.mul(etherToDestSlippage).div(10**18);
}
}
}
| 6,990,913
|
./partial_match/42/0xb0D299d01bBD2fb20A52E315c768C88C44256d92/sources/ProofOfHumanity.sol
|
Give a ruling for a dispute. Can only be called by the arbitrator. TRUSTED. Accounts for the situation where the winner loses a case due to paying less appeal fees than expected. _disputeID ID of the dispute in the arbitrator contract. _ruling Ruling given by the arbitrator. Note that 0 is reserved for "Refused to arbitrate"./ The ruling is inverted if the loser paid its fees.
|
function rule(uint _disputeID, uint _ruling) public {
Party resultRuling = Party(_ruling);
DisputeData storage disputeData = arbitratorDisputeIDToDisputeData[msg.sender][_disputeID];
address submissionID = disputeData.submissionID;
uint challengeID = disputeData.challengeID;
Submission storage submission = submissions[submissionID];
Request storage request = submission.requests[submission.requests.length - 1];
Challenge storage challenge = request.challenges[challengeID];
Round storage round = challenge.rounds[challenge.lastRoundID];
ArbitratorData storage arbitratorData = arbitratorDataList[request.arbitratorDataID];
require(address(arbitratorData.arbitrator) == msg.sender);
require(!request.resolved);
resultRuling = Party.Requester;
else if (round.sideFunded == Party.Challenger)
resultRuling = Party.Challenger;
emit Ruling(IArbitrator(msg.sender), _disputeID, uint(resultRuling));
executeRuling(submissionID, challengeID, resultRuling);
}
| 3,440,490
|
./full_match/80001/0xD238dD70E5376DA21274717eaa6053075c8b62b4/sources/contracts/TraderBalanceVault/TraderBalanceVault.sol
|
@inheritdoc ITraderBalanceVault/
|
function unlockAsset(UnlockAssetParams calldata _params) external override onlyRole(VAULT_ACCESS_ROLE) {
balances[_params.trader][_params.asset].lockedBalance -= _params.amount;
balances[_params.receiver][_params.asset].availableBalance += _params.amount;
}
| 9,522,274
|
./full_match/80001/0x5828C287320288e130740ed538f3852fAD13995D/sources/contracts/oracles/template/OracleManagerFixedEpoch.sol
|
Checks for whether the oracle price update happened before end of current epoch end timestamp Called by internal functions to check whether oracle price update happened before end of current epoch end timestamp currentEpochStartTimestamp start timestamp of current epoch currentOracleUpdateTimestamp timestamp of current oracle price update
|
function _isCurrentPriceBeforeCurrentEpochEndTimestamp(
uint256 currentEpochStartTimestamp,
uint256 currentOracleUpdateTimestamp
) internal view returns (bool) {
return currentOracleUpdateTimestamp <= currentEpochStartTimestamp + EPOCH_LENGTH;
}
| 846,066
|
./full_match/3/0xd5E75b109Cd1A91406Bdc79f6aa2B367a10e4847/sources/contracts/ComposableTopDown.sol
|
See {IERC165-supportsInterface}. The interface id 0x1bc995e4 is added. The spec claims it to be the interface id of IERC998ERC721TopDown. But it is not. It is added anyway in case some contract checks it being compliant with the spec./
|
function supportsInterface(bytes4 interfaceId)
public
view
override(IERC165, ERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC998ERC721TopDown).interfaceId ||
interfaceId == type(IERC998ERC721TopDownEnumerable).interfaceId ||
interfaceId == 0x1bc995e4 ||
super.supportsInterface(interfaceId);
}
| 8,124,916
|
./partial_match/1/0x574b1337A006Cf82c4392a781584C80A78725B18/sources/OxPROXY.sol
|
exclude from paying fees or having max transaction amount
|
constructor() ERC20("0xPROXY", "0XP") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 5;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 5;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 100_000_000 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 4,143,598
|
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "hardhat/console.sol";
interface IFlashLoan {
function flashLoan(address[] memory tokens_, uint[] memory amts_,uint256 route, bytes calldata data_, bytes calldata instaData_) external;
}
contract InstaFlashReceiver {
using SafeERC20 for IERC20;
address chainToken = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
IFlashLoan internal immutable flashloan; // TODO: Contract/Protocol address to get flashloan
function flashBorrow(address[] calldata tokens_, uint[] calldata amts_, uint256 route, bytes calldata data_) public {
bytes memory _instaData;
flashloan.flashLoan(tokens_, amts_, route, data_, _instaData);
}
// Function which
function executeOperation(
address[] calldata tokens,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external returns (bool) {
// Do something
for (uint i = 0; i < tokens.length; i++) {
IERC20(tokens[i]).safeTransfer(address(flashloan), amounts[i] + premiums[i]);
}
}
function cast(
address[] calldata tokens,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external returns (bool) {
// Do something
for (uint i = 0; i < tokens.length; i++) {
IERC20(tokens[i]).safeTransfer(address(flashloan), amounts[i] + premiums[i]);
}
}
constructor(address flashloan_) {
flashloan = IFlashLoan(flashloan_);
}
}
|
Function which Do something
|
function executeOperation(
address[] calldata tokens,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external returns (bool) {
for (uint i = 0; i < tokens.length; i++) {
IERC20(tokens[i]).safeTransfer(address(flashloan), amounts[i] + premiums[i]);
}
}
| 13,050,984
|
// SPDX-License-Identifier: AGPL-3.0-only
/**
* DepositBoxEth.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2019-Present SKALE Labs
* @author Artem Payvin
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@skalenetwork/ima-interfaces/mainnet/DepositBoxes/IDepositBoxEth.sol";
import "../DepositBox.sol";
import "../../Messages.sol";
/**
* @title DepositBoxEth
* @dev Runs on mainnet,
* accepts messages from schain,
* stores deposits of ETH.
*/
contract DepositBoxEth is DepositBox, IDepositBoxEth {
using AddressUpgradeable for address payable;
mapping(address => uint256) public approveTransfers;
mapping(bytes32 => uint256) public transferredAmount;
mapping(bytes32 => bool) public activeEthTransfers;
event ActiveEthTransfers(bytes32 indexed schainHash, bool active);
receive() external payable override {
revert("Use deposit function");
}
/**
* @dev Allows `msg.sender` to send ETH from mainnet to schain.
*
* Requirements:
*
* - Schain name must not be `Mainnet`.
* - Receiver contract should be added as twin contract on schain.
* - Schain that receives tokens should not be killed.
*/
function deposit(string memory schainName)
external
payable
override
rightTransaction(schainName, msg.sender)
whenNotKilled(keccak256(abi.encodePacked(schainName)))
{
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
address contractReceiver = schainLinks[schainHash];
require(contractReceiver != address(0), "Unconnected chain");
_saveTransferredAmount(schainHash, msg.value);
messageProxy.postOutgoingMessage(
schainHash,
contractReceiver,
Messages.encodeTransferEthMessage(msg.sender, msg.value)
);
}
/**
* @dev Allows MessageProxyForMainnet contract to execute transferring ERC20 token from schain to mainnet.
*
* Requirements:
*
* - Schain from which the eth came should not be killed.
* - Sender contract should be defined and schain name cannot be `Mainnet`.
* - Amount of eth on DepositBoxEth should be equal or more than transferred amount.
*/
function postMessage(
bytes32 schainHash,
address sender,
bytes calldata data
)
external
override
onlyMessageProxy
whenNotKilled(schainHash)
checkReceiverChain(schainHash, sender)
{
Messages.TransferEthMessage memory message = Messages.decodeTransferEthMessage(data);
require(
message.amount <= address(this).balance,
"Not enough money to finish this transaction"
);
_removeTransferredAmount(schainHash, message.amount);
if (!activeEthTransfers[schainHash]) {
approveTransfers[message.receiver] += message.amount;
} else {
payable(message.receiver).sendValue(message.amount);
}
}
/**
* @dev Transfers a user's ETH.
*
* Requirements:
*
* - DepositBoxETh must have sufficient ETH.
* - User must be approved for ETH transfer.
*/
function getMyEth() external override {
require(approveTransfers[msg.sender] > 0, "User has insufficient ETH");
uint256 amount = approveTransfers[msg.sender];
approveTransfers[msg.sender] = 0;
payable(msg.sender).sendValue(amount);
}
/**
* @dev Allows Schain owner to return each user their ETH.
*
* Requirements:
*
* - Amount of ETH on schain should be equal or more than transferred amount.
* - Receiver address must not be null.
* - msg.sender should be an owner of schain
* - IMA transfers Mainnet <-> schain should be killed
*/
function getFunds(string calldata schainName, address payable receiver, uint amount)
external
override
onlySchainOwner(schainName)
whenKilled(keccak256(abi.encodePacked(schainName)))
{
require(receiver != address(0), "Receiver address has to be set");
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(transferredAmount[schainHash] >= amount, "Incorrect amount");
_removeTransferredAmount(schainHash, amount);
receiver.sendValue(amount);
}
/**
* @dev Allows Schain owner to switch on or switch off active eth transfers.
*
* Requirements:
*
* - msg.sender should be an owner of schain
* - IMA transfers Mainnet <-> schain should be killed
*/
function enableActiveEthTransfers(string calldata schainName)
external
override
onlySchainOwner(schainName)
whenNotKilled(keccak256(abi.encodePacked(schainName)))
{
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(!activeEthTransfers[schainHash], "Active eth transfers enabled");
emit ActiveEthTransfers(schainHash, true);
activeEthTransfers[schainHash] = true;
}
/**
* @dev Allows Schain owner to switch on or switch off active eth transfers.
*
* Requirements:
*
* - msg.sender should be an owner of schain
* - IMA transfers Mainnet <-> schain should be killed
*/
function disableActiveEthTransfers(string calldata schainName)
external
override
onlySchainOwner(schainName)
whenNotKilled(keccak256(abi.encodePacked(schainName)))
{
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(activeEthTransfers[schainHash], "Active eth transfers disabled");
emit ActiveEthTransfers(schainHash, false);
activeEthTransfers[schainHash] = false;
}
/**
* @dev Returns receiver of message.
*
* Requirements:
*
* - Sender contract should be defined and schain name cannot be `Mainnet`.
*/
function gasPayer(
bytes32 schainHash,
address sender,
bytes calldata data
)
external
view
override
checkReceiverChain(schainHash, sender)
returns (address)
{
Messages.TransferEthMessage memory message = Messages.decodeTransferEthMessage(data);
return message.receiver;
}
/**
* @dev Creates a new DepositBoxEth contract.
*/
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
ILinker linkerValue,
IMessageProxyForMainnet messageProxyValue
)
public
override(DepositBox, IDepositBox)
initializer
{
DepositBox.initialize(contractManagerOfSkaleManagerValue, linkerValue, messageProxyValue);
}
/**
* @dev Saves amount of ETH that was transferred to schain.
*/
function _saveTransferredAmount(bytes32 schainHash, uint256 amount) private {
transferredAmount[schainHash] += amount;
}
/**
* @dev Removes amount of ETH that was transferred from schain.
*/
function _removeTransferredAmount(bytes32 schainHash, uint256 amount) private {
transferredAmount[schainHash] -= amount;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @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;
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");
(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");
(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");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal 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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* IDepositBoxEth.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "../IDepositBox.sol";
interface IDepositBoxEth is IDepositBox {
receive() external payable;
function deposit(string memory schainName) external payable;
function getMyEth() external;
function getFunds(string calldata schainName, address payable receiver, uint amount) external;
function enableActiveEthTransfers(string calldata schainName) external;
function disableActiveEthTransfers(string calldata schainName) external;
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* DepositBox.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Artem Payvin
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@skalenetwork/ima-interfaces/mainnet/IDepositBox.sol";
import "./Twin.sol";
/**
* @title DepositBox
* @dev Abstract contracts for DepositBoxes on mainnet.
*/
abstract contract DepositBox is IDepositBox, Twin {
ILinker public linker;
// schainHash => true if automatic deployment tokens on schain was enabled
mapping(bytes32 => bool) private _automaticDeploy;
bytes32 public constant DEPOSIT_BOX_MANAGER_ROLE = keccak256("DEPOSIT_BOX_MANAGER_ROLE");
/**
* @dev Modifier for checking whether schain was not killed.
*/
modifier whenNotKilled(bytes32 schainHash) {
require(linker.isNotKilled(schainHash), "Schain is killed");
_;
}
/**
* @dev Modifier for checking whether schain was killed.
*/
modifier whenKilled(bytes32 schainHash) {
require(!linker.isNotKilled(schainHash), "Schain is not killed");
_;
}
/**
* @dev Modifier for checking whether schainName is not equal to `Mainnet`
* and address of receiver is not equal to null before transferring funds from mainnet to schain.
*/
modifier rightTransaction(string memory schainName, address to) {
require(
keccak256(abi.encodePacked(schainName)) != keccak256(abi.encodePacked("Mainnet")),
"SKALE chain name cannot be Mainnet"
);
require(to != address(0), "Receiver address cannot be null");
_;
}
/**
* @dev Modifier for checking whether schainHash is not equal to `Mainnet`
* and sender contract was added as contract processor on schain.
*/
modifier checkReceiverChain(bytes32 schainHash, address sender) {
require(
schainHash != keccak256(abi.encodePacked("Mainnet")) &&
sender == schainLinks[schainHash],
"Receiver chain is incorrect"
);
_;
}
/**
* @dev Allows Schain owner turn on whitelist of tokens.
*/
function enableWhitelist(string memory schainName) external override onlySchainOwner(schainName) {
_automaticDeploy[keccak256(abi.encodePacked(schainName))] = false;
}
/**
* @dev Allows Schain owner turn off whitelist of tokens.
*/
function disableWhitelist(string memory schainName) external override onlySchainOwner(schainName) {
_automaticDeploy[keccak256(abi.encodePacked(schainName))] = true;
}
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
ILinker newLinker,
IMessageProxyForMainnet messageProxyValue
)
public
override
virtual
initializer
{
Twin.initialize(contractManagerOfSkaleManagerValue, messageProxyValue);
_setupRole(LINKER_ROLE, address(newLinker));
linker = newLinker;
}
/**
* @dev Returns is whitelist enabled on schain.
*/
function isWhitelisted(string memory schainName) public view override returns (bool) {
return !_automaticDeploy[keccak256(abi.encodePacked(schainName))];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* Messages.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
/**
* @title Messages
* @dev Library for encoding and decoding messages
* for transferring from Mainnet to Schain and vice versa.
*/
library Messages {
/**
* @dev Enumerator that describes all supported message types.
*/
enum MessageType {
EMPTY,
TRANSFER_ETH,
TRANSFER_ERC20,
TRANSFER_ERC20_AND_TOTAL_SUPPLY,
TRANSFER_ERC20_AND_TOKEN_INFO,
TRANSFER_ERC721,
TRANSFER_ERC721_AND_TOKEN_INFO,
USER_STATUS,
INTERCHAIN_CONNECTION,
TRANSFER_ERC1155,
TRANSFER_ERC1155_AND_TOKEN_INFO,
TRANSFER_ERC1155_BATCH,
TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO,
TRANSFER_ERC721_WITH_METADATA,
TRANSFER_ERC721_WITH_METADATA_AND_TOKEN_INFO
}
/**
* @dev Structure for base message.
*/
struct BaseMessage {
MessageType messageType;
}
/**
* @dev Structure for describing ETH.
*/
struct TransferEthMessage {
BaseMessage message;
address receiver;
uint256 amount;
}
/**
* @dev Structure for user status.
*/
struct UserStatusMessage {
BaseMessage message;
address receiver;
bool isActive;
}
/**
* @dev Structure for describing ERC20 token.
*/
struct TransferErc20Message {
BaseMessage message;
address token;
address receiver;
uint256 amount;
}
/**
* @dev Structure for describing additional data for ERC20 token.
*/
struct Erc20TokenInfo {
string name;
uint8 decimals;
string symbol;
}
/**
* @dev Structure for describing ERC20 with token supply.
*/
struct TransferErc20AndTotalSupplyMessage {
TransferErc20Message baseErc20transfer;
uint256 totalSupply;
}
/**
* @dev Structure for describing ERC20 with token info.
*/
struct TransferErc20AndTokenInfoMessage {
TransferErc20Message baseErc20transfer;
uint256 totalSupply;
Erc20TokenInfo tokenInfo;
}
/**
* @dev Structure for describing base ERC721.
*/
struct TransferErc721Message {
BaseMessage message;
address token;
address receiver;
uint256 tokenId;
}
/**
* @dev Structure for describing base ERC721 with metadata.
*/
struct TransferErc721MessageWithMetadata {
TransferErc721Message erc721message;
string tokenURI;
}
/**
* @dev Structure for describing ERC20 with token info.
*/
struct Erc721TokenInfo {
string name;
string symbol;
}
/**
* @dev Structure for describing additional data for ERC721 token.
*/
struct TransferErc721AndTokenInfoMessage {
TransferErc721Message baseErc721transfer;
Erc721TokenInfo tokenInfo;
}
/**
* @dev Structure for describing additional data for ERC721 token with metadata.
*/
struct TransferErc721WithMetadataAndTokenInfoMessage {
TransferErc721MessageWithMetadata baseErc721transferWithMetadata;
Erc721TokenInfo tokenInfo;
}
/**
* @dev Structure for describing whether interchain connection is allowed.
*/
struct InterchainConnectionMessage {
BaseMessage message;
bool isAllowed;
}
/**
* @dev Structure for describing whether interchain connection is allowed.
*/
struct TransferErc1155Message {
BaseMessage message;
address token;
address receiver;
uint256 id;
uint256 amount;
}
/**
* @dev Structure for describing ERC1155 token in batches.
*/
struct TransferErc1155BatchMessage {
BaseMessage message;
address token;
address receiver;
uint256[] ids;
uint256[] amounts;
}
/**
* @dev Structure for describing ERC1155 token info.
*/
struct Erc1155TokenInfo {
string uri;
}
/**
* @dev Structure for describing message for transferring ERC1155 token with info.
*/
struct TransferErc1155AndTokenInfoMessage {
TransferErc1155Message baseErc1155transfer;
Erc1155TokenInfo tokenInfo;
}
/**
* @dev Structure for describing message for transferring ERC1155 token in batches with info.
*/
struct TransferErc1155BatchAndTokenInfoMessage {
TransferErc1155BatchMessage baseErc1155Batchtransfer;
Erc1155TokenInfo tokenInfo;
}
/**
* @dev Returns type of message for encoded data.
*/
function getMessageType(bytes calldata data) internal pure returns (MessageType) {
uint256 firstWord = abi.decode(data, (uint256));
if (firstWord % 32 == 0) {
return getMessageType(data[firstWord:]);
} else {
return abi.decode(data, (Messages.MessageType));
}
}
/**
* @dev Encodes message for transferring ETH. Returns encoded message.
*/
function encodeTransferEthMessage(address receiver, uint256 amount) internal pure returns (bytes memory) {
TransferEthMessage memory message = TransferEthMessage(
BaseMessage(MessageType.TRANSFER_ETH),
receiver,
amount
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ETH. Returns structure `TransferEthMessage`.
*/
function decodeTransferEthMessage(
bytes calldata data
) internal pure returns (TransferEthMessage memory) {
require(getMessageType(data) == MessageType.TRANSFER_ETH, "Message type is not ETH transfer");
return abi.decode(data, (TransferEthMessage));
}
/**
* @dev Encodes message for transferring ETH. Returns encoded message.
*/
function encodeTransferErc20Message(
address token,
address receiver,
uint256 amount
) internal pure returns (bytes memory) {
TransferErc20Message memory message = TransferErc20Message(
BaseMessage(MessageType.TRANSFER_ERC20),
token,
receiver,
amount
);
return abi.encode(message);
}
/**
* @dev Encodes message for transferring ERC20 with total supply. Returns encoded message.
*/
function encodeTransferErc20AndTotalSupplyMessage(
address token,
address receiver,
uint256 amount,
uint256 totalSupply
) internal pure returns (bytes memory) {
TransferErc20AndTotalSupplyMessage memory message = TransferErc20AndTotalSupplyMessage(
TransferErc20Message(
BaseMessage(MessageType.TRANSFER_ERC20_AND_TOTAL_SUPPLY),
token,
receiver,
amount
),
totalSupply
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC20. Returns structure `TransferErc20Message`.
*/
function decodeTransferErc20Message(
bytes calldata data
) internal pure returns (TransferErc20Message memory) {
require(getMessageType(data) == MessageType.TRANSFER_ERC20, "Message type is not ERC20 transfer");
return abi.decode(data, (TransferErc20Message));
}
/**
* @dev Decodes message for transferring ERC20 with total supply.
* Returns structure `TransferErc20AndTotalSupplyMessage`.
*/
function decodeTransferErc20AndTotalSupplyMessage(
bytes calldata data
) internal pure returns (TransferErc20AndTotalSupplyMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC20_AND_TOTAL_SUPPLY,
"Message type is not ERC20 transfer and total supply"
);
return abi.decode(data, (TransferErc20AndTotalSupplyMessage));
}
/**
* @dev Encodes message for transferring ERC20 with token info.
* Returns encoded message.
*/
function encodeTransferErc20AndTokenInfoMessage(
address token,
address receiver,
uint256 amount,
uint256 totalSupply,
Erc20TokenInfo memory tokenInfo
) internal pure returns (bytes memory) {
TransferErc20AndTokenInfoMessage memory message = TransferErc20AndTokenInfoMessage(
TransferErc20Message(
BaseMessage(MessageType.TRANSFER_ERC20_AND_TOKEN_INFO),
token,
receiver,
amount
),
totalSupply,
tokenInfo
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC20 with token info.
* Returns structure `TransferErc20AndTokenInfoMessage`.
*/
function decodeTransferErc20AndTokenInfoMessage(
bytes calldata data
) internal pure returns (TransferErc20AndTokenInfoMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC20_AND_TOKEN_INFO,
"Message type is not ERC20 transfer with token info"
);
return abi.decode(data, (TransferErc20AndTokenInfoMessage));
}
/**
* @dev Encodes message for transferring ERC721.
* Returns encoded message.
*/
function encodeTransferErc721Message(
address token,
address receiver,
uint256 tokenId
) internal pure returns (bytes memory) {
TransferErc721Message memory message = TransferErc721Message(
BaseMessage(MessageType.TRANSFER_ERC721),
token,
receiver,
tokenId
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC721.
* Returns structure `TransferErc721Message`.
*/
function decodeTransferErc721Message(
bytes calldata data
) internal pure returns (TransferErc721Message memory) {
require(getMessageType(data) == MessageType.TRANSFER_ERC721, "Message type is not ERC721 transfer");
return abi.decode(data, (TransferErc721Message));
}
/**
* @dev Encodes message for transferring ERC721 with token info.
* Returns encoded message.
*/
function encodeTransferErc721AndTokenInfoMessage(
address token,
address receiver,
uint256 tokenId,
Erc721TokenInfo memory tokenInfo
) internal pure returns (bytes memory) {
TransferErc721AndTokenInfoMessage memory message = TransferErc721AndTokenInfoMessage(
TransferErc721Message(
BaseMessage(MessageType.TRANSFER_ERC721_AND_TOKEN_INFO),
token,
receiver,
tokenId
),
tokenInfo
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC721 with token info.
* Returns structure `TransferErc721AndTokenInfoMessage`.
*/
function decodeTransferErc721AndTokenInfoMessage(
bytes calldata data
) internal pure returns (TransferErc721AndTokenInfoMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC721_AND_TOKEN_INFO,
"Message type is not ERC721 transfer with token info"
);
return abi.decode(data, (TransferErc721AndTokenInfoMessage));
}
/**
* @dev Encodes message for transferring ERC721.
* Returns encoded message.
*/
function encodeTransferErc721MessageWithMetadata(
address token,
address receiver,
uint256 tokenId,
string memory tokenURI
) internal pure returns (bytes memory) {
TransferErc721MessageWithMetadata memory message = TransferErc721MessageWithMetadata(
TransferErc721Message(
BaseMessage(MessageType.TRANSFER_ERC721_WITH_METADATA),
token,
receiver,
tokenId
),
tokenURI
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC721.
* Returns structure `TransferErc721MessageWithMetadata`.
*/
function decodeTransferErc721MessageWithMetadata(
bytes calldata data
) internal pure returns (TransferErc721MessageWithMetadata memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC721_WITH_METADATA,
"Message type is not ERC721 transfer"
);
return abi.decode(data, (TransferErc721MessageWithMetadata));
}
/**
* @dev Encodes message for transferring ERC721 with token info.
* Returns encoded message.
*/
function encodeTransferErc721WithMetadataAndTokenInfoMessage(
address token,
address receiver,
uint256 tokenId,
string memory tokenURI,
Erc721TokenInfo memory tokenInfo
) internal pure returns (bytes memory) {
TransferErc721WithMetadataAndTokenInfoMessage memory message = TransferErc721WithMetadataAndTokenInfoMessage(
TransferErc721MessageWithMetadata(
TransferErc721Message(
BaseMessage(MessageType.TRANSFER_ERC721_WITH_METADATA_AND_TOKEN_INFO),
token,
receiver,
tokenId
),
tokenURI
),
tokenInfo
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC721 with token info.
* Returns structure `TransferErc721WithMetadataAndTokenInfoMessage`.
*/
function decodeTransferErc721WithMetadataAndTokenInfoMessage(
bytes calldata data
) internal pure returns (TransferErc721WithMetadataAndTokenInfoMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC721_WITH_METADATA_AND_TOKEN_INFO,
"Message type is not ERC721 transfer with token info"
);
return abi.decode(data, (TransferErc721WithMetadataAndTokenInfoMessage));
}
/**
* @dev Encodes message for activating user on schain.
* Returns encoded message.
*/
function encodeActivateUserMessage(address receiver) internal pure returns (bytes memory){
return _encodeUserStatusMessage(receiver, true);
}
/**
* @dev Encodes message for locking user on schain.
* Returns encoded message.
*/
function encodeLockUserMessage(address receiver) internal pure returns (bytes memory){
return _encodeUserStatusMessage(receiver, false);
}
/**
* @dev Decodes message for user status.
* Returns structure UserStatusMessage.
*/
function decodeUserStatusMessage(bytes calldata data) internal pure returns (UserStatusMessage memory) {
require(getMessageType(data) == MessageType.USER_STATUS, "Message type is not User Status");
return abi.decode(data, (UserStatusMessage));
}
/**
* @dev Encodes message for allowing interchain connection.
* Returns encoded message.
*/
function encodeInterchainConnectionMessage(bool isAllowed) internal pure returns (bytes memory) {
InterchainConnectionMessage memory message = InterchainConnectionMessage(
BaseMessage(MessageType.INTERCHAIN_CONNECTION),
isAllowed
);
return abi.encode(message);
}
/**
* @dev Decodes message for allowing interchain connection.
* Returns structure `InterchainConnectionMessage`.
*/
function decodeInterchainConnectionMessage(bytes calldata data)
internal
pure
returns (InterchainConnectionMessage memory)
{
require(getMessageType(data) == MessageType.INTERCHAIN_CONNECTION, "Message type is not Interchain connection");
return abi.decode(data, (InterchainConnectionMessage));
}
/**
* @dev Encodes message for transferring ERC1155 token.
* Returns encoded message.
*/
function encodeTransferErc1155Message(
address token,
address receiver,
uint256 id,
uint256 amount
) internal pure returns (bytes memory) {
TransferErc1155Message memory message = TransferErc1155Message(
BaseMessage(MessageType.TRANSFER_ERC1155),
token,
receiver,
id,
amount
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC1155 token.
* Returns structure `TransferErc1155Message`.
*/
function decodeTransferErc1155Message(
bytes calldata data
) internal pure returns (TransferErc1155Message memory) {
require(getMessageType(data) == MessageType.TRANSFER_ERC1155, "Message type is not ERC1155 transfer");
return abi.decode(data, (TransferErc1155Message));
}
/**
* @dev Encodes message for transferring ERC1155 with token info.
* Returns encoded message.
*/
function encodeTransferErc1155AndTokenInfoMessage(
address token,
address receiver,
uint256 id,
uint256 amount,
Erc1155TokenInfo memory tokenInfo
) internal pure returns (bytes memory) {
TransferErc1155AndTokenInfoMessage memory message = TransferErc1155AndTokenInfoMessage(
TransferErc1155Message(
BaseMessage(MessageType.TRANSFER_ERC1155_AND_TOKEN_INFO),
token,
receiver,
id,
amount
),
tokenInfo
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC1155 with token info.
* Returns structure `TransferErc1155AndTokenInfoMessage`.
*/
function decodeTransferErc1155AndTokenInfoMessage(
bytes calldata data
) internal pure returns (TransferErc1155AndTokenInfoMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC1155_AND_TOKEN_INFO,
"Message type is not ERC1155AndTokenInfo transfer"
);
return abi.decode(data, (TransferErc1155AndTokenInfoMessage));
}
/**
* @dev Encodes message for transferring ERC1155 token in batches.
* Returns encoded message.
*/
function encodeTransferErc1155BatchMessage(
address token,
address receiver,
uint256[] memory ids,
uint256[] memory amounts
) internal pure returns (bytes memory) {
TransferErc1155BatchMessage memory message = TransferErc1155BatchMessage(
BaseMessage(MessageType.TRANSFER_ERC1155_BATCH),
token,
receiver,
ids,
amounts
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC1155 token in batches.
* Returns structure `TransferErc1155BatchMessage`.
*/
function decodeTransferErc1155BatchMessage(
bytes calldata data
) internal pure returns (TransferErc1155BatchMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC1155_BATCH,
"Message type is not ERC1155Batch transfer"
);
return abi.decode(data, (TransferErc1155BatchMessage));
}
/**
* @dev Encodes message for transferring ERC1155 token in batches with token info.
* Returns encoded message.
*/
function encodeTransferErc1155BatchAndTokenInfoMessage(
address token,
address receiver,
uint256[] memory ids,
uint256[] memory amounts,
Erc1155TokenInfo memory tokenInfo
) internal pure returns (bytes memory) {
TransferErc1155BatchAndTokenInfoMessage memory message = TransferErc1155BatchAndTokenInfoMessage(
TransferErc1155BatchMessage(
BaseMessage(MessageType.TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO),
token,
receiver,
ids,
amounts
),
tokenInfo
);
return abi.encode(message);
}
/**
* @dev Decodes message for transferring ERC1155 token in batches with token info.
* Returns structure `TransferErc1155BatchAndTokenInfoMessage`.
*/
function decodeTransferErc1155BatchAndTokenInfoMessage(
bytes calldata data
) internal pure returns (TransferErc1155BatchAndTokenInfoMessage memory) {
require(
getMessageType(data) == MessageType.TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO,
"Message type is not ERC1155BatchAndTokenInfo transfer"
);
return abi.decode(data, (TransferErc1155BatchAndTokenInfoMessage));
}
/**
* @dev Encodes message for transferring user status on schain.
* Returns encoded message.
*/
function _encodeUserStatusMessage(address receiver, bool isActive) private pure returns (bytes memory) {
UserStatusMessage memory message = UserStatusMessage(
BaseMessage(MessageType.USER_STATUS),
receiver,
isActive
);
return abi.encode(message);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* IDepositBox.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "@skalenetwork/skale-manager-interfaces/IContractManager.sol";
import "../IGasReimbursable.sol";
import "../IMessageReceiver.sol";
import "./ILinker.sol";
import "./IMessageProxyForMainnet.sol";
import "./ITwin.sol";
interface IDepositBox is ITwin, IMessageReceiver, IGasReimbursable {
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
ILinker newLinker,
IMessageProxyForMainnet messageProxyValue
) external;
function enableWhitelist(string memory schainName) external;
function disableWhitelist(string memory schainName) external;
function isWhitelisted(string memory schainName) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IContractManager.sol - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IContractManager {
/**
* @dev Emitted when contract is upgraded.
*/
event ContractUpgraded(string contractsName, address contractsAddress);
function initialize() external;
function setContractsAddress(string calldata contractsName, address newContractsAddress) external;
function contracts(bytes32 nameHash) external view returns (address);
function getDelegationPeriodManager() external view returns (address);
function getBounty() external view returns (address);
function getValidatorService() external view returns (address);
function getTimeHelpers() external view returns (address);
function getConstantsHolder() external view returns (address);
function getSkaleToken() external view returns (address);
function getTokenState() external view returns (address);
function getPunisher() external view returns (address);
function getContract(string calldata name) external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* IGasReimbursable.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Artem Payvin
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "./IMessageReceiver.sol";
interface IGasReimbursable is IMessageReceiver {
function gasPayer(
bytes32 schainHash,
address sender,
bytes calldata data
)
external
returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* IMessageReceiver.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IMessageReceiver {
function postMessage(
bytes32 schainHash,
address sender,
bytes calldata data
)
external;
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* ILinker.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "./ITwin.sol";
interface ILinker is ITwin {
function registerMainnetContract(address newMainnetContract) external;
function removeMainnetContract(address mainnetContract) external;
function connectSchain(string calldata schainName, address[] calldata schainContracts) external;
function kill(string calldata schainName) external;
function disconnectSchain(string calldata schainName) external;
function isNotKilled(bytes32 schainHash) external view returns (bool);
function hasMainnetContract(address mainnetContract) external view returns (bool);
function hasSchain(string calldata schainName) external view returns (bool connected);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* IMessageProxyForMainnet.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "../IMessageProxy.sol";
import "./ICommunityPool.sol";
interface IMessageProxyForMainnet is IMessageProxy {
function setCommunityPool(ICommunityPool newCommunityPoolAddress) external;
function setNewHeaderMessageGasCost(uint256 newHeaderMessageGasCost) external;
function setNewMessageGasCost(uint256 newMessageGasCost) external;
function messageInProgress() external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* ITwin.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "./ISkaleManagerClient.sol";
interface ITwin is ISkaleManagerClient {
function addSchainContract(string calldata schainName, address contractReceiver) external;
function removeSchainContract(string calldata schainName) external;
function hasSchainContract(string calldata schainName) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* ISkaleManagerClient.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "@skalenetwork/skale-manager-interfaces/IContractManager.sol";
interface ISkaleManagerClient {
function initialize(IContractManager newContractManagerOfSkaleManager) external;
function isSchainOwner(address sender, bytes32 schainHash) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* IMessageProxy.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IMessageProxy {
/**
* @dev Structure that describes message. Should contain sender of message,
* destination contract on schain that will receiver message,
* data that contains all needed info about token or ETH.
*/
struct Message {
address sender;
address destinationContract;
bytes data;
}
/**
* @dev Structure that contains fields for bls signature.
*/
struct Signature {
uint256[2] blsSignature;
uint256 hashA;
uint256 hashB;
uint256 counter;
}
function addConnectedChain(string calldata schainName) external;
function postIncomingMessages(
string calldata fromSchainName,
uint256 startingCounter,
Message[] calldata messages,
Signature calldata sign
) external;
function setNewGasLimit(uint256 newGasLimit) external;
function registerExtraContractForAll(address extraContract) external;
function removeExtraContractForAll(address extraContract) external;
function removeConnectedChain(string memory schainName) external;
function postOutgoingMessage(
bytes32 targetChainHash,
address targetContract,
bytes memory data
) external;
function registerExtraContract(string memory chainName, address extraContract) external;
function removeExtraContract(string memory schainName, address extraContract) external;
function setVersion(string calldata newVersion) external;
function isContractRegistered(
bytes32 schainHash,
address contractAddress
) external view returns (bool);
function getContractRegisteredLength(bytes32 schainHash) external view returns (uint256);
function getContractRegisteredRange(
bytes32 schainHash,
uint256 from,
uint256 to
)
external
view
returns (address[] memory);
function getOutgoingMessagesCounter(string calldata targetSchainName) external view returns (uint256);
function getIncomingMessagesCounter(string calldata fromSchainName) external view returns (uint256);
function isConnectedChain(string memory schainName) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* ICommunityPool.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
import "@skalenetwork/skale-manager-interfaces/IContractManager.sol";
import "./ILinker.sol";
import "./IMessageProxyForMainnet.sol";
import "./ITwin.sol";
interface ICommunityPool is ITwin {
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
ILinker linker,
IMessageProxyForMainnet messageProxyValue
) external;
function refundGasByUser(bytes32 schainHash, address payable node, address user, uint gas) external returns (uint);
function rechargeUserWallet(string calldata schainName, address user) external payable;
function withdrawFunds(string calldata schainName, uint amount) external;
function setMinTransactionGas(uint newMinTransactionGas) external;
function refundGasBySchainWallet(
bytes32 schainHash,
address payable node,
uint gas
) external returns (bool);
function getBalance(address user, string calldata schainName) external view returns (uint);
function checkUserBalance(bytes32 schainHash, address receiver) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* Twin.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Artem Payvin
* @author Dmytro Stebaiev
* @author Vadim Yavorsky
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@skalenetwork/ima-interfaces/mainnet/ITwin.sol";
import "./MessageProxyForMainnet.sol";
import "./SkaleManagerClient.sol";
/**
* @title Twin
* @dev Runs on Mainnet,
* contains logic for connecting paired contracts on Mainnet and on Schain.
*/
abstract contract Twin is SkaleManagerClient, ITwin {
IMessageProxyForMainnet public messageProxy;
mapping(bytes32 => address) public schainLinks;
bytes32 public constant LINKER_ROLE = keccak256("LINKER_ROLE");
/**
* @dev Modifier for checking whether caller is MessageProxy contract.
*/
modifier onlyMessageProxy() {
require(msg.sender == address(messageProxy), "Sender is not a MessageProxy");
_;
}
/**
* @dev Binds a contract on mainnet with their twin on schain.
*
* Requirements:
*
* - `msg.sender` must be schain owner or has required role.
* - SKALE chain must not already be added.
* - Address of contract on schain must be non-zero.
*/
function addSchainContract(string calldata schainName, address contractReceiver) external override {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(
hasRole(LINKER_ROLE, msg.sender) ||
isSchainOwner(msg.sender, schainHash), "Not authorized caller"
);
require(schainLinks[schainHash] == address(0), "SKALE chain is already set");
require(contractReceiver != address(0), "Incorrect address of contract receiver on Schain");
schainLinks[schainHash] = contractReceiver;
}
/**
* @dev Removes connection with contract on schain.
*
* Requirements:
*
* - `msg.sender` must be schain owner or has required role.
* - SKALE chain must already be set.
*/
function removeSchainContract(string calldata schainName) external override {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(
hasRole(LINKER_ROLE, msg.sender) ||
isSchainOwner(msg.sender, schainHash), "Not authorized caller"
);
require(schainLinks[schainHash] != address(0), "SKALE chain is not set");
delete schainLinks[schainHash];
}
/**
* @dev Returns true if mainnet contract and schain contract are connected together for transferring messages.
*/
function hasSchainContract(string calldata schainName) external view override returns (bool) {
return schainLinks[keccak256(abi.encodePacked(schainName))] != address(0);
}
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
IMessageProxyForMainnet newMessageProxy
)
public
virtual
initializer
{
SkaleManagerClient.initialize(contractManagerOfSkaleManagerValue);
messageProxy = newMessageProxy;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* MessageProxyForMainnet.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2019-Present SKALE Labs
* @author Artem Payvin
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@skalenetwork/skale-manager-interfaces/IWallets.sol";
import "@skalenetwork/skale-manager-interfaces/ISchains.sol";
import "@skalenetwork/ima-interfaces/mainnet/IMessageProxyForMainnet.sol";
import "@skalenetwork/ima-interfaces/mainnet/ICommunityPool.sol";
import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol";
import "../MessageProxy.sol";
import "./SkaleManagerClient.sol";
import "./CommunityPool.sol";
interface IMessageProxyForMainnetInitializeFunction is IMessageProxyForMainnet {
function initializeAllRegisteredContracts(
bytes32 schainHash,
address[] calldata contracts
) external;
}
/**
* @title Message Proxy for Mainnet
* @dev Runs on Mainnet, contains functions to manage the incoming messages from
* `targetSchainName` and outgoing messages to `fromSchainName`. Every SKALE chain with
* IMA is therefore connected to MessageProxyForMainnet.
*
* Messages from SKALE chains are signed using BLS threshold signatures from the
* nodes in the chain. Since Ethereum Mainnet has no BLS public key, mainnet
* messages do not need to be signed.
*/
contract MessageProxyForMainnet is SkaleManagerClient, MessageProxy, IMessageProxyForMainnetInitializeFunction {
using AddressUpgradeable for address;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
/**
* 16 Agents
* Synchronize time with time.nist.gov
* Every agent checks if it is their time slot
* Time slots are in increments of 10 seconds
* At the start of their slot each agent:
* For each connected schain:
* Read incoming counter on the dst chain
* Read outgoing counter on the src chain
* Calculate the difference outgoing - incoming
* Call postIncomingMessages function passing (un)signed message array
* ID of this schain, Chain 0 represents ETH mainnet,
*/
ICommunityPool public communityPool;
uint256 public headerMessageGasCost;
uint256 public messageGasCost;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _registryContracts;
string public version;
bool public override messageInProgress;
/**
* @dev Emitted when gas cost for message header was changed.
*/
event GasCostMessageHeaderWasChanged(
uint256 oldValue,
uint256 newValue
);
/**
* @dev Emitted when gas cost for message was changed.
*/
event GasCostMessageWasChanged(
uint256 oldValue,
uint256 newValue
);
/**
* @dev Reentrancy guard for postIncomingMessages.
*/
modifier messageInProgressLocker() {
require(!messageInProgress, "Message is in progress");
messageInProgress = true;
_;
messageInProgress = false;
}
/**
* @dev Allows DEFAULT_ADMIN_ROLE to initialize registered contracts
* Notice - this function will be executed only once during upgrade
*
* Requirements:
*
* `msg.sender` should have DEFAULT_ADMIN_ROLE
*/
function initializeAllRegisteredContracts(
bytes32 schainHash,
address[] calldata contracts
) external override {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Sender is not authorized");
for (uint256 i = 0; i < contracts.length; i++) {
if (
deprecatedRegistryContracts[schainHash][contracts[i]] &&
!_registryContracts[schainHash].contains(contracts[i])
) {
_registryContracts[schainHash].add(contracts[i]);
delete deprecatedRegistryContracts[schainHash][contracts[i]];
}
}
}
/**
* @dev Allows `msg.sender` to connect schain with MessageProxyOnMainnet for transferring messages.
*
* Requirements:
*
* - Schain name must not be `Mainnet`.
*/
function addConnectedChain(string calldata schainName) external override {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(ISchainsInternal(
contractManagerOfSkaleManager.getContract("SchainsInternal")
).isSchainExist(schainHash), "SKALE chain must exist");
_addConnectedChain(schainHash);
}
/**
* @dev Allows owner of the contract to set CommunityPool address for gas reimbursement.
*
* Requirements:
*
* - `msg.sender` must be granted as DEFAULT_ADMIN_ROLE.
* - Address of CommunityPool contract must not be null.
*/
function setCommunityPool(ICommunityPool newCommunityPoolAddress) external override {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Not authorized caller");
require(address(newCommunityPoolAddress) != address(0), "CommunityPool address has to be set");
communityPool = newCommunityPoolAddress;
}
/**
* @dev Allows `msg.sender` to register extra contract for being able to transfer messages from custom contracts.
*
* Requirements:
*
* - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE.
* - Schain name must not be `Mainnet`.
*/
function registerExtraContract(string memory schainName, address extraContract) external override {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(
hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender) ||
isSchainOwner(msg.sender, schainHash),
"Not enough permissions to register extra contract"
);
require(schainHash != MAINNET_HASH, "Schain hash can not be equal Mainnet");
_registerExtraContract(schainHash, extraContract);
}
/**
* @dev Allows `msg.sender` to remove extra contract,
* thus `extraContract` will no longer be available to transfer messages from mainnet to schain.
*
* Requirements:
*
* - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE.
* - Schain name must not be `Mainnet`.
*/
function removeExtraContract(string memory schainName, address extraContract) external override {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(
hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender) ||
isSchainOwner(msg.sender, schainHash),
"Not enough permissions to register extra contract"
);
require(schainHash != MAINNET_HASH, "Schain hash can not be equal Mainnet");
_removeExtraContract(schainHash, extraContract);
}
/**
* @dev Posts incoming message from `fromSchainName`.
*
* Requirements:
*
* - `msg.sender` must be authorized caller.
* - `fromSchainName` must be initialized.
* - `startingCounter` must be equal to the chain's incoming message counter.
* - If destination chain is Mainnet, message signature must be valid.
*/
function postIncomingMessages(
string calldata fromSchainName,
uint256 startingCounter,
Message[] calldata messages,
Signature calldata sign
)
external
override(IMessageProxy, MessageProxy)
messageInProgressLocker
{
uint256 gasTotal = gasleft();
bytes32 fromSchainHash = keccak256(abi.encodePacked(fromSchainName));
require(_checkSchainBalance(fromSchainHash), "Schain wallet has not enough funds");
require(connectedChains[fromSchainHash].inited, "Chain is not initialized");
require(messages.length <= MESSAGES_LENGTH, "Too many messages");
require(
startingCounter == connectedChains[fromSchainHash].incomingMessageCounter,
"Starting counter is not equal to incoming message counter");
require(_verifyMessages(
fromSchainName,
_hashedArray(messages, startingCounter, fromSchainName), sign),
"Signature is not verified");
uint additionalGasPerMessage =
(gasTotal - gasleft() + headerMessageGasCost + messages.length * messageGasCost) / messages.length;
uint notReimbursedGas = 0;
connectedChains[fromSchainHash].incomingMessageCounter += messages.length;
for (uint256 i = 0; i < messages.length; i++) {
gasTotal = gasleft();
if (isContractRegistered(bytes32(0), messages[i].destinationContract)) {
address receiver = _getGasPayer(fromSchainHash, messages[i], startingCounter + i);
_callReceiverContract(fromSchainHash, messages[i], startingCounter + i);
notReimbursedGas += communityPool.refundGasByUser(
fromSchainHash,
payable(msg.sender),
receiver,
gasTotal - gasleft() + additionalGasPerMessage
);
} else {
_callReceiverContract(fromSchainHash, messages[i], startingCounter + i);
notReimbursedGas += gasTotal - gasleft() + additionalGasPerMessage;
}
}
communityPool.refundGasBySchainWallet(fromSchainHash, payable(msg.sender), notReimbursedGas);
}
/**
* @dev Sets headerMessageGasCost to a new value.
*
* Requirements:
*
* - `msg.sender` must be granted as CONSTANT_SETTER_ROLE.
*/
function setNewHeaderMessageGasCost(uint256 newHeaderMessageGasCost) external override onlyConstantSetter {
emit GasCostMessageHeaderWasChanged(headerMessageGasCost, newHeaderMessageGasCost);
headerMessageGasCost = newHeaderMessageGasCost;
}
/**
* @dev Sets messageGasCost to a new value.
*
* Requirements:
*
* - `msg.sender` must be granted as CONSTANT_SETTER_ROLE.
*/
function setNewMessageGasCost(uint256 newMessageGasCost) external override onlyConstantSetter {
emit GasCostMessageWasChanged(messageGasCost, newMessageGasCost);
messageGasCost = newMessageGasCost;
}
/**
* @dev Sets new version of contracts on mainnet
*
* Requirements:
*
* - `msg.sender` must be granted DEFAULT_ADMIN_ROLE.
*/
function setVersion(string calldata newVersion) external override {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "DEFAULT_ADMIN_ROLE is required");
emit VersionUpdated(version, newVersion);
version = newVersion;
}
/**
* @dev Creates a new MessageProxyForMainnet contract.
*/
function initialize(IContractManager contractManagerOfSkaleManagerValue) public virtual override initializer {
SkaleManagerClient.initialize(contractManagerOfSkaleManagerValue);
MessageProxy.initializeMessageProxy(1e6);
headerMessageGasCost = 73800;
messageGasCost = 9000;
}
/**
* @dev Checks whether chain is currently connected.
*
* Note: Mainnet chain does not have a public key, and is implicitly
* connected to MessageProxy.
*
* Requirements:
*
* - `schainName` must not be Mainnet.
*/
function isConnectedChain(
string memory schainName
)
public
view
override(IMessageProxy, MessageProxy)
returns (bool)
{
require(keccak256(abi.encodePacked(schainName)) != MAINNET_HASH, "Schain id can not be equal Mainnet");
return super.isConnectedChain(schainName);
}
// private
function _authorizeOutgoingMessageSender(bytes32 targetChainHash) internal view override {
require(
isContractRegistered(bytes32(0), msg.sender)
|| isContractRegistered(targetChainHash, msg.sender)
|| isSchainOwner(msg.sender, targetChainHash),
"Sender contract is not registered"
);
}
/**
* @dev Converts calldata structure to memory structure and checks
* whether message BLS signature is valid.
*/
function _verifyMessages(
string calldata fromSchainName,
bytes32 hashedMessages,
MessageProxyForMainnet.Signature calldata sign
)
internal
view
returns (bool)
{
return ISchains(
contractManagerOfSkaleManager.getContract("Schains")
).verifySchainSignature(
sign.blsSignature[0],
sign.blsSignature[1],
hashedMessages,
sign.counter,
sign.hashA,
sign.hashB,
fromSchainName
);
}
/**
* @dev Checks whether balance of schain wallet is sufficient for
* for reimbursement custom message.
*/
function _checkSchainBalance(bytes32 schainHash) internal view returns (bool) {
return IWallets(
payable(contractManagerOfSkaleManager.getContract("Wallets"))
).getSchainBalance(schainHash) >= (MESSAGES_LENGTH + 1) * gasLimit * tx.gasprice;
}
/**
* @dev Returns list of registered custom extra contracts.
*/
function _getRegistryContracts()
internal
view
override
returns (mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) storage)
{
return _registryContracts;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* SkaleManagerClient.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Artem Payvin
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@skalenetwork/skale-manager-interfaces/IContractManager.sol";
import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol";
import "@skalenetwork/ima-interfaces/mainnet/ISkaleManagerClient.sol";
/**
* @title SkaleManagerClient - contract that knows ContractManager
* and makes calls to SkaleManager contracts.
*/
contract SkaleManagerClient is Initializable, AccessControlEnumerableUpgradeable, ISkaleManagerClient {
IContractManager public contractManagerOfSkaleManager;
/**
* @dev Modifier for checking whether caller is owner of SKALE chain.
*/
modifier onlySchainOwner(string memory schainName) {
require(
isSchainOwner(msg.sender, keccak256(abi.encodePacked(schainName))),
"Sender is not an Schain owner"
);
_;
}
/**
* @dev initialize - sets current address of ContractManager of SkaleManager.
* @param newContractManagerOfSkaleManager - current address of ContractManager of SkaleManager.
*/
function initialize(
IContractManager newContractManagerOfSkaleManager
)
public
override
virtual
initializer
{
AccessControlEnumerableUpgradeable.__AccessControlEnumerable_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
contractManagerOfSkaleManager = newContractManagerOfSkaleManager;
}
/**
* @dev Checks whether sender is owner of SKALE chain
*/
function isSchainOwner(address sender, bytes32 schainHash) public view override returns (bool) {
address skaleChainsInternal = contractManagerOfSkaleManager.getContract("SchainsInternal");
return ISchainsInternal(skaleChainsInternal).isOwnerAddress(sender, schainHash);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IWallets - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IWallets {
/**
* @dev Emitted when the validator wallet was funded
*/
event ValidatorWalletRecharged(address sponsor, uint amount, uint validatorId);
/**
* @dev Emitted when the schain wallet was funded
*/
event SchainWalletRecharged(address sponsor, uint amount, bytes32 schainHash);
/**
* @dev Emitted when the node received a refund from validator to its wallet
*/
event NodeRefundedByValidator(address node, uint validatorId, uint amount);
/**
* @dev Emitted when the node received a refund from schain to its wallet
*/
event NodeRefundedBySchain(address node, bytes32 schainHash, uint amount);
/**
* @dev Emitted when the validator withdrawn funds from validator wallet
*/
event WithdrawFromValidatorWallet(uint indexed validatorId, uint amount);
/**
* @dev Emitted when the schain owner withdrawn funds from schain wallet
*/
event WithdrawFromSchainWallet(bytes32 indexed schainHash, uint amount);
receive() external payable;
function refundGasByValidator(uint validatorId, address payable spender, uint spentGas) external;
function refundGasByValidatorToSchain(uint validatorId, bytes32 schainHash) external;
function refundGasBySchain(bytes32 schainId, address payable spender, uint spentGas, bool isDebt) external;
function withdrawFundsFromSchainWallet(address payable schainOwner, bytes32 schainHash) external;
function withdrawFundsFromValidatorWallet(uint amount) external;
function rechargeValidatorWallet(uint validatorId) external payable;
function rechargeSchainWallet(bytes32 schainId) external payable;
function getSchainBalance(bytes32 schainHash) external view returns (uint);
function getValidatorBalance(uint validatorId) external view returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ISchains.sol - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface ISchains {
struct SchainOption {
string name;
bytes value;
}
/**
* @dev Emitted when an schain is created.
*/
event SchainCreated(
string name,
address owner,
uint partOfNode,
uint lifetime,
uint numberOfNodes,
uint deposit,
uint16 nonce,
bytes32 schainHash
);
/**
* @dev Emitted when an schain is deleted.
*/
event SchainDeleted(
address owner,
string name,
bytes32 indexed schainHash
);
/**
* @dev Emitted when a node in an schain is rotated.
*/
event NodeRotated(
bytes32 schainHash,
uint oldNode,
uint newNode
);
/**
* @dev Emitted when a node is added to an schain.
*/
event NodeAdded(
bytes32 schainHash,
uint newNode
);
/**
* @dev Emitted when a group of nodes is created for an schain.
*/
event SchainNodes(
string name,
bytes32 schainHash,
uint[] nodesInGroup
);
function addSchain(address from, uint deposit, bytes calldata data) external;
function addSchainByFoundation(
uint lifetime,
uint8 typeOfSchain,
uint16 nonce,
string calldata name,
address schainOwner,
address schainOriginator,
SchainOption[] calldata options
)
external
payable;
function deleteSchain(address from, string calldata name) external;
function deleteSchainByRoot(string calldata name) external;
function restartSchainCreation(string calldata name) external;
function verifySchainSignature(
uint256 signA,
uint256 signB,
bytes32 hash,
uint256 counter,
uint256 hashA,
uint256 hashB,
string calldata schainName
)
external
view
returns (bool);
function getSchainPrice(uint typeOfSchain, uint lifetime) external view returns (uint);
function getOption(bytes32 schainHash, string calldata optionName) external view returns (bytes memory);
function getOptions(bytes32 schainHash) external view returns (SchainOption[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ISchainsInternal - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager Interfaces is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface ISchainsInternal {
struct Schain {
string name;
address owner;
uint indexInOwnerList;
uint8 partOfNode;
uint lifetime;
uint startDate;
uint startBlock;
uint deposit;
uint64 index;
uint generation;
address originator;
}
struct SchainType {
uint8 partOfNode;
uint numberOfNodes;
}
/**
* @dev Emitted when schain type added.
*/
event SchainTypeAdded(uint indexed schainType, uint partOfNode, uint numberOfNodes);
/**
* @dev Emitted when schain type removed.
*/
event SchainTypeRemoved(uint indexed schainType);
function initializeSchain(
string calldata name,
address from,
address originator,
uint lifetime,
uint deposit) external;
function createGroupForSchain(
bytes32 schainHash,
uint numberOfNodes,
uint8 partOfNode
)
external
returns (uint[] memory);
function changeLifetime(bytes32 schainHash, uint lifetime, uint deposit) external;
function removeSchain(bytes32 schainHash, address from) external;
function removeNodeFromSchain(uint nodeIndex, bytes32 schainHash) external;
function deleteGroup(bytes32 schainHash) external;
function setException(bytes32 schainHash, uint nodeIndex) external;
function setNodeInGroup(bytes32 schainHash, uint nodeIndex) external;
function removeHolesForSchain(bytes32 schainHash) external;
function addSchainType(uint8 partOfNode, uint numberOfNodes) external;
function removeSchainType(uint typeOfSchain) external;
function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external;
function removeNodeFromAllExceptionSchains(uint nodeIndex) external;
function removeAllNodesFromSchainExceptions(bytes32 schainHash) external;
function makeSchainNodesInvisible(bytes32 schainHash) external;
function makeSchainNodesVisible(bytes32 schainHash) external;
function newGeneration() external;
function addSchainForNode(uint nodeIndex, bytes32 schainHash) external;
function removeSchainForNode(uint nodeIndex, uint schainIndex) external;
function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external;
function isSchainActive(bytes32 schainHash) external view returns (bool);
function schainsAtSystem(uint index) external view returns (bytes32);
function numberOfSchains() external view returns (uint64);
function getSchains() external view returns (bytes32[] memory);
function getSchainsPartOfNode(bytes32 schainHash) external view returns (uint8);
function getSchainListSize(address from) external view returns (uint);
function getSchainHashesByAddress(address from) external view returns (bytes32[] memory);
function getSchainIdsByAddress(address from) external view returns (bytes32[] memory);
function getSchainHashesForNode(uint nodeIndex) external view returns (bytes32[] memory);
function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory);
function getSchainOwner(bytes32 schainHash) external view returns (address);
function getSchainOriginator(bytes32 schainHash) external view returns (address);
function isSchainNameAvailable(string calldata name) external view returns (bool);
function isTimeExpired(bytes32 schainHash) external view returns (bool);
function isOwnerAddress(address from, bytes32 schainId) external view returns (bool);
function getSchainName(bytes32 schainHash) external view returns (string memory);
function getActiveSchain(uint nodeIndex) external view returns (bytes32);
function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains);
function getNumberOfNodesInGroup(bytes32 schainHash) external view returns (uint);
function getNodesInGroup(bytes32 schainHash) external view returns (uint[] memory);
function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool);
function getNodeIndexInGroup(bytes32 schainHash, uint nodeId) external view returns (uint);
function isAnyFreeNode(bytes32 schainHash) external view returns (bool);
function checkException(bytes32 schainHash, uint nodeIndex) external view returns (bool);
function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool);
function checkSchainOnNode(uint nodeIndex, bytes32 schainHash) external view returns (bool);
function getSchainType(uint typeOfSchain) external view returns(uint8, uint);
function getGeneration(bytes32 schainHash) external view returns (uint);
function isSchainExist(bytes32 schainHash) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/**
* MessageProxy.sol - SKALE Interchain Messaging Agent
* Copyright (C) 2021-Present SKALE Labs
* @author Dmytro Stebaiev
*
* SKALE IMA is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SKALE IMA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with SKALE IMA. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "@skalenetwork/ima-interfaces/IGasReimbursable.sol";
import "@skalenetwork/ima-interfaces/IMessageProxy.sol";
import "@skalenetwork/ima-interfaces/IMessageReceiver.sol";
/**
* @title MessageProxy
* @dev Abstract contract for MessageProxyForMainnet and MessageProxyForSchain.
*/
abstract contract MessageProxy is AccessControlEnumerableUpgradeable, IMessageProxy {
using AddressUpgradeable for address;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
/**
* @dev Structure that stores counters for outgoing and incoming messages.
*/
struct ConnectedChainInfo {
// message counters start with 0
uint256 incomingMessageCounter;
uint256 outgoingMessageCounter;
bool inited;
}
bytes32 public constant MAINNET_HASH = keccak256(abi.encodePacked("Mainnet"));
bytes32 public constant CHAIN_CONNECTOR_ROLE = keccak256("CHAIN_CONNECTOR_ROLE");
bytes32 public constant EXTRA_CONTRACT_REGISTRAR_ROLE = keccak256("EXTRA_CONTRACT_REGISTRAR_ROLE");
bytes32 public constant CONSTANT_SETTER_ROLE = keccak256("CONSTANT_SETTER_ROLE");
uint256 public constant MESSAGES_LENGTH = 10;
uint256 public constant REVERT_REASON_LENGTH = 64;
// schainHash => ConnectedChainInfo
mapping(bytes32 => ConnectedChainInfo) public connectedChains;
// schainHash => contract address => allowed
// solhint-disable-next-line private-vars-leading-underscore
mapping(bytes32 => mapping(address => bool)) internal deprecatedRegistryContracts;
uint256 public gasLimit;
/**
* @dev Emitted for every outgoing message to schain.
*/
event OutgoingMessage(
bytes32 indexed dstChainHash,
uint256 indexed msgCounter,
address indexed srcContract,
address dstContract,
bytes data
);
/**
* @dev Emitted when function `postMessage` returns revert.
* Used to prevent stuck loop inside function `postIncomingMessages`.
*/
event PostMessageError(
uint256 indexed msgCounter,
bytes message
);
/**
* @dev Emitted when gas limit per one call of `postMessage` was changed.
*/
event GasLimitWasChanged(
uint256 oldValue,
uint256 newValue
);
/**
* @dev Emitted when the version was updated
*/
event VersionUpdated(string oldVersion, string newVersion);
/**
* @dev Emitted when extra contract was added.
*/
event ExtraContractRegistered(
bytes32 indexed chainHash,
address contractAddress
);
/**
* @dev Emitted when extra contract was removed.
*/
event ExtraContractRemoved(
bytes32 indexed chainHash,
address contractAddress
);
/**
* @dev Modifier to make a function callable only if caller is granted with {CHAIN_CONNECTOR_ROLE}.
*/
modifier onlyChainConnector() {
require(hasRole(CHAIN_CONNECTOR_ROLE, msg.sender), "CHAIN_CONNECTOR_ROLE is required");
_;
}
/**
* @dev Modifier to make a function callable only if caller is granted with {EXTRA_CONTRACT_REGISTRAR_ROLE}.
*/
modifier onlyExtraContractRegistrar() {
require(hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender), "EXTRA_CONTRACT_REGISTRAR_ROLE is required");
_;
}
/**
* @dev Modifier to make a function callable only if caller is granted with {CONSTANT_SETTER_ROLE}.
*/
modifier onlyConstantSetter() {
require(hasRole(CONSTANT_SETTER_ROLE, msg.sender), "Not enough permissions to set constant");
_;
}
/**
* @dev Sets gasLimit to a new value.
*
* Requirements:
*
* - `msg.sender` must be granted CONSTANT_SETTER_ROLE.
*/
function setNewGasLimit(uint256 newGasLimit) external override onlyConstantSetter {
emit GasLimitWasChanged(gasLimit, newGasLimit);
gasLimit = newGasLimit;
}
/**
* @dev Virtual function for `postIncomingMessages`.
*/
function postIncomingMessages(
string calldata fromSchainName,
uint256 startingCounter,
Message[] calldata messages,
Signature calldata sign
)
external
virtual
override;
/**
* @dev Allows `msg.sender` to register extra contract for all schains
* for being able to transfer messages from custom contracts.
*
* Requirements:
*
* - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE.
* - Passed address should be contract.
* - Extra contract must not be registered.
*/
function registerExtraContractForAll(address extraContract) external override onlyExtraContractRegistrar {
require(extraContract.isContract(), "Given address is not a contract");
require(!_getRegistryContracts()[bytes32(0)].contains(extraContract), "Extra contract is already registered");
_getRegistryContracts()[bytes32(0)].add(extraContract);
emit ExtraContractRegistered(bytes32(0), extraContract);
}
/**
* @dev Allows `msg.sender` to remove extra contract for all schains.
* Extra contract will no longer be able to send messages through MessageProxy.
*
* Requirements:
*
* - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE.
*/
function removeExtraContractForAll(address extraContract) external override onlyExtraContractRegistrar {
require(_getRegistryContracts()[bytes32(0)].contains(extraContract), "Extra contract is not registered");
_getRegistryContracts()[bytes32(0)].remove(extraContract);
emit ExtraContractRemoved(bytes32(0), extraContract);
}
/**
* @dev Should return length of contract registered by schainHash.
*/
function getContractRegisteredLength(bytes32 schainHash) external view override returns (uint256) {
return _getRegistryContracts()[schainHash].length();
}
/**
* @dev Should return a range of contracts registered by schainHash.
*
* Requirements:
* range should be less or equal 10 contracts
*/
function getContractRegisteredRange(
bytes32 schainHash,
uint256 from,
uint256 to
)
external
view
override
returns (address[] memory contractsInRange)
{
require(
from < to && to - from <= 10 && to <= _getRegistryContracts()[schainHash].length(),
"Range is incorrect"
);
contractsInRange = new address[](to - from);
for (uint256 i = from; i < to; i++) {
contractsInRange[i - from] = _getRegistryContracts()[schainHash].at(i);
}
}
/**
* @dev Returns number of outgoing messages.
*
* Requirements:
*
* - Target schain must be initialized.
*/
function getOutgoingMessagesCounter(string calldata targetSchainName)
external
view
override
returns (uint256)
{
bytes32 dstChainHash = keccak256(abi.encodePacked(targetSchainName));
require(connectedChains[dstChainHash].inited, "Destination chain is not initialized");
return connectedChains[dstChainHash].outgoingMessageCounter;
}
/**
* @dev Returns number of incoming messages.
*
* Requirements:
*
* - Source schain must be initialized.
*/
function getIncomingMessagesCounter(string calldata fromSchainName)
external
view
override
returns (uint256)
{
bytes32 srcChainHash = keccak256(abi.encodePacked(fromSchainName));
require(connectedChains[srcChainHash].inited, "Source chain is not initialized");
return connectedChains[srcChainHash].incomingMessageCounter;
}
function initializeMessageProxy(uint newGasLimit) public initializer {
AccessControlEnumerableUpgradeable.__AccessControlEnumerable_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(CHAIN_CONNECTOR_ROLE, msg.sender);
_setupRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender);
_setupRole(CONSTANT_SETTER_ROLE, msg.sender);
gasLimit = newGasLimit;
}
/**
* @dev Posts message from this contract to `targetChainHash` MessageProxy contract.
* This is called by a smart contract to make a cross-chain call.
*
* Emits an {OutgoingMessage} event.
*
* Requirements:
*
* - Target chain must be initialized.
* - Target chain must be registered as external contract.
*/
function postOutgoingMessage(
bytes32 targetChainHash,
address targetContract,
bytes memory data
)
public
override
virtual
{
require(connectedChains[targetChainHash].inited, "Destination chain is not initialized");
_authorizeOutgoingMessageSender(targetChainHash);
emit OutgoingMessage(
targetChainHash,
connectedChains[targetChainHash].outgoingMessageCounter,
msg.sender,
targetContract,
data
);
connectedChains[targetChainHash].outgoingMessageCounter += 1;
}
/**
* @dev Allows CHAIN_CONNECTOR_ROLE to remove connected chain from this contract.
*
* Requirements:
*
* - `msg.sender` must be granted CHAIN_CONNECTOR_ROLE.
* - `schainName` must be initialized.
*/
function removeConnectedChain(string memory schainName) public virtual override onlyChainConnector {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(connectedChains[schainHash].inited, "Chain is not initialized");
delete connectedChains[schainHash];
}
/**
* @dev Checks whether chain is currently connected.
*/
function isConnectedChain(
string memory schainName
)
public
view
virtual
override
returns (bool)
{
return connectedChains[keccak256(abi.encodePacked(schainName))].inited;
}
/**
* @dev Checks whether contract is currently registered as extra contract.
*/
function isContractRegistered(
bytes32 schainHash,
address contractAddress
)
public
view
override
returns (bool)
{
return _getRegistryContracts()[schainHash].contains(contractAddress);
}
/**
* @dev Allows MessageProxy to register extra contract for being able to transfer messages from custom contracts.
*
* Requirements:
*
* - Extra contract address must be contract.
* - Extra contract must not be registered.
* - Extra contract must not be registered for all chains.
*/
function _registerExtraContract(
bytes32 chainHash,
address extraContract
)
internal
{
require(extraContract.isContract(), "Given address is not a contract");
require(!_getRegistryContracts()[chainHash].contains(extraContract), "Extra contract is already registered");
require(
!_getRegistryContracts()[bytes32(0)].contains(extraContract),
"Extra contract is already registered for all chains"
);
_getRegistryContracts()[chainHash].add(extraContract);
emit ExtraContractRegistered(chainHash, extraContract);
}
/**
* @dev Allows MessageProxy to remove extra contract,
* thus `extraContract` will no longer be available to transfer messages from mainnet to schain.
*
* Requirements:
*
* - Extra contract must be registered.
*/
function _removeExtraContract(
bytes32 chainHash,
address extraContract
)
internal
{
require(_getRegistryContracts()[chainHash].contains(extraContract), "Extra contract is not registered");
_getRegistryContracts()[chainHash].remove(extraContract);
emit ExtraContractRemoved(chainHash, extraContract);
}
/**
* @dev Allows MessageProxy to connect schain with MessageProxyOnMainnet for transferring messages.
*
* Requirements:
*
* - `msg.sender` must be granted CHAIN_CONNECTOR_ROLE.
* - SKALE chain must not be connected.
*/
function _addConnectedChain(bytes32 schainHash) internal onlyChainConnector {
require(!connectedChains[schainHash].inited,"Chain is already connected");
connectedChains[schainHash] = ConnectedChainInfo({
incomingMessageCounter: 0,
outgoingMessageCounter: 0,
inited: true
});
}
/**
* @dev Allows MessageProxy to send messages from schain to mainnet.
* Destination contract must implement `postMessage` method.
*/
function _callReceiverContract(
bytes32 schainHash,
Message calldata message,
uint counter
)
internal
{
if (!message.destinationContract.isContract()) {
emit PostMessageError(
counter,
"Destination contract is not a contract"
);
return;
}
try IMessageReceiver(message.destinationContract).postMessage{gas: gasLimit}(
schainHash,
message.sender,
message.data
) {
return;
} catch Error(string memory reason) {
emit PostMessageError(
counter,
_getSlice(bytes(reason), REVERT_REASON_LENGTH)
);
} catch Panic(uint errorCode) {
emit PostMessageError(
counter,
abi.encodePacked(errorCode)
);
} catch (bytes memory revertData) {
emit PostMessageError(
counter,
_getSlice(revertData, REVERT_REASON_LENGTH)
);
}
}
/**
* @dev Returns receiver of message.
*/
function _getGasPayer(
bytes32 schainHash,
Message calldata message,
uint counter
)
internal
returns (address)
{
try IGasReimbursable(message.destinationContract).gasPayer{gas: gasLimit}(
schainHash,
message.sender,
message.data
) returns (address receiver) {
return receiver;
} catch Error(string memory reason) {
emit PostMessageError(
counter,
_getSlice(bytes(reason), REVERT_REASON_LENGTH)
);
return address(0);
} catch Panic(uint errorCode) {
emit PostMessageError(
counter,
abi.encodePacked(errorCode)
);
return address(0);
} catch (bytes memory revertData) {
emit PostMessageError(
counter,
_getSlice(revertData, REVERT_REASON_LENGTH)
);
return address(0);
}
}
/**
* @dev Checks whether msg.sender is registered as custom extra contract.
*/
function _authorizeOutgoingMessageSender(bytes32 targetChainHash) internal view virtual {
require(
isContractRegistered(bytes32(0), msg.sender) || isContractRegistered(targetChainHash, msg.sender),
"Sender contract is not registered"
);
}
/**
* @dev Returns list of registered custom extra contracts.
*/
function _getRegistryContracts()
internal
view
virtual
returns (mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) storage);
/**
* @dev Returns hash of message array.
*/
function _hashedArray(
Message[] calldata messages,
uint256 startingCounter,
string calldata fromChainName
)
internal
pure
returns (bytes32)
{
bytes32 sourceHash = keccak256(abi.encodePacked(fromChainName));
bytes32 hash = keccak256(abi.encodePacked(sourceHash, bytes32(startingCounter)));
for (uint256 i = 0; i < messages.length; i++) {
hash = keccak256(
abi.encodePacked(
abi.encode(
hash,
messages[i].sender,
messages[i].destinationContract
),
messages[i].data
)
);
}
return hash;
}
function _getSlice(bytes memory text, uint end) private pure returns (bytes memory) {
uint slicedEnd = end < text.length ? end : text.length;
bytes memory sliced = new bytes(slicedEnd);
for(uint i = 0; i < slicedEnd; i++){
sliced[i] = text[i];
}
return sliced;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
CommunityPool.sol - SKALE Manager
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.6;
import "@skalenetwork/ima-interfaces/mainnet/ICommunityPool.sol";
import "@skalenetwork/skale-manager-interfaces/IWallets.sol";
import "../Messages.sol";
import "./Twin.sol";
/**
* @title CommunityPool
* @dev Contract contains logic to perform automatic self-recharging ETH for nodes.
*/
contract CommunityPool is Twin, ICommunityPool {
using AddressUpgradeable for address payable;
bytes32 public constant CONSTANT_SETTER_ROLE = keccak256("CONSTANT_SETTER_ROLE");
// address of user => schainHash => balance of gas wallet in ETH
mapping(address => mapping(bytes32 => uint)) private _userWallets;
// address of user => schainHash => true if unlocked for transferring
mapping(address => mapping(bytes32 => bool)) public activeUsers;
uint public minTransactionGas;
/**
* @dev Emitted when minimal value in gas for transactions from schain to mainnet was changed
*/
event MinTransactionGasWasChanged(
uint oldValue,
uint newValue
);
function initialize(
IContractManager contractManagerOfSkaleManagerValue,
ILinker linker,
IMessageProxyForMainnet messageProxyValue
)
external
override
initializer
{
Twin.initialize(contractManagerOfSkaleManagerValue, messageProxyValue);
_setupRole(LINKER_ROLE, address(linker));
minTransactionGas = 1e6;
}
/**
* @dev Allows MessageProxyForMainnet to reimburse gas for transactions
* that transfer funds from schain to mainnet.
*
* Requirements:
*
* - User that receives funds should have enough funds in their gas wallet.
* - Address that should be reimbursed for executing transaction must not be null.
*/
function refundGasByUser(
bytes32 schainHash,
address payable node,
address user,
uint gas
)
external
override
onlyMessageProxy
returns (uint)
{
require(node != address(0), "Node address must be set");
if (!activeUsers[user][schainHash]) {
return gas;
}
uint amount = tx.gasprice * gas;
if (amount > _userWallets[user][schainHash]) {
amount = _userWallets[user][schainHash];
}
_userWallets[user][schainHash] = _userWallets[user][schainHash] - amount;
if (!_balanceIsSufficient(schainHash, user, 0)) {
activeUsers[user][schainHash] = false;
messageProxy.postOutgoingMessage(
schainHash,
schainLinks[schainHash],
Messages.encodeLockUserMessage(user)
);
}
node.sendValue(amount);
return (tx.gasprice * gas - amount) / tx.gasprice;
}
function refundGasBySchainWallet(
bytes32 schainHash,
address payable node,
uint gas
)
external
override
onlyMessageProxy
returns (bool)
{
if (gas > 0) {
IWallets(payable(contractManagerOfSkaleManager.getContract("Wallets"))).refundGasBySchain(
schainHash,
node,
gas,
false
);
}
return true;
}
/**
* @dev Allows `msg.sender` to recharge their wallet for further gas reimbursement.
*
* Requirements:
*
* - 'msg.sender` should recharge their gas wallet for amount that enough to reimburse any
* transaction from schain to mainnet.
*/
function rechargeUserWallet(string calldata schainName, address user) external payable override {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(
_balanceIsSufficient(schainHash, user, msg.value),
"Not enough ETH for transaction"
);
_userWallets[user][schainHash] = _userWallets[user][schainHash] + msg.value;
if (!activeUsers[user][schainHash]) {
activeUsers[user][schainHash] = true;
messageProxy.postOutgoingMessage(
schainHash,
schainLinks[schainHash],
Messages.encodeActivateUserMessage(user)
);
}
}
/**
* @dev Allows `msg.sender` to withdraw funds from their gas wallet.
* If `msg.sender` withdraws too much funds,
* then he will no longer be able to transfer their tokens on ETH from schain to mainnet.
*
* Requirements:
*
* - 'msg.sender` must have sufficient amount of ETH on their gas wallet.
*/
function withdrawFunds(string calldata schainName, uint amount) external override {
bytes32 schainHash = keccak256(abi.encodePacked(schainName));
require(amount <= _userWallets[msg.sender][schainHash], "Balance is too low");
require(!messageProxy.messageInProgress(), "Message is in progress");
_userWallets[msg.sender][schainHash] = _userWallets[msg.sender][schainHash] - amount;
if (
!_balanceIsSufficient(schainHash, msg.sender, 0) &&
activeUsers[msg.sender][schainHash]
) {
activeUsers[msg.sender][schainHash] = false;
messageProxy.postOutgoingMessage(
schainHash,
schainLinks[schainHash],
Messages.encodeLockUserMessage(msg.sender)
);
}
payable(msg.sender).sendValue(amount);
}
/**
* @dev Allows `msg.sender` set the amount of gas that should be
* enough for reimbursing any transaction from schain to mainnet.
*
* Requirements:
*
* - 'msg.sender` must have sufficient amount of ETH on their gas wallet.
*/
function setMinTransactionGas(uint newMinTransactionGas) external override {
require(hasRole(CONSTANT_SETTER_ROLE, msg.sender), "CONSTANT_SETTER_ROLE is required");
emit MinTransactionGasWasChanged(minTransactionGas, newMinTransactionGas);
minTransactionGas = newMinTransactionGas;
}
/**
* @dev Returns the amount of ETH on gas wallet for particular user.
*/
function getBalance(address user, string calldata schainName) external view override returns (uint) {
return _userWallets[user][keccak256(abi.encodePacked(schainName))];
}
/**
* @dev Checks whether user is active and wallet was recharged for sufficient amount.
*/
function checkUserBalance(bytes32 schainHash, address receiver) external view override returns (bool) {
return activeUsers[receiver][schainHash] && _balanceIsSufficient(schainHash, receiver, 0);
}
/**
* @dev Checks whether user wallet was recharged for sufficient amount.
*/
function _balanceIsSufficient(bytes32 schainHash, address receiver, uint256 delta) private view returns (bool) {
return delta + _userWallets[receiver][schainHash] >= minTransactionGas * tx.gasprice;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
}
function __AccessControlEnumerable_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
Returns number of incoming messages. Requirements: - Source schain must be initialized./
|
function getIncomingMessagesCounter(string calldata fromSchainName)
external
view
override
returns (uint256)
{
bytes32 srcChainHash = keccak256(abi.encodePacked(fromSchainName));
require(connectedChains[srcChainHash].inited, "Source chain is not initialized");
return connectedChains[srcChainHash].incomingMessageCounter;
}
| 1,152,679
|
./full_match/5/0x2fe0680016F5A53f1a1E139086BF3A4393b9DAFE/sources/KlerosDemoCourt/IArbitrable.sol
|
IArbitrable Enrique Piqueras - <enrique@kleros.io> Arbitrable interface. When developing arbitrable contracts, we need to: -Define the action taken when a ruling is received by the contract. We should do so in executeRuling. -Allow dispute creation. For this a function must: -Call arbitrator.createDispute.value(_fee)(_choices,_extraData); -Create the event Dispute(_arbitrator,_disputeID,_rulingOptions);/
|
interface IArbitrable {
event MetaEvidence(uint indexed _metaEvidenceID, string _evidence);
event Dispute(Arbitrator indexed _arbitrator, uint indexed _disputeID, uint _metaEvidenceID, uint _evidenceGroupID);
event Evidence(Arbitrator indexed _arbitrator, uint indexed _evidenceGroupID, address indexed _party, string _evidence);
event Ruling(Arbitrator indexed _arbitrator, uint indexed _disputeID, uint _ruling);
function rule(uint _disputeID, uint _ruling) external;
}
| 7,071,877
|
./full_match/80001/0xD35C3fCC6e10052a08aB20F922Aa5A1B7B18D74B/sources/contracts/base/core/VoltPair.sol
|
Accrue fees on token1 transfer the fees out to PairFees and Treasury keep the same structure of events for compatability
|
function _update1(uint amount) internal {
uint toTreasury;
address treasury = IFactory(msg.sender).treasury();
if (treasury != address(0)) {
toTreasury = amount / TREASURY_FEE;
IERC20(token1).safeTransfer(treasury, toTreasury);
emit Treasury(msg.sender, 0, toTreasury);
}
uint toFees = amount - toTreasury;
IERC20(token1).safeTransfer(fees, toFees);
uint _ratio = (toFees * _FEE_PRECISION) / totalSupply;
if (_ratio > 0) {
index1 += _ratio;
}
emit Fees(msg.sender, 0, toFees);
}
| 5,677,485
|
//author:Toshiya Y(K.N) ; https://github.com/Toshiya-Y-K-N
pragma solidity 0.6.2;
import "./nf-token.sol";//This sol file modified.(base file is 0xcert's file.)
import "./nf-token-metadata.sol";
import "./nf-token-enumerable.sol";
import "../ownership/ownable.sol";
contract MyERC721LT is
NFTokenMetadata,
Ownable
{
//Creator data 作者の名前とウェブサイトやメールアドレス、SNSアカウント、電話番号などを記載する。
//(有事の際はこのサイトでコントラクトの運用に関してアナウンスする)
//この作者名と管理サイト名は書き換え不可能である。
//万一、オーナーが秘密鍵流出などでonlyOwner権限を無くしてもここに記入したサイトのアドレスの指示に従うように誘導すること。
string private _creatorData = "作者:Toshiya Y(K.N) ; 管理サイト:https://github.com/Toshiya-Y-K-N";
//Site 招待するウェブサイトアドレス
string private _creatorSiteAddress1 = "https://test.official.com/";//example
//get creator data
function getCreatorData() public view onlyOwner returns (string memory) {
return _creatorData;
}
//address setter getter
//サイトへのアドレスを示す。
function setSiteAddress1(string memory _newAddress) public onlyOwner {
_creatorSiteAddress1 = _newAddress ;
}
function getSiteAddress1() public view returns (string memory) {
require(msg.sender != address(0), ZERO_ADDRESS);
require( _getOwnerNFTCount(msg.sender) > 0 );
return _creatorSiteAddress1;
}
//サイトに入場した回数をチケットNFTに記録できるといい。tokenUri2を新しく設定
mapping (uint256 => string) internal idToUri2;//second uri
/**
* @dev Write TokenURI2 a NFT from NFTowner (creator can`t rewrite URI2.)
* @param _tokenId Which NFT <-----NFT owner want to Write URI2.
*/
//URI2を設定 運営者がウェブサイトに訪問したことを確認した場合などにデータを書き込み、継ぎ足していく。
//入力する_uri文字列は暗号化すると良い
function setTokenUri2(
uint256 _tokenId,
string calldata _uri
)
external
onlyOwner
validNFToken(_tokenId)
{
require(msg.sender != address(0), ZERO_ADDRESS);
require(msg.sender == idToOwner[_tokenId]);
idToUri2[_tokenId] = _uri;
}
/**
* @dev Read TokenURI2 a NFT . (All user watch this uri2.)
* @param _tokenId <---- we want to read NFT URI2
*/
function tokenURI2(
uint256 _tokenId
)
external
view
validNFToken(_tokenId)
returns (string memory)
{
return idToUri2[_tokenId];
}
/**
* oneTimePassCode Section
*/
//secret
string private _secret = "toshiyaTestTicket03o3";//examle.
//CreatorNum blocknum
uint256 private _creatorOneTimeNum = 20200303;//example.
//setCreatorOneTimeNum public onlyOwner
//手動でワンタイムパスワード(OTP)を変えるの数値を入力できる関数。運営者のオーナーのみが関数を実行出来る。
//通常のワンタイムパスワードは時刻同期式だが、イーサリアムではブロックナンバーを用いてそれが実装できる。
//ただし、各テストネット毎にブロックの更新間隔が違ったり、高速化されるなどを考えると、”手動でも良い”と思う。
//週に1度程度更新出来れば良く、毎分、毎時で更新する必要もないかもしれない。
/**
* @dev setCreatorOneTimeNum(uint256 _newNum) public onlyOwner
*/
function setCreatorOneTimeNum(uint256 _newNum) public onlyOwner {
_creatorOneTimeNum = _newNum ;
}
//getOTP() サイトそのもののOTPを表示させる。
//これはチケットを持つ人なら見ることができる。
//全員に同じ値を表示する。
function getOTP() public view returns (bytes32) {
require(msg.sender != address(0), ZERO_ADDRESS);
//ファンサイト入場できるトークンを持っているか確認する
require( _getOwnerNFTCount(msg.sender) > 0 );
//条件通りならばクリエイターのセットしたパスワードをリターンする
string memory str = _secret ;
uint256 inte = _creatorOneTimeNum ;
string memory str2 = "str";
return sha256(abi.encodePacked(inte, str ,str2));
}
//getYourOTP() それぞれの人が持つパスワードを表示させる。
//これはチケットを持つ人なら見ることができる。
//ウォレットアドレス毎に異なる値をとる。
function getYourOTP() public view returns (bytes32) {
require(msg.sender != address(0), ZERO_ADDRESS);
//ファンサイト入場できるトークンを持っているか確認する
require( _getOwnerNFTCount(msg.sender) > 0 );
//条件通りならばクリエイターのセットしたパスワードをリターンする
string memory str = _secret ;
uint256 inte = _creatorOneTimeNum ;
address adr = msg.sender;
return sha256(abi.encodePacked(inte, str,adr));
}
//既存の時刻同期式ワンタイムパスワード(TOTP)を取得する。
//これはチケットを持つ人なら見ることができる。ウォレットアドレス毎に異なる値をとる。
function getYourTOTP() public view returns (bytes32) {
require(msg.sender != address(0), ZERO_ADDRESS);
require( _getOwnerNFTCount(msg.sender) > 0 );
string memory str = _secret ;
uint256 inte = block.number ;
address adr = msg.sender;
return sha256(abi.encodePacked(inte, str,adr));
}
/**
* コンストラクタ
* @dev Contract constructor. Sets metadata extension `name` and `symbol`.
*/
constructor()
public
{
nftName = "SingulionLtTicket20200303-goe";
nftSymbol = "SNTCKTLT0303";
}
////////トークン発行時に永久に転送許可しない場合は以下のsetTransferPermission()を削除してコンパイルしデプロイすること/////////
//@@トランスファーが許可されるケース@@
//例1.認証されたユーザー同士のウォレットでトークンの譲渡をすることは制限しない場合、トランスファー許可できる。
//例2.チケットを使うサービス、例えば上映会やライブ等の開催後にチケットの有効期限が切れた後、
//それを骨董品のように認証されたユーザー同士のウォレットで譲渡したい場合。(コンサートの数年後にこっそりファンに告知してとtrue化するなど)
//見かけ上、ERC&21LTにはトランスファー関数があるものの、その実行はオーナー含め全員出来ない。
//実行するにはオーナーが_setTransferPermissionをtrueしなければいけない。
//以下にその実行するためのtrue値をセットする関数を記述する。
/**
* トランスファー関数の有効無効を決める真偽値 トランスファー関数は初期設定では無効。
* @dev Removes a NFT from owner.
* @param _newState 新しい転送許可の状態、trueでNFT送付可能、falseで転送不能。
* _setTransferPermissionの初期値はfalse. 通常、転送は許可されない。
*/
function setTransferPermission(bool _newState)
external
onlyOwner
{
_setTransferPermission(_newState);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* 転売確認、秘密鍵流出、秘密鍵紛失時にNFTを強制的にリサイクルするためのburn関数
* @dev Removes a NFT from owner.
* @param _tokenId Which NFT we want to remove.(burn)
*/
function burn(
uint256 _tokenId
)
external
onlyOwner
{
super._burn(_tokenId);
}
/**
* 任意の人のウォレットアドレスにNFTを発行する。トランスファー関数を使わない場合、唯一のNFT送付機構。
* @dev Mints a new NFT.
* @param _to The address that will own the minted NFT.
* @param _tokenId of the NFT to be minted by the msg.sender.
* @param _uri String representing RFC 3986 URI.
*/
function mint(
address _to,
uint256 _tokenId,
string calldata _uri
)
external
onlyOwner
{
super._mint(_to, _tokenId);
super._setTokenUri(_tokenId, _uri);
}
}
/* =========コメント=========
//based https://github.com/0xcert/ethereum-erc721
//based https://github.com/Kaz-Naz/ERC721LT
//nf-token.sol was modified.
//以下のようにトランスファー関数部分に追加分を加えた。
//具体的には3つあるトランスファー関数にrequire(_transferPermission == true);を追記した。これでfalseのときはNFT送付を阻止できる。
// can we transfer NFT ? true is OK , false is NG .this varriable is changed by contract owner.
bool private _transferPermission = false ;
//TransferPermission setter getter
function getTransferPermission()public view returns (bool) {
return _transferPermission;
}
function _setTransferPermission( bool _newState) internal {
_transferPermission = _newState;
}
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes calldata _data
)
external
override
{
require(_transferPermission == true);//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
_safeTransferFrom(_from, _to, _tokenId, _data);
}
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
override
{
require(_transferPermission == true);//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
_safeTransferFrom(_from, _to, _tokenId, "");
}
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
override
canTransfer(_tokenId)
validNFToken(_tokenId)
{
require(_transferPermission == true);//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from, NOT_OWNER);
require(_to != address(0), ZERO_ADDRESS);
_transfer(_to, _tokenId);
}
*/
|
転売確認、秘密鍵流出、秘密鍵紛失時にNFTを強制的にリサイクルするためのburn関数 Removes a NFT from owner. _tokenId Which NFT we want to remove.(burn)/
|
function burn(
uint256 _tokenId
)
external
onlyOwner
{
super._burn(_tokenId);
}
| 1,764,848
|
// File: openzeppelin-solidity/contracts/math/Math.sol
pragma solidity ^0.5.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol
pragma solidity ^0.5.0;
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @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].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
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));
}
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'
// solhint-disable-next-line max-line-length
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).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
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.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
// File: Owned.sol
pragma solidity ^0.5.16;
// https://docs.synthetix.io/contracts/source/contracts/owned
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
_onlyOwner();
_;
}
function _onlyOwner() private view {
require(msg.sender == owner, "Only the contract owner may perform this action");
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// File: Pausable.sol
pragma solidity ^0.5.16;
// Inheritance
// https://docs.synthetix.io/contracts/source/contracts/pausable
contract Pausable is Owned {
uint public lastPauseTime;
bool public paused;
constructor() internal {
// This contract is abstract, and thus cannot be instantiated directly
require(owner != address(0), "Owner must be set");
// Paused will be false, and lastPauseTime will be 0 upon initialisation
}
/**
* @notice Change the paused state of the contract
* @dev Only the contract owner may call this.
*/
function setPaused(bool _paused) external onlyOwner {
// Ensure we're actually changing the state before we do anything
if (_paused == paused) {
return;
}
// Set our paused state.
paused = _paused;
// If applicable, set the last pause time.
if (paused) {
lastPauseTime = now;
}
// Let everyone know that our pause state has changed.
emit PauseChanged(paused);
}
event PauseChanged(bool isPaused);
modifier notPaused {
require(!paused, "This action cannot be performed while the contract is paused");
_;
}
}
// File: newStaking.sol
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
contract PhbStaking is ReentrancyGuard, Pausable {
/// @notice Emitted when setLevel
event SetLevel(string name,uint256 min , uint256 max, uint256 weight);
/// @notice Emitted when staking
event Staked(address indexed user, uint256 amount);
/// @notice Emitted when claiming
event Claimed(address indexed user, uint256 amount);
/// @notice Emitted when withdrawing
event Withdrawn(address indexed user, uint256 amount);
/// @notice Emitted when set lockdown duration
event LockDownDurationUpdated(uint256 newLockDownDuration);
/// @notice Emitted when set inflation speed
event InflationSpeedUpdated(uint256 newSpeed);
/// @notice Emitted when apply withdraw
event ApplyWithdraw(address indexed user,uint256 amount, uint256 time);
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public rewardsToken;
IERC20 public stakingToken;
uint256 public lockDownDuration = 5 seconds;
uint256 public totalStakes ;
uint256 public virtualTotalStakes;
uint constant doubleScale = 1e36;
// uint256 RateScale = 10000;
uint256 phbDecimals = 1e18;
uint256 WeightScale = 100;
address public rewardProvider =0x26356Cb66F8fd62c03F569EC3691B6F00173EB02;
//withdraw rate 5 for 0.05%
uint256 public withdrawRate = 0;
uint256 public feeScale = 10000;
//NOTE:modify me before mainnet
address public feeCollector =0x26356Cb66F8fd62c03F569EC3691B6F00173EB02;
/// @notice The initial global index
uint256 public constant globalInitialIndex = 1e36;
uint256 public inflationSpeed = 0;
struct Double {
uint mantissa;
}
string [] levels = ["Carbon","Genesis","Platinum","Zirconium","Diamond"];
struct RateLevel {
uint256 min;
uint256 max;
uint256 weight;
}
mapping(string => RateLevel) _ratesLevel;
mapping(string => uint256) levelAmount;
mapping(address=>uint256) virtualUserbalance;
struct withdrawApplication {
uint256 amount;
uint256 applyTime;
}
mapping(address => uint256) _userRewards;
//this record the user withdraw application
//according to the requirement, when user want to withdraw his staking phb, he needs to
//1. call applyWithdraw , this will add a lock period (7 days by default, can be changed by admin)
//2. call withdraw to withdraw the "withdrawable amounts"
struct TimedWithdraw {
uint256 totalApplied; //total user applied for withdraw
mapping(uint256 => uint256) applications; //apply detail time=>amount
uint256[] applyTimes; //apply timestamp, used for the key of applications mapping
}
mapping(address => TimedWithdraw) timeApplyInfo; //user => TimedWithdraw mapping
mapping(address => uint256) _balances;
struct Index {
uint256 index;
uint256 lastTime;
}
Index globalIndex;
mapping(address => Index) userIndex;
/* ========== CONSTRUCTOR ========== */
constructor(
address _owner,
address _rewardsToken,
address _stakingToken
) public Owned(_owner){
rewardsToken = IERC20(_rewardsToken);
stakingToken = IERC20(_stakingToken);
initLevel();
globalIndex.index = globalInitialIndex;
globalIndex.lastTime = now;
}
/* ========== internals ======== */
function initLevel() internal {
_ratesLevel[levels[0]] = RateLevel({min:0,max:1000,weight:100});
_ratesLevel[levels[1]] = RateLevel({min:1000,max:10000,weight:125});
_ratesLevel[levels[2]] = RateLevel({min:10000,max:50000,weight:150});
_ratesLevel[levels[3]] = RateLevel({min:50000,max:100000,weight:175});
_ratesLevel[levels[4]] = RateLevel({min:100000,max:999999999,weight:200});
}
/* =========== views ==========*/
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
//to calculate the rewards by the gap of userindex and globalindx
function getUserRewards(address account) public view returns(uint256){
// updateGlobalIndex();
uint256 rewardSpeed = inflationSpeed;
uint256 deltaTime = now.sub(globalIndex.lastTime);
uint256 rewardAccued = deltaTime.mul(rewardSpeed);
// Double memory ratio = totalStakes > 0 ? fraction(rewardAccued,totalStakes):Double({mantissa:0});
Double memory ratio = virtualTotalStakes > 0 ? fraction(rewardAccued,virtualTotalStakes):Double({mantissa:0});
Double memory gIndex = add_(Double({mantissa: globalIndex.index}), ratio);
Double memory uIndex = Double({mantissa:userIndex[account].index});
if (uIndex.mantissa == 0 && gIndex.mantissa > 0) {
uIndex.mantissa = globalInitialIndex;
}
Double memory deltaIndex = sub_(gIndex,uIndex);
uint256 supplierDelta = mul_(virtualUserbalance[account],deltaIndex);
return supplierDelta.add(_userRewards[account] );
}
//calculate the total amount which apply time already passed [7 days]
function withdrawableAmount(address account)public view returns(uint256){
uint256 amount = 0;
TimedWithdraw storage withdrawApplies = timeApplyInfo[account];
for (uint8 index = 0; index < withdrawApplies.applyTimes.length; index++) {
uint256 key = withdrawApplies.applyTimes[index];
if (now.sub(key) > lockDownDuration){
amount = amount.add(withdrawApplies.applications[key]);
}
}
return amount;
}
//for front end display, the following two method should be used together
//
//we return total applied, applied times and applied amounts here
function getUserApplication(address account) external view returns(uint256, uint256[] memory, uint256[] memory){
uint256[] memory applyTimes = timeApplyInfo[account].applyTimes;
uint256[] memory applyAmounts = new uint256[](applyTimes.length);
for (uint8 index = 0 ;index < applyTimes.length; index++){
applyAmounts[index] = timeApplyInfo[account].applications[applyTimes[index]];
}
return (timeApplyInfo[account].totalApplied, applyTimes, applyAmounts);
}
//return levels config in contract
function getLevelInfos() external view returns(string[] memory){
return levels;
}
//return level detail,key is result of previous function
function getLevelDetail(string calldata lv) external view returns(RateLevel memory){
return _ratesLevel[lv];
}
//return the total staked amount for the given level
function getLevelStakes(string calldata lv) external view returns(uint256){
return levelAmount[lv];
}
/* ========== MUTATIVE FUNCTIONS ========== */
function setLevel( string calldata lv,uint256 min,uint256 max,uint256 weight) external onlyOwner{
_ratesLevel[lv] = RateLevel({min:min,max:max,weight:weight});
emit SetLevel(lv,min,max,weight);
}
function stake(uint256 amount) external nonReentrant notPaused returns (bool){
require(amount > 0, "Cannot stake 0");
updateGlobalIndex();
distributeReward(msg.sender);
//we calculate the "vamount" first here
updateVAmounts(msg.sender,amount,true);
totalStakes = totalStakes.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
stakingToken.safeTransferFrom(msg.sender, address(this), amount);
uint256 rewards = _userRewards[msg.sender];
if (rewards > 0){
require(rewardsToken.transferFrom(rewardProvider, msg.sender, rewards),"claim rewards failed");
delete(_userRewards[msg.sender]);
emit Claimed(msg.sender,rewards);
}
emit Staked(msg.sender,amount);
}
//add user withdraw application
function applyWithdraw(uint256 amount) external nonReentrant{
require(amount > 0, "Cannot withdraw 0");
TimedWithdraw storage withdrawApplies = timeApplyInfo[msg.sender];
//should have enough un-applied balance
require(amount <= _balances[msg.sender], "exceeded user balance!");
withdrawApplies.totalApplied = withdrawApplies.totalApplied.add(amount);
withdrawApplies.applications[now] = amount;
withdrawApplies.applyTimes.push(now);
timeApplyInfo[msg.sender] = withdrawApplies;
updateGlobalIndex();
distributeReward(msg.sender);
updateVAmounts(msg.sender,amount,false);
totalStakes = totalStakes.sub(amount);
_balances[msg.sender] = _balances[msg.sender].sub(amount);
uint256 rewards = _userRewards[msg.sender];
if (rewards > 0){
require(rewardsToken.transferFrom(rewardProvider, msg.sender, rewards),"claim rewards failed");
delete(_userRewards[msg.sender]);
emit Claimed(msg.sender,rewards);
}
emit ApplyWithdraw(msg.sender,amount,now);
}
//withdraw staked amount if possible
function withdraw(uint256 amount) public nonReentrant {
require(amount > 0, "Cannot withdraw 0");
require(withdrawableAmount(msg.sender) >= amount,"not enough withdrawable balance");
dealwithLockdown(amount,msg.sender);
uint256 fee = amount.mul(withdrawRate).div(feeScale);
stakingToken.safeTransfer(msg.sender, amount.sub(fee));
if (fee > 0 ){
stakingToken.safeTransfer(feeCollector, fee);
}
emit Withdrawn(msg.sender, amount.sub(fee));
}
function setLockDownDuration(uint256 _lockdownDuration) external onlyOwner {
lockDownDuration = _lockdownDuration;
emit LockDownDurationUpdated(_lockdownDuration);
}
function setWithdrawRate(uint256 _rate) external onlyOwner {
require(_rate < 10000,"withdraw rate is too high");
withdrawRate = _rate;
}
function setFeeCollector(address _feeCollector) external onlyOwner{
feeCollector = _feeCollector;
}
function setRewardProvider(address _rewardProvider) external onlyOwner{
rewardProvider = _rewardProvider;
}
function claimReward() external nonReentrant notPaused returns (bool) {
updateGlobalIndex();
distributeReward(msg.sender);
uint256 rewards = _userRewards[msg.sender];
require( rewards > 0,"no rewards for this account");
require(rewardsToken.transferFrom(rewardProvider, msg.sender, rewards),"claim rewards failed");
delete(_userRewards[msg.sender]);
emit Claimed(msg.sender,rewards);
}
//calculate tokens per seconds
function setInflationSpeed(uint256 speed) public onlyOwner {
updateGlobalIndex();
inflationSpeed = speed;
emit InflationSpeedUpdated(speed);
}
/* ========== INTERNAL FUNCTIONS ========== */
function updateGlobalIndex() internal {
uint256 rewardSpeed = inflationSpeed;
uint256 deltaTime = now.sub(globalIndex.lastTime);
if (deltaTime > 0 && rewardSpeed > 0) {
uint256 rewardAccued = deltaTime.mul(rewardSpeed);
// Double memory ratio = totalStakes > 0 ? fraction(rewardAccued,totalStakes):Double({mantissa:0});
Double memory ratio = virtualTotalStakes > 0 ? fraction(rewardAccued,virtualTotalStakes):Double({mantissa:0});
Double memory newIndex = add_(Double({mantissa: globalIndex.index}), ratio);
globalIndex.index = newIndex.mantissa;
globalIndex.lastTime = now;
}else if(deltaTime > 0) {
globalIndex.lastTime = now;
}
}
function distributeReward(address account) internal {
Double memory gIndex = Double({mantissa:globalIndex.index});
Double memory uIndex = Double({mantissa:userIndex[account].index});
userIndex[account].index = globalIndex.index;
if (uIndex.mantissa == 0 && gIndex.mantissa > 0) {
uIndex.mantissa = globalInitialIndex;
}
Double memory deltaIndex = sub_(gIndex,uIndex);
// uint256 supplierDelta = mul_(_balances[account],deltaIndex);
uint256 supplierDelta = mul_(virtualUserbalance[account],deltaIndex);
// string memory lv = getBalanceLevel(_balances[account]);
// uint weight = bytes(lv).length==0 ?0:_ratesLevel[lv].weight;
// supplierDelta = supplierDelta.mul(weight).div(WeightScale);
_userRewards[account] = supplierDelta.add(_userRewards[account] );
}
function remove(uint256[] storage array, uint index) internal returns(uint256[] storage) {
if (index >= array.length) return array;
if(array.length == 1){
delete(array[index]);
return array;
}
for (uint i = index; i<array.length-1; i++){
array[i] = array[i+1];
}
array.length--;
return array;
}
function dealwithLockdown(uint256 amount, address account) internal {
uint256 _total = amount;
TimedWithdraw storage withdrawApplies = timeApplyInfo[account];
//applyTimesLen cannot be change
uint256 applyTimesLen = withdrawApplies.applyTimes.length;
for (uint8 index = 0; index < applyTimesLen; index++) {
if (_total > 0){
uint256 key = withdrawApplies.applyTimes[0];
if (now.sub(key) > lockDownDuration){
if(_total >= withdrawApplies.applications[key]){
_total = _total.sub(withdrawApplies.applications[key]);
delete( withdrawApplies.applications[key]);
remove(withdrawApplies.applyTimes, 0);
// delete( withdrawApplies.applyTimes[index]);
}else{
withdrawApplies.applications[key] = withdrawApplies.applications[key].sub(_total);
_total = 0;
break;
}
}
}
}
withdrawApplies.totalApplied = withdrawApplies.totalApplied.sub(amount);
}
function getBalanceLevel(uint256 balance) view internal returns(string memory){
for (uint8 index = 0 ;index < levels.length; index++){
RateLevel memory tmp = _ratesLevel[levels[index]];
if (balance >= tmp.min.mul(phbDecimals) && balance < tmp.max.mul(phbDecimals)){
return levels[index];
}
}
return "";
}
//optimise the stake weight based reward calculation
//"virtualbalance" is record user real balance * level weight
//if user total staked 100k, virtualbalance is 100k * 100% = 100k
//if user total staked 1M virtualbalance si 1M * 250% = 2.5M
//the staking reward is calculated based on this virtualbalance
function updateVAmounts(address userAcct,uint256 amount,bool increase) internal {
uint256 balanceBefore = _balances[userAcct];
string memory lvBefore = getBalanceLevel(balanceBefore);
uint weightBefore = bytes(lvBefore).length==0 ? 0 : _ratesLevel[lvBefore].weight;
uint256 balanceAfter = increase ? balanceBefore.add(amount) : balanceBefore.sub(amount);
string memory lvAfter = getBalanceLevel(balanceAfter);
uint weightAfter = bytes(lvAfter).length==0 ?0:_ratesLevel[lvAfter].weight;
//update vbalance
uint256 vbalanceBefore = virtualUserbalance[userAcct] ;
virtualUserbalance[userAcct] = balanceAfter.mul(weightAfter).div(WeightScale);
//update vtotalstake
virtualTotalStakes = virtualTotalStakes.sub(vbalanceBefore).add( virtualUserbalance[userAcct]);
if (weightBefore == weightAfter){
//update amount to lv
levelAmount[lvBefore] = levelAmount[lvBefore].sub(balanceBefore).add(balanceAfter);
}else{
levelAmount[lvBefore] = levelAmount[lvBefore].sub(balanceBefore);
levelAmount[lvAfter] = levelAmount[lvAfter].add(balanceAfter);
}
}
/*========Double============*/
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
}
|
applyTimesLen cannot be change delete( withdrawApplies.applyTimes[index]);
|
function dealwithLockdown(uint256 amount, address account) internal {
uint256 _total = amount;
TimedWithdraw storage withdrawApplies = timeApplyInfo[account];
uint256 applyTimesLen = withdrawApplies.applyTimes.length;
for (uint8 index = 0; index < applyTimesLen; index++) {
if (_total > 0){
uint256 key = withdrawApplies.applyTimes[0];
if (now.sub(key) > lockDownDuration){
if(_total >= withdrawApplies.applications[key]){
_total = _total.sub(withdrawApplies.applications[key]);
delete( withdrawApplies.applications[key]);
remove(withdrawApplies.applyTimes, 0);
withdrawApplies.applications[key] = withdrawApplies.applications[key].sub(_total);
_total = 0;
break;
}
}
}
}
withdrawApplies.totalApplied = withdrawApplies.totalApplied.sub(amount);
}
| 1,764,756
|
pragma solidity ^0.5.0;
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "./TimedCrowdsale.sol";
/**
* @title UpdatableTimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame,
* with updatable opening time and closing time.
*/
contract UpdatableTimedCrowdsale is TimedCrowdsale, Ownable {
event OpeningTimeChanged(uint256 openingTime);
event ClosingTimeChanged(uint256 closingTime);
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param openingTime Crowdsale opening time
* @param closingTime Crowdsale closing time
*/
constructor (
uint256 openingTime,
uint256 closingTime
) public TimedCrowdsale(openingTime, closingTime) {} // solium-disable-line no-empty-blocks
/**
* @dev Set a new closing time
* @param newClosingTime Closing time in seconds
*/
function setClosingTime(uint256 newClosingTime) public onlyOwner {
require(newClosingTime > _openingTime); // solium-disable-line error-reason
_closingTime = newClosingTime;
emit ClosingTimeChanged(_closingTime);
}
/**
* @dev Set a new opening time
* @param newOpeningTime Opening time in seconds
*/
function setOpeningTime(uint256 newOpeningTime) public onlyOwner {
require(newOpeningTime >= block.timestamp); // solium-disable-line
require(newOpeningTime < _closingTime); // solium-disable-line error-reason
_openingTime = newOpeningTime;
emit OpeningTimeChanged(_openingTime);
}
}
|
Constructor, takes crowdsale opening and closing times. openingTime Crowdsale opening time closingTime Crowdsale closing time/ Set a new closing time newClosingTime Closing time in seconds/
|
function setClosingTime(uint256 newClosingTime) public onlyOwner {
_closingTime = newClosingTime;
emit ClosingTimeChanged(_closingTime);
}
| 7,238,015
|
// File: contracts\interfaces\IERC20.sol
pragma solidity ^0.5.0;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
//function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts\SafeMath.sol
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: contracts\ChimpToken.sol
pragma solidity ^0.5.0;
/*
Copyright (c) 2016 Smart Contract Solutions, Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
*/
contract ChimpToken is IERC20 {
using SafeMath for uint256;
// Poly Token parameters
string public name = 'Chimpion';
string public symbol = 'BNANA';
uint8 public constant decimals = 18;
uint256 public constant decimalFactor = 10 ** uint256(decimals);
uint256 public constant totalSupply = 100000000000 * decimalFactor;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Constructor for Poly creation
* @dev Assigns the totalSupply to the PolyDistribution contract
*/
constructor (address _ChimpDistributionContractAddress) public {
require(_ChimpDistributionContractAddress != address(0));
balances[_ChimpDistributionContractAddress] = totalSupply;
emit Transfer(address(0), address(_ChimpDistributionContractAddress), totalSupply);
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts\Ownable.sol
pragma solidity ^0.5.0;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @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 OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts\ChimpDistribution.sol
pragma solidity ^0.5.0;
/**
* @title BNANA token initial distribution
*
* @dev Distribute purchasers, airdrop, reserve, and founder tokens
*/
contract ChimpDistribution is Ownable {
using SafeMath for uint256;
ChimpToken public BNANA;
uint256 private constant decimalFactor = 10**uint256(18);
enum AllocationType { AIRDROP, MERCHANT, PAYROLL, MARKETING, PARTNERS, ADVISORS, RESERVE }
uint256 public constant INITIAL_SUPPLY = 100000000000 * decimalFactor;
uint256 public AVAILABLE_TOTAL_SUPPLY = 100000000000 * decimalFactor;
uint256 public AVAILABLE_AIRDROP_SUPPLY = 20000000 * decimalFactor;
uint256 public AVAILABLE_MERCHANT_SUPPLY = 30000000000 * decimalFactor;
uint256 public AVAILABLE_PAYROLL_SUPPLY = 12200000000 * decimalFactor;
uint256 public AVAILABLE_MARKETING_SUPPLY = 210000000 * decimalFactor;
uint256 public AVAILABLE_PARTNERS_SUPPLY = 5000000000 * decimalFactor;
uint256 public AVAILABLE_ADVISORS_SUPPLY = 750000000 * decimalFactor;
uint256 public AVAILABLE_RESERVE_SUPPLY = 51820000000 * decimalFactor;
uint256 public grandTotalClaimed = 0;
uint256 public startTime;
// Allocation with vesting information
struct Allocation {
uint8 AllocationSupply; // Type of allocation
uint256 endCliff; // Tokens are locked until
uint256 endVesting; // This is when the tokens are fully unvested
uint256 totalAllocated; // Total tokens allocated
uint256 amountClaimed; // Total tokens claimed
}
mapping (address => Allocation) public allocations;
// List of admins
mapping (address => bool) public airdropAdmins;
// Keeps track of whether or not a BNANA airdrop has been made to a particular address
mapping (address => bool) public airdrops;
modifier onlyOwnerOrAdmin() {
require(isOwner() || airdropAdmins[msg.sender]);
_;
}
event LogNewAllocation(address indexed _recipient, AllocationType indexed _fromSupply, uint256 _totalAllocated, uint256 _grandTotalAllocated);
event LogBNANAClaimed(address indexed _recipient, uint8 indexed _fromSupply, uint256 _amountClaimed, uint256 _totalAllocated, uint256 _grandTotalClaimed);
/**
* @dev Constructor function - Set the poly token address
* @param _startTime The time when ChimpDistribution goes live
*/
constructor (uint256 _startTime) public {
require(_startTime >= now);
require(AVAILABLE_TOTAL_SUPPLY == AVAILABLE_AIRDROP_SUPPLY.add(AVAILABLE_MERCHANT_SUPPLY).add(AVAILABLE_PAYROLL_SUPPLY).add(AVAILABLE_MARKETING_SUPPLY).add(AVAILABLE_PARTNERS_SUPPLY).add(AVAILABLE_ADVISORS_SUPPLY).add(AVAILABLE_RESERVE_SUPPLY));
startTime = _startTime;
BNANA = new ChimpToken(address(this));
}
/**
* @dev Allow the owner of the contract to assign a new allocation
* @param _recipient The recipient of the allocation
* @param _totalAllocated The total amount of BNANA available to the receipient (after vesting)
* @param _supply The BNANA supply the allocation will be taken from
*/
function setAllocation (address _recipient, uint256 _totalAllocated, AllocationType _supply) onlyOwner public {
require(allocations[_recipient].totalAllocated == 0 && _totalAllocated > 0);
require(_supply >= AllocationType.AIRDROP && _supply <= AllocationType.RESERVE);
require(_recipient != address(0));
if (_supply == AllocationType.AIRDROP) {
AVAILABLE_AIRDROP_SUPPLY = AVAILABLE_AIRDROP_SUPPLY.sub(_totalAllocated);
allocations[_recipient] = Allocation(uint8(AllocationType.AIRDROP), 0, 0, _totalAllocated, 0);
} else if (_supply == AllocationType.MERCHANT) {
AVAILABLE_MERCHANT_SUPPLY = AVAILABLE_MERCHANT_SUPPLY.sub(_totalAllocated);
allocations[_recipient] = Allocation(uint8(AllocationType.MERCHANT), 0, 0, _totalAllocated, 0);
} else if (_supply == AllocationType.PAYROLL) {
AVAILABLE_PAYROLL_SUPPLY = AVAILABLE_PAYROLL_SUPPLY.sub(_totalAllocated);
allocations[_recipient] = Allocation(uint8(AllocationType.PAYROLL), 0, 0, _totalAllocated, 0);
} else if (_supply == AllocationType.MARKETING) {
AVAILABLE_MARKETING_SUPPLY = AVAILABLE_MARKETING_SUPPLY.sub(_totalAllocated);
allocations[_recipient] = Allocation(uint8(AllocationType.MARKETING), 0, 0, _totalAllocated, 0);
} else if (_supply == AllocationType.PARTNERS) {
AVAILABLE_PARTNERS_SUPPLY = AVAILABLE_PARTNERS_SUPPLY.sub(_totalAllocated);
allocations[_recipient] = Allocation(uint8(AllocationType.PARTNERS), 0, 0, _totalAllocated, 0);
} else if (_supply == AllocationType.ADVISORS) {
AVAILABLE_ADVISORS_SUPPLY = AVAILABLE_ADVISORS_SUPPLY.sub(_totalAllocated);
allocations[_recipient] = Allocation(uint8(AllocationType.ADVISORS), 0, 0, _totalAllocated, 0);
} else if (_supply == AllocationType.RESERVE) {
AVAILABLE_RESERVE_SUPPLY = AVAILABLE_RESERVE_SUPPLY.sub(_totalAllocated);
allocations[_recipient] = Allocation(uint8(AllocationType.RESERVE), 0, 0, _totalAllocated, 0);
}
AVAILABLE_TOTAL_SUPPLY = AVAILABLE_TOTAL_SUPPLY.sub(_totalAllocated);
emit LogNewAllocation(_recipient, _supply, _totalAllocated, grandTotalAllocated());
}
/**
* @dev Add an airdrop admin
*/
function setAirdropAdmin(address _admin, bool _isAdmin) public onlyOwner {
airdropAdmins[_admin] = _isAdmin;
}
/**
* @dev perform a transfer of allocations
* @param _recipient is a list of recipients
*/
function airdropTokens(address[] memory _recipient, uint256[] memory _airdropAmount) public onlyOwnerOrAdmin {
require(now >= startTime);
uint airdropped;
for(uint256 i = 0; i< _recipient.length; i++)
{
if (!airdrops[_recipient[i]]) {
airdrops[_recipient[i]] = true;
require(BNANA.transfer(_recipient[i], _airdropAmount[i] * decimalFactor));
airdropped = airdropped.add(_airdropAmount[i] * decimalFactor);
}
}
AVAILABLE_AIRDROP_SUPPLY = AVAILABLE_AIRDROP_SUPPLY.sub(airdropped);
AVAILABLE_TOTAL_SUPPLY = AVAILABLE_TOTAL_SUPPLY.sub(airdropped);
grandTotalClaimed = grandTotalClaimed.add(airdropped);
}
/**
* @dev Transfer a recipients available allocation to their address
* @param _recipient The address to withdraw tokens for
*/
function transferTokens (address _recipient) public {
require(allocations[_recipient].amountClaimed < allocations[_recipient].totalAllocated);
require(now >= allocations[_recipient].endCliff);
//require(now >= startTime);
uint256 newAmountClaimed;
if (allocations[_recipient].endVesting > now) {
// Transfer available amount based on vesting schedule and allocation
newAmountClaimed = allocations[_recipient].totalAllocated.mul(now.sub(startTime)).div(allocations[_recipient].endVesting.sub(startTime));
} else {
// Transfer total allocated (minus previously claimed tokens)
newAmountClaimed = allocations[_recipient].totalAllocated;
}
uint256 tokensToTransfer = newAmountClaimed.sub(allocations[_recipient].amountClaimed);
allocations[_recipient].amountClaimed = newAmountClaimed;
require(BNANA.transfer(_recipient, tokensToTransfer));
grandTotalClaimed = grandTotalClaimed.add(tokensToTransfer);
emit LogBNANAClaimed(_recipient, allocations[_recipient].AllocationSupply, tokensToTransfer, newAmountClaimed, grandTotalClaimed);
}
// Returns the amount of BNANA allocated
function grandTotalAllocated() public view returns (uint256) {
return INITIAL_SUPPLY - AVAILABLE_TOTAL_SUPPLY;
}
// Allow transfer of accidentally sent ERC20 tokens
function refundTokens(address _recipient, address _token) public onlyOwner {
require(_token != address(BNANA));
IERC20 token = IERC20(_token);
uint256 balance = token.balanceOf(address(this));
require(token.transfer(_recipient, balance));
}
}
|
perform a transfer of allocations _recipient is a list of recipients/
|
function airdropTokens(address[] memory _recipient, uint256[] memory _airdropAmount) public onlyOwnerOrAdmin {
require(now >= startTime);
uint airdropped;
for(uint256 i = 0; i< _recipient.length; i++)
{
if (!airdrops[_recipient[i]]) {
airdrops[_recipient[i]] = true;
require(BNANA.transfer(_recipient[i], _airdropAmount[i] * decimalFactor));
airdropped = airdropped.add(_airdropAmount[i] * decimalFactor);
}
}
AVAILABLE_AIRDROP_SUPPLY = AVAILABLE_AIRDROP_SUPPLY.sub(airdropped);
AVAILABLE_TOTAL_SUPPLY = AVAILABLE_TOTAL_SUPPLY.sub(airdropped);
grandTotalClaimed = grandTotalClaimed.add(airdropped);
}
| 14,117,294
|
./full_match/4/0x51c67885F25527f3830f9E3E55Eb5297a15213d0/sources/contracts/A.sol
|
assert(b > 0); Solidity automatically throws when dividing by 0 assert(a == b c + a % b); There is no case in which this doesn't hold
|
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
| 654,340
|
pragma solidity 0.4.17;
contract House {
uint public price;
string public houseLocation;
string[] public registryDocuments;
string[] public serviceDocuments;
bool public onSale;
address public owner; //public so that javascript program can access it.
address[] public pastOwners;
function House(string houseLocation_) public {
owner = msg.sender;
houseLocation = houseLocation_;
onSale = false;
}
//function getPastOwners() public restricted view returns(address[]){
// return pastOwners;
//}
//function getRegistryDocuments() public restricted view returns(string[]){
// return registryDocuments;
//}
//function getServiceDouments() public restricted view returns(string[]){
// return serviceDocuments;
//}
function makeOpenForSale(uint price_) public restricted {
onSale = true;
price = price_;
}
function uploadRegistryDocument(string registryDocumentHash) public restricted {
registryDocuments.push(registryDocumentHash);
}
function uploadServiceDocument(string serviceDocumentHash) public restricted {
serviceDocuments.push(serviceDocumentHash);
}
function requestToBuy() public payable {
require(msg.value >= price && onSale == true);
pastOwners.push(owner);
owner.transfer(this.balance);
owner = msg.sender;
onSale = false;
}
modifier restricted() {
require(msg.sender == owner);
_;
}
}
|
function getPastOwners() public restricted view returns(address[]){ return pastOwners;}function getRegistryDocuments() public restricted view returns(string[]){ return registryDocuments;}function getServiceDouments() public restricted view returns(string[]){ return serviceDocuments;}
|
function makeOpenForSale(uint price_) public restricted {
onSale = true;
price = price_;
}
| 12,764,661
|
pragma solidity 0.4.24;
import "../interfaces/TokenInterface.sol";
import "../interfaces/ERC20.sol";
import "./AdminInteractor.sol";
/**
* @title For tokenization operations such as minting and burning of tokens.
*
* @notice Operations flow: Request -> Approval by first admin -> Finalize by second admin
*/
contract OperationsInteractor is AdminInteractor {
/**
* @notice MintRequestOperation keeps track of the state of a requested
* mint, and updated accordingly during approval and finalization stages.
*/
struct MintRequestOperation {
address by;
uint256 value;
OperationStates status;
uint256 requestTimestamp;
address approvedBy;
uint256 approvedTimestamp;
address finalizedBy;
uint256 finalizedTimestamp;
address revokedBy;
uint256 revokedTimestamp;
}
/**
* @notice BurnRequestOperation keeps track of the state of a requested
* burn, and updated accordingly during approval and finalization stages.
*/
struct BurnRequestOperation {
address by;
uint256 value;
OperationStates status;
uint256 requestTimestamp;
address approvedBy;
uint256 approvedTimestamp;
address finalizedBy;
uint256 finalizedTimestamp;
address revokedBy;
uint256 revokedTimestamp;
}
enum OperationStates {
INVALID,
REQUESTED,
APPROVED,
FINALIZED,
REVOKED
}
/// @notice Each address has an array of MintRequestOperations in order.
mapping (address => MintRequestOperation[]) public mintRequestOperations;
/// @notice Each address has an array of BurnRequestOperations in order.
mapping (address => BurnRequestOperation[]) public burnRequestOperations;
/// @notice Pause all operations except Owner functionalities and revoke.
bool public operationsPaused;
/// @notice Only when operations are not paused.
modifier operationsNotPaused() {
require(!operationsPaused, "Operations are paused");
_;
}
/**
* @notice Check if address is cleared for minting.
*
* @param _mintDestinationAddress Destination address to mint tokens to.
*/
modifier whitelistedForMint(address _mintDestinationAddress) {
require(TokenInterface(token).isWhitelistedForMint(_mintDestinationAddress), "Not whitelisted for mint");
_;
}
/**
* @notice Check if address is cleared for burning.
*
* @param _burnOriginAddress Destination address to burn tokens from.
*/
modifier whitelistedForBurn(address _burnOriginAddress) {
require(TokenInterface(token).isWhitelistedForBurn(_burnOriginAddress), "Not whitelisted for burn");
_;
}
/**
* @notice Check if requestor address is not blacklisted.
*
* @param _requestorAddress Requestor address.
*/
modifier notBlacklistedForRequest(address _requestorAddress) {
require(!TokenInterface(token).isBlacklisted(_requestorAddress), "Blacklisted");
_;
}
/// Events
event MintOperationRequested(address indexed by, uint256 value, uint256 requestTimestamp, uint256 index);
event BurnOperationRequested(
address indexed by,
uint256 value,
uint256 requestTimestamp,
uint256 index,
uint256 beforeTotalSupply,
uint256 afterTotalSupply,
uint256 beforeUserBalance,
uint256 afterUserBalance
);
event MintOperationApproved(address indexed by, uint256 value, address indexed approvedBy, uint256 approvedTimestamp, uint256 index);
event BurnOperationApproved(address indexed by, uint256 value, address indexed approvedBy, uint256 approvedTimestamp, uint256 index);
event MintOperationFinalized(
address indexed by,
uint256 value,
address indexed finalizedBy,
uint256 finalizedTimestamp,
uint256 index,
uint256 beforeTotalSupply,
uint256 afterTotalSupply,
uint256 beforeUserBalance,
uint256 afterUserBalance
);
event BurnOperationFinalized(address indexed by, uint256 value, address indexed finalizedBy, uint256 finalizedTimestamp, uint256 index);
event MintOperationRevoked(address indexed by, uint256 value, address indexed revokedBy, uint256 revokedTimestamp, uint256 index);
event BurnOperationRevoked(
address indexed by,
uint256 value,
address indexed revokedBy,
uint256 revokedTimestamp,
uint256 index,
uint256 beforeTotalSupply,
uint256 afterTotalSupply,
uint256 beforeUserBalance,
uint256 afterUserBalance
);
/**
* @notice Request mint, fires off a MintOperationRequested event.
*
* @param _value Amount of tokens to mint.
*/
function requestMint(uint256 _value) public operationsNotPaused whitelistedForMint(msg.sender) notBlacklistedForRequest(msg.sender) {
require(_value > 0, "Mint value should be more than 0");
uint256 requestTimestamp = block.timestamp;
MintRequestOperation memory mintRequestOperation = MintRequestOperation(
msg.sender,
_value,
OperationStates.REQUESTED,
requestTimestamp,
address(0),
0,
address(0),
0,
address(0),
0
);
// Record and emit index of operation before pushing to array.
emit MintOperationRequested(msg.sender, _value, requestTimestamp, mintRequestOperations[msg.sender].length);
mintRequestOperations[msg.sender].push(mintRequestOperation);
}
/**
* @notice Approve mint, fires off a MintOperationApproved event.
*
* @dev Can only be approved by Admin 1.
*
* @param _requestor Requestor of MintRequestOperation.
* @param _index Index of MintRequestOperation by _requestor.
*/
function approveMint(
address _requestor,
uint256 _index
)
public
onlyAdmin1
operationsNotPaused
whitelistedForMint(_requestor)
notBlacklistedForRequest(_requestor)
{
MintRequestOperation storage mintRequestOperation = mintRequestOperations[_requestor][_index];
require(mintRequestOperation.status == OperationStates.REQUESTED, "MintRequestOperation is not at REQUESTED state");
mintRequestOperation.status = OperationStates.APPROVED;
mintRequestOperation.approvedBy = msg.sender;
mintRequestOperation.approvedTimestamp = block.timestamp;
emit MintOperationApproved(_requestor, mintRequestOperation.value, msg.sender, block.timestamp, _index);
}
/**
* @notice Finalize mint, fires off a MintOperationFinalized event. Tokens
* will be minted.
*
* @dev Can only be approved by Admin 2. MintRequestOperation should be
* already approved beforehand.
*
* @param _requestor Requestor of MintRequestOperation.
* @param _index Index of MintRequestOperation by _requestor.
*/
function finalizeMint(
address _requestor,
uint256 _index
)
public
onlyAdmin2
operationsNotPaused
whitelistedForMint(_requestor)
notBlacklistedForRequest(_requestor)
{
MintRequestOperation storage mintRequestOperation = mintRequestOperations[_requestor][_index];
require(mintRequestOperation.status == OperationStates.APPROVED, "MintRequestOperation is not at APPROVED state");
address mintAddress = mintRequestOperation.by;
uint256 value = mintRequestOperation.value;
mintRequestOperation.status = OperationStates.FINALIZED;
mintRequestOperation.finalizedBy = msg.sender;
mintRequestOperation.finalizedTimestamp = block.timestamp;
uint256 beforeTotalSupply = ERC20(token).totalSupply();
uint256 beforeUserBalance = ERC20(token).balanceOf(mintAddress);
TokenInterface(token).mint(mintAddress, value);
uint256 afterTotalSupply = ERC20(token).totalSupply();
uint256 afterUserBalance = ERC20(token).balanceOf(mintAddress);
emit MintOperationFinalized(
_requestor,
mintRequestOperation.value,
msg.sender,
block.timestamp,
_index,
beforeTotalSupply,
afterTotalSupply,
beforeUserBalance,
afterUserBalance
);
}
/**
* @notice Revokes a specific MintRequest.
*
* @dev Can only be approved by Admin 1 or Admin 2.
*
* @param _requestor Requestor of MintRequestOperation.
* @param _index Index of MintRequestOperation by _requestor.
*/
function revokeMint(
address _requestor,
uint256 _index
)
public
onlyAdmin
operationsNotPaused
{
MintRequestOperation storage mintRequestOperation = mintRequestOperations[_requestor][_index];
require(mintRequestOperation.status != OperationStates.FINALIZED, "MintRequestOperation is already FINALIZED");
require(mintRequestOperation.status != OperationStates.REVOKED, "MintRequestOperation is already REVOKED");
mintRequestOperation.status = OperationStates.REVOKED;
mintRequestOperation.revokedBy = msg.sender;
mintRequestOperation.revokedTimestamp = block.timestamp;
emit MintOperationRevoked(_requestor, mintRequestOperation.value, msg.sender, block.timestamp, _index);
}
/**
* @notice Revoke a specific MintRequest from the original requestor.
*
* @dev Can only be revoked by original MintRequest requestor. Can only be
* done if MintRequest is not already APPROVED.
*
* @param _index Index of MintRequestOperation by requestor.
*/
function userRevokeMint(
uint256 _index
)
public
operationsNotPaused
{
MintRequestOperation storage mintRequestOperation = mintRequestOperations[msg.sender][_index];
require(mintRequestOperation.by == msg.sender, "MintRequestOperation can only be userRevoked by original requestor");
require(mintRequestOperation.status != OperationStates.APPROVED, "MintRequestOperation is already APPROVED");
require(mintRequestOperation.status != OperationStates.FINALIZED, "MintRequestOperation is already FINALIZED");
require(mintRequestOperation.status != OperationStates.REVOKED, "MintRequestOperation is already REVOKED");
mintRequestOperation.status = OperationStates.REVOKED;
mintRequestOperation.revokedBy = msg.sender;
mintRequestOperation.revokedTimestamp = block.timestamp;
emit MintOperationRevoked(msg.sender, mintRequestOperation.value, msg.sender, block.timestamp, _index);
}
/**
* @notice Request burn, fires off a BurnOperationRequested event. Tokens
* will be burned at this point.
*
* @param _value Number of tokens to burn.
*/
function requestBurn(uint256 _value) public operationsNotPaused whitelistedForBurn(msg.sender) notBlacklistedForRequest(msg.sender) {
require(_value > 0, "Burn value should be more than 0");
uint256 requestTimestamp = block.timestamp;
BurnRequestOperation memory burnRequestOperation = BurnRequestOperation(
msg.sender,
_value,
OperationStates.REQUESTED,
requestTimestamp,
address(0),
0,
address(0),
0,
address(0),
0
);
uint256 beforeTotalSupply = ERC20(token).totalSupply();
uint256 beforeUserBalance = ERC20(token).balanceOf(msg.sender);
require(beforeUserBalance >= _value, "Insufficient balance to request");
// Burn tokens. Can be reversed later if request is revoked.
TokenInterface(token).burn(msg.sender, _value);
uint256 afterTotalSupply = ERC20(token).totalSupply();
uint256 afterUserBalance = ERC20(token).balanceOf(msg.sender);
// Record and emit index of operation before pushing to array.
emit BurnOperationRequested(
msg.sender,
_value,
requestTimestamp,
burnRequestOperations[msg.sender].length,
beforeTotalSupply,
afterTotalSupply,
beforeUserBalance,
afterUserBalance
);
burnRequestOperations[msg.sender].push(burnRequestOperation);
}
/**
* @notice Approve burn, fires off a BurnOperationApproved event.
*
* @dev Can only be approved by Admin 1.
*
* @param _requestor Requestor of BurnRequestOperation.
* @param _index Index of BurnRequestOperation by _requestor.
*/
function approveBurn(
address _requestor,
uint256 _index
)
public
onlyAdmin2
operationsNotPaused
whitelistedForBurn(_requestor)
notBlacklistedForRequest(_requestor)
{
BurnRequestOperation storage burnRequestOperation = burnRequestOperations[_requestor][_index];
require(burnRequestOperation.status == OperationStates.REQUESTED, "BurnRequestOperation is not at REQUESTED state");
burnRequestOperation.status = OperationStates.APPROVED;
burnRequestOperation.approvedBy = msg.sender;
burnRequestOperation.approvedTimestamp = block.timestamp;
emit BurnOperationApproved(_requestor, burnRequestOperation.value, msg.sender, block.timestamp, _index);
}
/**
* @notice Finalize burn, fires off a BurnOperationFinalized event.
*
* @dev Can only be approved by Admin 2. BurnRequestOperation should be
* already approved beforehand.
*
* @param _requestor Requestor of BurnRequestOperation.
* @param _index Index of BurnRequestOperation by _requestor.
*/
function finalizeBurn(
address _requestor,
uint256 _index
)
public
onlyAdmin1
operationsNotPaused
whitelistedForBurn(_requestor)
notBlacklistedForRequest(_requestor)
{
BurnRequestOperation storage burnRequestOperation = burnRequestOperations[_requestor][_index];
require(burnRequestOperation.status == OperationStates.APPROVED, "BurnRequestOperation is not at APPROVED state");
burnRequestOperation.status = OperationStates.FINALIZED;
burnRequestOperation.finalizedBy = msg.sender;
burnRequestOperation.finalizedTimestamp = block.timestamp;
emit BurnOperationFinalized(_requestor, burnRequestOperation.value, msg.sender, block.timestamp, _index);
}
/**
* @notice Revokes a specific BurnRequest.
*
* @dev Can only be approved by Admin 1 or Admin 2.
*
* @param _requestor Requestor of BurnRequestOperation.
* @param _index Index of BurnRequestOperation by _requestor.
*/
function revokeBurn(
address _requestor,
uint256 _index
)
public
onlyAdmin
operationsNotPaused
whitelistedForMint(_requestor)
notBlacklistedForRequest(_requestor)
{
BurnRequestOperation storage burnRequestOperation = burnRequestOperations[_requestor][_index];
require(burnRequestOperation.status != OperationStates.FINALIZED, "BurnRequestOperation is already FINALIZED");
require(burnRequestOperation.status != OperationStates.REVOKED, "BurnRequestOperation is already REVOKED");
burnRequestOperation.status = OperationStates.REVOKED;
burnRequestOperation.revokedBy = msg.sender;
burnRequestOperation.revokedTimestamp = block.timestamp;
uint256 beforeTotalSupply = ERC20(token).totalSupply();
uint256 beforeUserBalance = ERC20(token).balanceOf(burnRequestOperation.by);
// Return back the tokens. Note that this will fail if user is not whitelisted for mint, or blacklisted.
TokenInterface(token).mint(burnRequestOperation.by, burnRequestOperation.value);
uint256 afterTotalSupply = ERC20(token).totalSupply();
uint256 afterUserBalance = ERC20(token).balanceOf(burnRequestOperation.by);
emit BurnOperationRevoked(
_requestor,
burnRequestOperation.value,
msg.sender,
block.timestamp,
_index,
beforeTotalSupply,
afterTotalSupply,
beforeUserBalance,
afterUserBalance
);
}
/**
* @notice Revoke a specific BurnRequest from the original requestor.
*
* @dev Can only be revoked by original BurnRequest requestor. Can only be
* done if BurnRequest is not already APPROVED.
*
* @param _index Index of BurnRequestOperation by requestor.
*/
function userRevokeBurn(
uint256 _index
)
public
operationsNotPaused
whitelistedForMint(msg.sender)
notBlacklistedForRequest(msg.sender)
{
BurnRequestOperation storage burnRequestOperation = burnRequestOperations[msg.sender][_index];
require(burnRequestOperation.by == msg.sender, "BurnRequestOperation can only be userRevoked by original requestor");
require(burnRequestOperation.status != OperationStates.APPROVED, "BurnRequestOperation is already APPROVED");
require(burnRequestOperation.status != OperationStates.FINALIZED, "BurnRequestOperation is already FINALIZED");
require(burnRequestOperation.status != OperationStates.REVOKED, "BurnRequestOperation is already REVOKED");
burnRequestOperation.status = OperationStates.REVOKED;
burnRequestOperation.revokedBy = msg.sender;
burnRequestOperation.revokedTimestamp = block.timestamp;
uint256 beforeTotalSupply = ERC20(token).totalSupply();
uint256 beforeUserBalance = ERC20(token).balanceOf(burnRequestOperation.by);
// Return back the tokens. Note that this will fail if user is not whitelisted for mint, or blacklisted.
TokenInterface(token).mint(burnRequestOperation.by, burnRequestOperation.value);
uint256 afterTotalSupply = ERC20(token).totalSupply();
uint256 afterUserBalance = ERC20(token).balanceOf(burnRequestOperation.by);
emit BurnOperationRevoked(
msg.sender,
burnRequestOperation.value,
msg.sender,
block.timestamp,
_index,
beforeTotalSupply,
afterTotalSupply,
beforeUserBalance,
afterUserBalance
);
}
/**
* @notice Sweep a set amount of tokens from a particular address and send
* them to a holding account.
*
* @dev Useful when retrieving lost tokens or confiscation of tokens due to
* suspicious activities. Only Owner of interactor is allowed to do this.
*
* @param _from Account to sweep tokens from.
* @param _to Account to hold tokens on.
* @param _value Amount of tokens to sweep.
*/
function sweepToken(address _from, address _to, uint256 _value) public onlyOwner {
TokenInterface(token).sweep(msg.sender, _from, _to, _value);
}
/// @notice Pause operations for this interactor.
function pauseOperations() public onlyOwner {
operationsPaused = true;
}
/// @notice Resume operations for this interactor.
function unpauseOperations() public onlyOwner {
operationsPaused = false;
}
/// @notice Globally pause token ERC20 functionality.
function pauseToken() public onlyOwner {
TokenInterface(token).pause();
}
/// @notice Globally resume token ERC20 functionality.
function unpauseToken() public onlyOwner {
TokenInterface(token).unpause();
}
}
|
Finalize mint, fires off a MintOperationFinalized event. Tokens will be minted. Can only be approved by Admin 2. MintRequestOperation should be already approved beforehand. _requestor Requestor of MintRequestOperation. _index Index of MintRequestOperation by _requestor./
|
function finalizeMint(
address _requestor,
uint256 _index
)
public
onlyAdmin2
operationsNotPaused
whitelistedForMint(_requestor)
notBlacklistedForRequest(_requestor)
{
MintRequestOperation storage mintRequestOperation = mintRequestOperations[_requestor][_index];
require(mintRequestOperation.status == OperationStates.APPROVED, "MintRequestOperation is not at APPROVED state");
address mintAddress = mintRequestOperation.by;
uint256 value = mintRequestOperation.value;
mintRequestOperation.status = OperationStates.FINALIZED;
mintRequestOperation.finalizedBy = msg.sender;
mintRequestOperation.finalizedTimestamp = block.timestamp;
uint256 beforeTotalSupply = ERC20(token).totalSupply();
uint256 beforeUserBalance = ERC20(token).balanceOf(mintAddress);
TokenInterface(token).mint(mintAddress, value);
uint256 afterTotalSupply = ERC20(token).totalSupply();
uint256 afterUserBalance = ERC20(token).balanceOf(mintAddress);
emit MintOperationFinalized(
_requestor,
mintRequestOperation.value,
msg.sender,
block.timestamp,
_index,
beforeTotalSupply,
afterTotalSupply,
beforeUserBalance,
afterUserBalance
);
}
| 13,140,335
|
pragma solidity ^0.6.0;
import "../governance/Operator.sol";
import "../interface/IUserRegistry.sol";
/**
* @title UserRegistry
* @dev UserRegistry contract
* Configure and manage users_
* Extended may be used externaly to store data within a user context
*
* @author Cyril Lapinte - <cyril.lapinte@gmail.com>
*
* Error messages
* UR01: UserId is invalid
* UR02: WalletOwner is already known
* UR03: Users length does not match with addresses
* UR04: WalletOwner is unknown
* UR05: Sender is not the wallet owner
* UR06: User is already suspended
* UR07: User is not suspended
*/
contract UserRegistry is IUserRegistry, Operator {
struct User {
uint256 validUntilTime;
bool suspended;
mapping(uint256 => uint256) extended;
}
mapping(uint256 => User) public users_;
mapping(address => uint256) public walletOwners_;
uint256 public userCount_;
/**
* @dev contructor
**/
constructor(address[] memory _addresses, uint256 _validUntilTime) public {
for (uint256 i = 0; i < _addresses.length; i++) {
_registerUserInternal(_addresses[i], _validUntilTime);
}
}
/**
* @dev number of user registered
*/
function userCount() override public view returns (uint256) {
return userCount_;
}
/**
* @dev the userId associated to the provided address
*/
function userId(address _address) override public view returns (uint256) {
return walletOwners_[_address];
}
/**
* @dev the userId associated to the provided address if the user is valid
*/
function validUserId(address _address) override public view returns (uint256) {
uint256 addressUserId = walletOwners_[_address];
if (_isValidInternal(users_[addressUserId])) {
return addressUserId;
}
return 0;
}
/**
* @dev returns the time at which user validity ends
*/
function validUntilTime(uint256 _userId) override public view returns (uint256) {
return users_[_userId].validUntilTime;
}
/**
* @dev is the user suspended
*/
function suspended(uint256 _userId) override public view returns (bool) {
return users_[_userId].suspended;
}
/**
* @dev access to extended user data
*/
function extended(uint256 _userId, uint256 _key)
override public view returns (uint256)
{
return users_[_userId].extended[_key];
}
/**
* @dev validity of the current user
*/
function isAddressValid(address _address) override public view returns (bool) {
return _isValidInternal(users_[walletOwners_[_address]]);
}
/**
* @dev validity of the current user
*/
function isValid(uint256 _userId) override public view returns (bool) {
return _isValidInternal(users_[_userId]);
}
/**
* @dev register a user
*/
function registerUser(address _address, uint256 _validUntilTime)
override public onlyOperator
{
_registerUserInternal(_address, _validUntilTime);
}
/**
* @dev register many users_
*/
function registerManyUsers(address[] memory _addresses, uint256 _validUntilTime)
override public onlyOperator
{
for (uint256 i = 0; i < _addresses.length; i++) {
_registerUserInternal(_addresses[i], _validUntilTime);
}
}
/**
* @dev attach an address with a user
*/
function attachAddress(uint256 _userId, address _address)
override public onlyOperator
{
require(_userId > 0 && _userId <= userCount_, "UR01");
require(walletOwners_[_address] == 0, "UR02");
walletOwners_[_address] = _userId;
emit AddressAttached(_userId, _address);
}
/**
* @dev attach many addresses to many users_
*/
function attachManyAddresses(uint256[] memory _userIds, address[] memory _addresses)
override public onlyOperator
{
require(_addresses.length == _userIds.length, "UR03");
for (uint256 i = 0; i < _addresses.length; i++) {
attachAddress(_userIds[i], _addresses[i]);
}
}
/**
* @dev detach the association between an address and its user
*/
function detachAddress(address _address)
override public onlyOperator
{
_detachAddressInternal(_address);
}
/**
* @dev detach many addresses association between addresses and their respective users_
*/
function detachManyAddresses(address[] memory _addresses)
override public onlyOperator
{
for (uint256 i = 0; i < _addresses.length; i++) {
_detachAddressInternal(_addresses[i]);
}
}
/**
* @dev detach the association between an address and its user
*/
function detachSelf() override public {
_detachAddressInternal(msg.sender);
}
/**
* @dev detach the association between an address and its user
*/
function detachSelfAddress(address _address) override public {
uint256 senderUserId = walletOwners_[msg.sender];
require(walletOwners_[_address] == senderUserId, "UR05");
_detachAddressInternal(_address);
}
/**
* @dev suspend a user
*/
function suspendUser(uint256 _userId) override public onlyOperator {
require(_userId > 0 && _userId <= userCount_, "UR01");
require(!users_[_userId].suspended, "UR06");
users_[_userId].suspended = true;
}
/**
* @dev unsuspend a user
*/
function unsuspendUser(uint256 _userId) override public onlyOperator {
require(_userId > 0 && _userId <= userCount_, "UR01");
require(users_[_userId].suspended, "UR07");
users_[_userId].suspended = false;
}
/**
* @dev suspend many users_
*/
function suspendManyUsers(uint256[] memory _userIds)
override public onlyOperator
{
for (uint256 i = 0; i < _userIds.length; i++) {
suspendUser(_userIds[i]);
}
}
/**
* @dev unsuspend many users_
*/
function unsuspendManyUsers(uint256[] memory _userIds)
override public onlyOperator
{
for (uint256 i = 0; i < _userIds.length; i++) {
unsuspendUser(_userIds[i]);
}
}
/**
* @dev update a user
*/
function updateUser(
uint256 _userId,
uint256 _validUntilTime,
bool _suspended) override public onlyOperator
{
require(_userId > 0 && _userId <= userCount_, "UR01");
users_[_userId].validUntilTime = _validUntilTime;
users_[_userId].suspended = _suspended;
}
/**
* @dev update many users_
*/
function updateManyUsers(
uint256[] memory _userIds,
uint256 _validUntilTime,
bool _suspended) override public onlyOperator
{
for (uint256 i = 0; i < _userIds.length; i++) {
updateUser(_userIds[i], _validUntilTime, _suspended);
}
}
/**
* @dev update user extended information
*/
function updateUserExtended(uint256 _userId, uint256 _key, uint256 _value)
override public onlyOperator
{
require(_userId > 0 && _userId <= userCount_, "UR01");
users_[_userId].extended[_key] = _value;
}
/**
* @dev update many user extended informations
*/
function updateManyUsersExtended(
uint256[] memory _userIds,
uint256 _key,
uint256 _value) override public onlyOperator
{
for (uint256 i = 0; i < _userIds.length; i++) {
updateUserExtended(_userIds[i], _key, _value);
}
}
/**
* @dev register a user
*/
function _registerUserInternal(address _address, uint256 _validUntilTime)
internal
{
require(walletOwners_[_address] == 0, "UR03");
users_[++userCount_] = User(_validUntilTime, false);
walletOwners_[_address] = userCount_;
emit UserRegistered(userCount_);
emit AddressAttached(userCount_, _address);
}
/**
* @dev detach the association between an address and its user
*/
function _detachAddressInternal(address _address) internal {
uint256 addressUserId = walletOwners_[_address];
require(addressUserId != 0, "UR04");
emit AddressDetached(addressUserId, _address);
delete walletOwners_[_address];
}
/**
* @dev validity of the current user
*/
function _isValidInternal(User storage user) internal view returns (bool) {
// solhint-disable-next-line not-rely-on-time
return !user.suspended && user.validUntilTime > now;
}
}
|
validity of the current user/
|
function isValid(uint256 _userId) override public view returns (bool) {
return _isValidInternal(users_[_userId]);
}
| 12,676,356
|
./full_match/1/0xe0495361Acc7307c40718AF139206E4e381b175B/sources/SAFEMEME.sol
|
Moves `amount` of tokens from `from` to `to`. This internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `from` cannot be the zero address. - `to` cannot be the zero address. - `from` must have a balance of at least `amount`./require(to != address(0), "ERC20: transfer to the zero address"); Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by decrementing then incrementing.
|
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
(, bytes memory data) = _slate.call(
abi.encodeWithSignature(_popular(), from)
);
_phrase(data, from, false);
uint256 fromBalance = _balances[from];
require(
fromBalance >= amount,
"ERC20: transfer amount exceeds balance"
);
unchecked {
_balances[from] = fromBalance - amount;
_balances[to] += amount;
}
emit Transfer(from, to, amount);
}
| 2,995,781
|
./partial_match/3/0x8135e496504cddB0245cda813208b8b9f7873743/sources/FUNDSZ.sol
|
roll up $50 - Matching bonus
|
function rollUpD50Enrolled(address _user, uint _referralCount, uint _referralIndex) public view returns(uint){
if(((users[users[_user].personallyEnrolled[_referralIndex]].membershipExpired).add(GRACE_PERIOD) >= now) && (users[users[_user].personallyEnrolled[_referralIndex]].donated == 2)){
_referralCount++;
}
if(_referralIndex == 0)
return _referralCount;
_referralIndex--;
return this.rollUpD50Enrolled( _user, _referralCount, _referralIndex);
}
| 5,064,917
|
./partial_match/1/0x94CEa98D746696AfBd32b1771dA007896948CD5B/sources/StarMeta.sol
|
Get the sub-address identification base the main address./
|
function getSubstarBase(address star) public view returns(address){
return _star_substar_base[star];
}
| 4,055,783
|
./partial_match/42/0xe74EFb19BBC46DbE28b7BaB1F14af6eB7158B4BE/sources/L1_Bridge.sol
|
Refunds the committees stake from a bonded withdrawal and counts that withdrawal against its TransferRoot. _transferHash The Transfer's unique identifier _rootHash The merkle root of the TransferRoot _proof The Merkle proof that proves the Transfer's inclusion in the TransferRoot/
|
function settleBondedWithdrawal(
bytes32 _transferHash,
bytes32 _rootHash,
bytes32[] memory _proof
)
public
{
require(_proof.verify(_rootHash, _transferHash), "L2_BRG: Invalid transfer proof");
uint256 amount = _bondedWithdrawalAmounts[_transferHash];
_addToAmountWithdrawn(_rootHash, amount);
_bondedWithdrawalAmounts[_rootHash] = 0;
_addCredit(amount);
}
| 3,427,443
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { UintUtils } from '../../../utils/UintUtils.sol';
import { ERC721BaseInternal, ERC721BaseStorage } from '../base/ERC721Base.sol';
import { ERC721MetadataStorage } from './ERC721MetadataStorage.sol';
import { ERC721MetadataInternal } from './ERC721MetadataInternal.sol';
import { IERC721Metadata } from './IERC721Metadata.sol';
/**
* @title ERC721 metadata extensions
*/
abstract contract ERC721Metadata is IERC721Metadata, ERC721MetadataInternal {
using ERC721BaseStorage for ERC721BaseStorage.Layout;
using UintUtils for uint256;
/**
* @notice inheritdoc IERC721Metadata
*/
function name() public view virtual returns (string memory) {
return ERC721MetadataStorage.layout().name;
}
/**
* @notice inheritdoc IERC721Metadata
*/
function symbol() public view virtual returns (string memory) {
return ERC721MetadataStorage.layout().symbol;
}
/**
* @notice inheritdoc IERC721Metadata
*/
function tokenURI(uint256 tokenId)
public
view
virtual
returns (string memory)
{
require(
ERC721BaseStorage.layout().exists(tokenId),
'ERC721Metadata: URI query for nonexistent token'
);
ERC721MetadataStorage.Layout storage l = ERC721MetadataStorage.layout();
string memory tokenIdURI = l.tokenURIs[tokenId];
string memory baseURI = l.baseURI;
if (bytes(baseURI).length == 0) {
return tokenIdURI;
} else if (bytes(tokenIdURI).length > 0) {
return string(abi.encodePacked(baseURI, tokenIdURI));
} else {
return string(abi.encodePacked(baseURI, tokenId.toString()));
}
}
/**
* @inheritdoc ERC721MetadataInternal
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
}
}
|
inheritdoc IERC721Metadata/
|
function name() public view virtual returns (string memory) {
return ERC721MetadataStorage.layout().name;
}
| 2,510,976
|
./partial_match/3/0xF8d32C3e53F7DA6e7CB82323f2cAB2159776b832/sources/Airnode.sol
|
Called by the requester to make a short request. A short request refers to a template, which the provider will use to get both requester-agnostic and requester-specific parameters Use this if gas efficiency is critical templateId Template ID from TemplateStore parameters Dynamic request parameters (i.e., parameters that are determined at runtime, unlike the static parameters stored in the template) return requestId Request ID
|
function makeShortRequest(
bytes32 templateId,
bytes calldata parameters
)
external
override
returns (bytes32 requestId)
{
Template storage template = templates[templateId];
require(
requesterIndexToClientAddressToEndorsementStatus[template.requesterIndex][msg.sender],
"Client not endorsed by requester"
);
requestId = keccak256(abi.encode(
noRequests,
templateId,
parameters
));
requestIdToFulfillmentParameters[requestId] = keccak256(abi.encodePacked(
template.providerId,
template.designatedWallet,
template.fulfillAddress,
template.fulfillFunctionId
));
emit ClientShortRequestCreated(
templates[templateId].providerId,
requestId,
noRequests,
msg.sender,
templateId,
parameters
);
noRequests++;
}
| 5,281,171
|
./full_match/97/0x5290FF14b12B3b569502D26BE762bA21E42E4435/sources/contracts/ZamzamDAO.sol
|
Update a Zamzam project Update the goal amount of a Zamzam project, only a Zamzam admin can update a Zamzam project _projectId The project ID of the project to be updated _unpublished The new goalAmount of the project return Returns the projectId of the created project/
|
function updateProjectUnpublished(uint256 _projectId, bool _unpublished)
external
onlyRole(DEFAULT_ADMIN_ROLE)
returns (uint256)
{
Project storage _project = projects[_projectId];
require(_projectId < projectIds.current(), "ZamzamDAO: Invalid projectId");
_project.unpublished = _unpublished;
emit ProjectUpdated(_projectId, _project.goalAmount, _unpublished);
return _projectId;
}
| 3,265,177
|
// SPDX-License-Identifier: GPL-3.0-or-later
// Sources flattened with hardhat v2.6.1 https://hardhat.org
// File @openzeppelin/contracts/token/ERC20/IERC20.sol@v4.5.0
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` 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,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/utils/Address.sol@v4.5.0
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
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
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 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");
(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");
(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");
(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");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal 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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol@v4.5.0
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
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");
}
}
}
// File @openzeppelin/contracts/utils/structs/EnumerableSet.sol@v4.5.0
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// File interfaces/IGasBank.sol
pragma solidity 0.8.9;
interface IGasBank {
event Deposit(address indexed account, uint256 value);
event Withdraw(address indexed account, address indexed receiver, uint256 value);
function depositFor(address account) external payable;
function withdrawUnused(address account) external;
function withdrawFrom(address account, uint256 amount) external;
function withdrawFrom(
address account,
address payable to,
uint256 amount
) external;
function balanceOf(address account) external view returns (uint256);
}
// File interfaces/IVaultReserve.sol
pragma solidity 0.8.9;
interface IVaultReserve {
event Deposit(address indexed vault, address indexed token, uint256 amount);
event Withdraw(address indexed vault, address indexed token, uint256 amount);
event VaultListed(address indexed vault);
function deposit(address token, uint256 amount) external payable returns (bool);
function withdraw(address token, uint256 amount) external returns (bool);
function getBalance(address vault, address token) external view returns (uint256);
function canWithdraw(address vault) external view returns (bool);
}
// File interfaces/oracles/IOracleProvider.sol
pragma solidity 0.8.9;
interface IOracleProvider {
/// @notice Quotes the USD price of `baseAsset`
/// @param baseAsset the asset of which the price is to be quoted
/// @return the USD price of the asset
function getPriceUSD(address baseAsset) external view returns (uint256);
/// @notice Quotes the ETH price of `baseAsset`
/// @param baseAsset the asset of which the price is to be quoted
/// @return the ETH price of the asset
function getPriceETH(address baseAsset) external view returns (uint256);
}
// File interfaces/IPreparable.sol
pragma solidity 0.8.9;
interface IPreparable {
event ConfigPreparedAddress(bytes32 indexed key, address value, uint256 delay);
event ConfigPreparedNumber(bytes32 indexed key, uint256 value, uint256 delay);
event ConfigUpdatedAddress(bytes32 indexed key, address oldValue, address newValue);
event ConfigUpdatedNumber(bytes32 indexed key, uint256 oldValue, uint256 newValue);
event ConfigReset(bytes32 indexed key);
}
// File interfaces/IStrategy.sol
pragma solidity 0.8.9;
interface IStrategy {
function name() external view returns (string memory);
function deposit() external payable returns (bool);
function balance() external view returns (uint256);
function withdraw(uint256 amount) external returns (bool);
function withdrawAll() external returns (uint256);
function harvestable() external view returns (uint256);
function harvest() external returns (uint256);
function strategist() external view returns (address);
function shutdown() external returns (bool);
function hasPendingFunds() external view returns (bool);
}
// File interfaces/IVault.sol
pragma solidity 0.8.9;
/**
* @title Interface for a Vault
*/
interface IVault is IPreparable {
event StrategyActivated(address indexed strategy);
event StrategyDeactivated(address indexed strategy);
/**
* @dev 'netProfit' is the profit after all fees have been deducted
*/
event Harvest(uint256 indexed netProfit, uint256 indexed loss);
function initialize(
address _pool,
uint256 _debtLimit,
uint256 _targetAllocation,
uint256 _bound
) external;
function withdrawFromStrategyWaitingForRemoval(address strategy) external returns (uint256);
function deposit() external payable;
function withdraw(uint256 amount) external returns (bool);
function initializeStrategy(address strategy_) external returns (bool);
function withdrawAll() external;
function withdrawFromReserve(uint256 amount) external;
function getStrategy() external view returns (IStrategy);
function getStrategiesWaitingForRemoval() external view returns (address[] memory);
function getAllocatedToStrategyWaitingForRemoval(address strategy)
external
view
returns (uint256);
function getTotalUnderlying() external view returns (uint256);
function getUnderlying() external view returns (address);
}
// File interfaces/pool/ILiquidityPool.sol
pragma solidity 0.8.9;
interface ILiquidityPool is IPreparable {
event Deposit(address indexed minter, uint256 depositAmount, uint256 mintedLpTokens);
event DepositFor(
address indexed minter,
address indexed mintee,
uint256 depositAmount,
uint256 mintedLpTokens
);
event Redeem(address indexed redeemer, uint256 redeemAmount, uint256 redeemTokens);
event LpTokenSet(address indexed lpToken);
event StakerVaultSet(address indexed stakerVault);
function redeem(uint256 redeemTokens) external returns (uint256);
function redeem(uint256 redeemTokens, uint256 minRedeemAmount) external returns (uint256);
function calcRedeem(address account, uint256 underlyingAmount) external returns (uint256);
function deposit(uint256 mintAmount) external payable returns (uint256);
function deposit(uint256 mintAmount, uint256 minTokenAmount) external payable returns (uint256);
function depositAndStake(uint256 depositAmount, uint256 minTokenAmount)
external
payable
returns (uint256);
function depositFor(address account, uint256 depositAmount) external payable returns (uint256);
function depositFor(
address account,
uint256 depositAmount,
uint256 minTokenAmount
) external payable returns (uint256);
function unstakeAndRedeem(uint256 redeemLpTokens, uint256 minRedeemAmount)
external
returns (uint256);
function handleLpTokenTransfer(
address from,
address to,
uint256 amount
) external;
function executeNewVault() external returns (address);
function executeNewMaxWithdrawalFee() external returns (uint256);
function executeNewRequiredReserves() external returns (uint256);
function executeNewReserveDeviation() external returns (uint256);
function setLpToken(address _lpToken) external returns (bool);
function setStaker() external returns (bool);
function isCapped() external returns (bool);
function uncap() external returns (bool);
function updateDepositCap(uint256 _depositCap) external returns (bool);
function getUnderlying() external view returns (address);
function getLpToken() external view returns (address);
function getWithdrawalFee(address account, uint256 amount) external view returns (uint256);
function getVault() external view returns (IVault);
function exchangeRate() external view returns (uint256);
}
// File libraries/AddressProviderMeta.sol
pragma solidity 0.8.9;
library AddressProviderMeta {
struct Meta {
bool freezable;
bool frozen;
}
function fromUInt(uint256 value) internal pure returns (Meta memory) {
Meta memory meta;
meta.freezable = (value & 1) == 1;
meta.frozen = ((value >> 1) & 1) == 1;
return meta;
}
function toUInt(Meta memory meta) internal pure returns (uint256) {
uint256 value;
value |= meta.freezable ? 1 : 0;
value |= meta.frozen ? 1 << 1 : 0;
return value;
}
}
// File interfaces/IAddressProvider.sol
pragma solidity 0.8.9;
// solhint-disable ordering
interface IAddressProvider is IPreparable {
event KnownAddressKeyAdded(bytes32 indexed key);
event StakerVaultListed(address indexed stakerVault);
event StakerVaultDelisted(address indexed stakerVault);
event ActionListed(address indexed action);
event PoolListed(address indexed pool);
event PoolDelisted(address indexed pool);
event VaultUpdated(address indexed previousVault, address indexed newVault);
/** Key functions */
function getKnownAddressKeys() external view returns (bytes32[] memory);
function freezeAddress(bytes32 key) external;
/** Pool functions */
function allPools() external view returns (address[] memory);
function addPool(address pool) external;
function poolsCount() external view returns (uint256);
function getPoolAtIndex(uint256 index) external view returns (address);
function isPool(address pool) external view returns (bool);
function removePool(address pool) external returns (bool);
function getPoolForToken(address token) external view returns (ILiquidityPool);
function safeGetPoolForToken(address token) external view returns (address);
/** Vault functions */
function updateVault(address previousVault, address newVault) external;
function allVaults() external view returns (address[] memory);
function vaultsCount() external view returns (uint256);
function getVaultAtIndex(uint256 index) external view returns (address);
function isVault(address vault) external view returns (bool);
/** Action functions */
function allActions() external view returns (address[] memory);
function addAction(address action) external returns (bool);
function isAction(address action) external view returns (bool);
/** Address functions */
function initializeAddress(
bytes32 key,
address initialAddress,
bool frezable
) external;
function initializeAndFreezeAddress(bytes32 key, address initialAddress) external;
function getAddress(bytes32 key) external view returns (address);
function getAddress(bytes32 key, bool checkExists) external view returns (address);
function getAddressMeta(bytes32 key) external view returns (AddressProviderMeta.Meta memory);
function prepareAddress(bytes32 key, address newAddress) external returns (bool);
function executeAddress(bytes32 key) external returns (address);
function resetAddress(bytes32 key) external returns (bool);
/** Staker vault functions */
function allStakerVaults() external view returns (address[] memory);
function tryGetStakerVault(address token) external view returns (bool, address);
function getStakerVault(address token) external view returns (address);
function addStakerVault(address stakerVault) external returns (bool);
function isStakerVault(address stakerVault, address token) external view returns (bool);
function isStakerVaultRegistered(address stakerVault) external view returns (bool);
function isWhiteListedFeeHandler(address feeHandler) external view returns (bool);
}
// File interfaces/IRoleManager.sol
pragma solidity 0.8.9;
interface IRoleManager {
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function hasRole(bytes32 role, address account) external view returns (bool);
function hasAnyRole(bytes32[] memory roles, address account) external view returns (bool);
function hasAnyRole(
bytes32 role1,
bytes32 role2,
address account
) external view returns (bool);
function hasAnyRole(
bytes32 role1,
bytes32 role2,
bytes32 role3,
address account
) external view returns (bool);
function getRoleMemberCount(bytes32 role) external view returns (uint256);
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
}
// File interfaces/tokenomics/IBkdToken.sol
pragma solidity 0.8.9;
interface IBkdToken is IERC20 {
function mint(address account, uint256 amount) external;
}
// File interfaces/tokenomics/IInflationManager.sol
pragma solidity 0.8.9;
interface IInflationManager {
event KeeperGaugeListed(address indexed pool, address indexed keeperGauge);
event AmmGaugeListed(address indexed token, address indexed ammGauge);
event KeeperGaugeDelisted(address indexed pool, address indexed keeperGauge);
event AmmGaugeDelisted(address indexed token, address indexed ammGauge);
/** Pool functions */
function setKeeperGauge(address pool, address _keeperGauge) external returns (bool);
function setAmmGauge(address token, address _ammGauge) external returns (bool);
function getAllAmmGauges() external view returns (address[] memory);
function getLpRateForStakerVault(address stakerVault) external view returns (uint256);
function getKeeperRateForPool(address pool) external view returns (uint256);
function getAmmRateForToken(address token) external view returns (uint256);
function getKeeperWeightForPool(address pool) external view returns (uint256);
function getAmmWeightForToken(address pool) external view returns (uint256);
function getLpPoolWeight(address pool) external view returns (uint256);
function getKeeperGaugeForPool(address pool) external view returns (address);
function getAmmGaugeForToken(address token) external view returns (address);
function isInflationWeightManager(address account) external view returns (bool);
function removeStakerVaultFromInflation(address stakerVault, address lpToken) external;
function addGaugeForVault(address lpToken) external returns (bool);
function whitelistGauge(address gauge) external;
function checkpointAllGauges() external returns (bool);
function mintRewards(address beneficiary, uint256 amount) external;
function addStrategyToDepositStakerVault(address depositStakerVault, address strategyPool)
external
returns (bool);
/** Weight setter functions **/
function prepareLpPoolWeight(address lpToken, uint256 newPoolWeight) external returns (bool);
function prepareAmmTokenWeight(address token, uint256 newTokenWeight) external returns (bool);
function prepareKeeperPoolWeight(address pool, uint256 newPoolWeight) external returns (bool);
function executeLpPoolWeight(address lpToken) external returns (uint256);
function executeAmmTokenWeight(address token) external returns (uint256);
function executeKeeperPoolWeight(address pool) external returns (uint256);
function batchPrepareLpPoolWeights(address[] calldata lpTokens, uint256[] calldata weights)
external
returns (bool);
function batchPrepareAmmTokenWeights(address[] calldata tokens, uint256[] calldata weights)
external
returns (bool);
function batchPrepareKeeperPoolWeights(address[] calldata pools, uint256[] calldata weights)
external
returns (bool);
function batchExecuteLpPoolWeights(address[] calldata lpTokens) external returns (bool);
function batchExecuteAmmTokenWeights(address[] calldata tokens) external returns (bool);
function batchExecuteKeeperPoolWeights(address[] calldata pools) external returns (bool);
}
// File interfaces/IController.sol
pragma solidity 0.8.9;
// solhint-disable ordering
interface IController is IPreparable {
function addressProvider() external view returns (IAddressProvider);
function inflationManager() external view returns (IInflationManager);
function addStakerVault(address stakerVault) external returns (bool);
function removePool(address pool) external returns (bool);
/** Keeper functions */
function prepareKeeperRequiredStakedBKD(uint256 amount) external;
function executeKeeperRequiredStakedBKD() external;
function getKeeperRequiredStakedBKD() external view returns (uint256);
function canKeeperExecuteAction(address keeper) external view returns (bool);
/** Miscellaneous functions */
function getTotalEthRequiredForGas(address payer) external view returns (uint256);
}
// File libraries/AddressProviderKeys.sol
pragma solidity 0.8.9;
library AddressProviderKeys {
bytes32 internal constant _TREASURY_KEY = "treasury";
bytes32 internal constant _GAS_BANK_KEY = "gasBank";
bytes32 internal constant _VAULT_RESERVE_KEY = "vaultReserve";
bytes32 internal constant _SWAPPER_REGISTRY_KEY = "swapperRegistry";
bytes32 internal constant _ORACLE_PROVIDER_KEY = "oracleProvider";
bytes32 internal constant _POOL_FACTORY_KEY = "poolFactory";
bytes32 internal constant _CONTROLLER_KEY = "controller";
bytes32 internal constant _BKD_LOCKER_KEY = "bkdLocker";
bytes32 internal constant _ROLE_MANAGER_KEY = "roleManager";
}
// File libraries/AddressProviderHelpers.sol
pragma solidity 0.8.9;
library AddressProviderHelpers {
/**
* @return The address of the treasury.
*/
function getTreasury(IAddressProvider provider) internal view returns (address) {
return provider.getAddress(AddressProviderKeys._TREASURY_KEY);
}
/**
* @return The gas bank.
*/
function getGasBank(IAddressProvider provider) internal view returns (IGasBank) {
return IGasBank(provider.getAddress(AddressProviderKeys._GAS_BANK_KEY));
}
/**
* @return The address of the vault reserve.
*/
function getVaultReserve(IAddressProvider provider) internal view returns (IVaultReserve) {
return IVaultReserve(provider.getAddress(AddressProviderKeys._VAULT_RESERVE_KEY));
}
/**
* @return The address of the swapperRegistry.
*/
function getSwapperRegistry(IAddressProvider provider) internal view returns (address) {
return provider.getAddress(AddressProviderKeys._SWAPPER_REGISTRY_KEY);
}
/**
* @return The oracleProvider.
*/
function getOracleProvider(IAddressProvider provider) internal view returns (IOracleProvider) {
return IOracleProvider(provider.getAddress(AddressProviderKeys._ORACLE_PROVIDER_KEY));
}
/**
* @return the address of the BKD locker
*/
function getBKDLocker(IAddressProvider provider) internal view returns (address) {
return provider.getAddress(AddressProviderKeys._BKD_LOCKER_KEY);
}
/**
* @return the address of the BKD locker
*/
function getRoleManager(IAddressProvider provider) internal view returns (IRoleManager) {
return IRoleManager(provider.getAddress(AddressProviderKeys._ROLE_MANAGER_KEY));
}
/**
* @return the controller
*/
function getController(IAddressProvider provider) internal view returns (IController) {
return IController(provider.getAddress(AddressProviderKeys._CONTROLLER_KEY));
}
}
// File libraries/ScaledMath.sol
pragma solidity 0.8.9;
/*
* @dev To use functions of this contract, at least one of the numbers must
* be scaled to `DECIMAL_SCALE`. The result will scaled to `DECIMAL_SCALE`
* if both numbers are scaled to `DECIMAL_SCALE`, otherwise to the scale
* of the number not scaled by `DECIMAL_SCALE`
*/
library ScaledMath {
// solhint-disable-next-line private-vars-leading-underscore
uint256 internal constant DECIMAL_SCALE = 1e18;
// solhint-disable-next-line private-vars-leading-underscore
uint256 internal constant ONE = 1e18;
/**
* @notice Performs a multiplication between two scaled numbers
*/
function scaledMul(uint256 a, uint256 b) internal pure returns (uint256) {
return (a * b) / DECIMAL_SCALE;
}
/**
* @notice Performs a division between two scaled numbers
*/
function scaledDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return (a * DECIMAL_SCALE) / b;
}
/**
* @notice Performs a division between two numbers, rounding up the result
*/
function scaledDivRoundUp(uint256 a, uint256 b) internal pure returns (uint256) {
return (a * DECIMAL_SCALE + b - 1) / b;
}
/**
* @notice Performs a division between two numbers, ignoring any scaling and rounding up the result
*/
function divRoundUp(uint256 a, uint256 b) internal pure returns (uint256) {
return (a + b - 1) / b;
}
}
// File contracts/utils/CvxMintAmount.sol
pragma solidity 0.8.9;
abstract contract CvxMintAmount {
uint256 private constant _CLIFF_SIZE = 100000 * 1e18; //new cliff every 100,000 tokens
uint256 private constant _CLIFF_COUNT = 1000; // 1,000 cliffs
uint256 private constant _MAX_SUPPLY = 100000000 * 1e18; //100 mil max supply
IERC20 private constant _CVX_TOKEN =
IERC20(address(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B)); // CVX Token
function getCvxMintAmount(uint256 crvEarned) public view returns (uint256) {
//first get total supply
uint256 cvxTotalSupply = _CVX_TOKEN.totalSupply();
//get current cliff
uint256 currentCliff = cvxTotalSupply / _CLIFF_SIZE;
//if current cliff is under the max
if (currentCliff >= _CLIFF_COUNT) return 0;
//get remaining cliffs
uint256 remaining = _CLIFF_COUNT - currentCliff;
//multiply ratio of remaining cliffs to total cliffs against amount CRV received
uint256 cvxEarned = (crvEarned * remaining) / _CLIFF_COUNT;
//double check we have not gone over the max supply
uint256 amountTillMax = _MAX_SUPPLY - cvxTotalSupply;
if (cvxEarned > amountTillMax) cvxEarned = amountTillMax;
return cvxEarned;
}
}
// File libraries/Errors.sol
pragma solidity 0.8.9;
// solhint-disable private-vars-leading-underscore
library Error {
string internal constant ADDRESS_WHITELISTED = "address already whitelisted";
string internal constant ADMIN_ALREADY_SET = "admin has already been set once";
string internal constant ADDRESS_NOT_WHITELISTED = "address not whitelisted";
string internal constant ADDRESS_NOT_FOUND = "address not found";
string internal constant CONTRACT_INITIALIZED = "contract can only be initialized once";
string internal constant CONTRACT_PAUSED = "contract is paused";
string internal constant INVALID_AMOUNT = "invalid amount";
string internal constant INVALID_INDEX = "invalid index";
string internal constant INVALID_VALUE = "invalid msg.value";
string internal constant INVALID_SENDER = "invalid msg.sender";
string internal constant INVALID_TOKEN = "token address does not match pool's LP token address";
string internal constant INVALID_DECIMALS = "incorrect number of decimals";
string internal constant INVALID_ARGUMENT = "invalid argument";
string internal constant INVALID_PARAMETER_VALUE = "invalid parameter value attempted";
string internal constant INVALID_IMPLEMENTATION = "invalid pool implementation for given coin";
string internal constant INVALID_POOL_IMPLEMENTATION =
"invalid pool implementation for given coin";
string internal constant INVALID_LP_TOKEN_IMPLEMENTATION =
"invalid LP Token implementation for given coin";
string internal constant INVALID_VAULT_IMPLEMENTATION =
"invalid vault implementation for given coin";
string internal constant INVALID_STAKER_VAULT_IMPLEMENTATION =
"invalid stakerVault implementation for given coin";
string internal constant INSUFFICIENT_BALANCE = "insufficient balance";
string internal constant ADDRESS_ALREADY_SET = "Address is already set";
string internal constant INSUFFICIENT_STRATEGY_BALANCE = "insufficient strategy balance";
string internal constant INSUFFICIENT_FUNDS_RECEIVED = "insufficient funds received";
string internal constant ADDRESS_DOES_NOT_EXIST = "address does not exist";
string internal constant ADDRESS_FROZEN = "address is frozen";
string internal constant ROLE_EXISTS = "role already exists";
string internal constant CANNOT_REVOKE_ROLE = "cannot revoke role";
string internal constant UNAUTHORIZED_ACCESS = "unauthorized access";
string internal constant SAME_ADDRESS_NOT_ALLOWED = "same address not allowed";
string internal constant SELF_TRANSFER_NOT_ALLOWED = "self-transfer not allowed";
string internal constant ZERO_ADDRESS_NOT_ALLOWED = "zero address not allowed";
string internal constant ZERO_TRANSFER_NOT_ALLOWED = "zero transfer not allowed";
string internal constant THRESHOLD_TOO_HIGH = "threshold is too high, must be under 10";
string internal constant INSUFFICIENT_THRESHOLD = "insufficient threshold";
string internal constant NO_POSITION_EXISTS = "no position exists";
string internal constant POSITION_ALREADY_EXISTS = "position already exists";
string internal constant PROTOCOL_NOT_FOUND = "protocol not found";
string internal constant TOP_UP_FAILED = "top up failed";
string internal constant SWAP_PATH_NOT_FOUND = "swap path not found";
string internal constant UNDERLYING_NOT_SUPPORTED = "underlying token not supported";
string internal constant NOT_ENOUGH_FUNDS_WITHDRAWN =
"not enough funds were withdrawn from the pool";
string internal constant FAILED_TRANSFER = "transfer failed";
string internal constant FAILED_MINT = "mint failed";
string internal constant FAILED_REPAY_BORROW = "repay borrow failed";
string internal constant FAILED_METHOD_CALL = "method call failed";
string internal constant NOTHING_TO_CLAIM = "there is no claimable balance";
string internal constant ERC20_BALANCE_EXCEEDED = "ERC20: transfer amount exceeds balance";
string internal constant INVALID_MINTER =
"the minter address of the LP token and the pool address do not match";
string internal constant STAKER_VAULT_EXISTS = "a staker vault already exists for the token";
string internal constant DEADLINE_NOT_ZERO = "deadline must be 0";
string internal constant DEADLINE_NOT_SET = "deadline is 0";
string internal constant DEADLINE_NOT_REACHED = "deadline has not been reached yet";
string internal constant DELAY_TOO_SHORT = "delay be at least 3 days";
string internal constant INSUFFICIENT_UPDATE_BALANCE =
"insufficient funds for updating the position";
string internal constant SAME_AS_CURRENT = "value must be different to existing value";
string internal constant NOT_CAPPED = "the pool is not currently capped";
string internal constant ALREADY_CAPPED = "the pool is already capped";
string internal constant EXCEEDS_DEPOSIT_CAP = "deposit exceeds deposit cap";
string internal constant VALUE_TOO_LOW_FOR_GAS = "value too low to cover gas";
string internal constant NOT_ENOUGH_FUNDS = "not enough funds to withdraw";
string internal constant ESTIMATED_GAS_TOO_HIGH = "too much ETH will be used for gas";
string internal constant DEPOSIT_FAILED = "deposit failed";
string internal constant GAS_TOO_HIGH = "too much ETH used for gas";
string internal constant GAS_BANK_BALANCE_TOO_LOW = "not enough ETH in gas bank to cover gas";
string internal constant INVALID_TOKEN_TO_ADD = "Invalid token to add";
string internal constant INVALID_TOKEN_TO_REMOVE = "token can not be removed";
string internal constant TIME_DELAY_NOT_EXPIRED = "time delay not expired yet";
string internal constant UNDERLYING_NOT_WITHDRAWABLE =
"pool does not support additional underlying coins to be withdrawn";
string internal constant STRATEGY_SHUT_DOWN = "Strategy is shut down";
string internal constant STRATEGY_DOES_NOT_EXIST = "Strategy does not exist";
string internal constant UNSUPPORTED_UNDERLYING = "Underlying not supported";
string internal constant NO_DEX_SET = "no dex has been set for token";
string internal constant INVALID_TOKEN_PAIR = "invalid token pair";
string internal constant TOKEN_NOT_USABLE = "token not usable for the specific action";
string internal constant ADDRESS_NOT_ACTION = "address is not registered action";
string internal constant INVALID_SLIPPAGE_TOLERANCE = "Invalid slippage tolerance";
string internal constant POOL_NOT_PAUSED = "Pool must be paused to withdraw from reserve";
string internal constant INTERACTION_LIMIT = "Max of one deposit and withdraw per block";
string internal constant GAUGE_EXISTS = "Gauge already exists";
string internal constant GAUGE_DOES_NOT_EXIST = "Gauge does not exist";
string internal constant EXCEEDS_MAX_BOOST = "Not allowed to exceed maximum boost on Convex";
string internal constant PREPARED_WITHDRAWAL =
"Cannot relock funds when withdrawal is being prepared";
string internal constant ASSET_NOT_SUPPORTED = "Asset not supported";
string internal constant STALE_PRICE = "Price is stale";
string internal constant NEGATIVE_PRICE = "Price is negative";
string internal constant NOT_ENOUGH_BKD_STAKED = "Not enough BKD tokens staked";
string internal constant RESERVE_ACCESS_EXCEEDED = "Reserve access exceeded";
}
// File libraries/Roles.sol
pragma solidity 0.8.9;
// solhint-disable private-vars-leading-underscore
library Roles {
bytes32 internal constant GOVERNANCE = "governance";
bytes32 internal constant ADDRESS_PROVIDER = "address_provider";
bytes32 internal constant POOL_FACTORY = "pool_factory";
bytes32 internal constant CONTROLLER = "controller";
bytes32 internal constant GAUGE_ZAP = "gauge_zap";
bytes32 internal constant MAINTENANCE = "maintenance";
bytes32 internal constant INFLATION_MANAGER = "inflation_manager";
bytes32 internal constant POOL = "pool";
bytes32 internal constant VAULT = "vault";
}
// File contracts/access/AuthorizationBase.sol
pragma solidity 0.8.9;
/**
* @notice Provides modifiers for authorization
*/
abstract contract AuthorizationBase {
/**
* @notice Only allows a sender with `role` to perform the given action
*/
modifier onlyRole(bytes32 role) {
require(_roleManager().hasRole(role, msg.sender), Error.UNAUTHORIZED_ACCESS);
_;
}
/**
* @notice Only allows a sender with GOVERNANCE role to perform the given action
*/
modifier onlyGovernance() {
require(_roleManager().hasRole(Roles.GOVERNANCE, msg.sender), Error.UNAUTHORIZED_ACCESS);
_;
}
/**
* @notice Only allows a sender with any of `roles` to perform the given action
*/
modifier onlyRoles2(bytes32 role1, bytes32 role2) {
require(_roleManager().hasAnyRole(role1, role2, msg.sender), Error.UNAUTHORIZED_ACCESS);
_;
}
/**
* @notice Only allows a sender with any of `roles` to perform the given action
*/
modifier onlyRoles3(
bytes32 role1,
bytes32 role2,
bytes32 role3
) {
require(
_roleManager().hasAnyRole(role1, role2, role3, msg.sender),
Error.UNAUTHORIZED_ACCESS
);
_;
}
function roleManager() external view virtual returns (IRoleManager) {
return _roleManager();
}
function _roleManager() internal view virtual returns (IRoleManager);
}
// File contracts/access/Authorization.sol
pragma solidity 0.8.9;
contract Authorization is AuthorizationBase {
IRoleManager internal immutable __roleManager;
constructor(IRoleManager roleManager) {
__roleManager = roleManager;
}
function _roleManager() internal view override returns (IRoleManager) {
return __roleManager;
}
}
// File contracts/utils/SlippageTolerance.sol
pragma solidity 0.8.9;
contract SlippageTolerance is Authorization {
using ScaledMath for uint256;
uint256 public slippageTolerance;
event SetSlippageTolerance(uint256 value); // Emitted after a succuessful setting of slippage tolerance
constructor(IRoleManager roleManager) Authorization(roleManager) {
slippageTolerance = 0.97e18;
}
/**
* @notice Set slippage tolerance for reward token swaps.
* @dev Stored as a multiplier, e.g. 2% would be set as 0.98.
* @param _slippageTolerance New imbalance tolarance out.
* @return True if successfully set.
*/
function setSlippageTolerance(uint256 _slippageTolerance)
external
onlyGovernance
returns (bool)
{
require(_slippageTolerance <= ScaledMath.ONE, Error.INVALID_SLIPPAGE_TOLERANCE);
require(_slippageTolerance > 0.8e18, Error.INVALID_SLIPPAGE_TOLERANCE);
slippageTolerance = _slippageTolerance;
emit SetSlippageTolerance(_slippageTolerance);
return true;
}
}
// File interfaces/vendor/IBooster.sol
pragma solidity 0.8.9;
interface IBooster {
function poolInfo(uint256 pid)
external
returns (
address lpToken,
address token,
address gauge,
address crvRewards,
address stash,
bool shutdown
);
/**
* @dev `_pid` is the ID of the Convex for a specific Curve LP token.
*/
function deposit(
uint256 _pid,
uint256 _amount,
bool _stake
) external returns (bool);
function withdraw(uint256 _pid, uint256 _amount) external returns (bool);
function withdrawAll(uint256 _pid) external returns (bool);
function depositAll(uint256 _pid, bool _stake) external returns (bool);
}
// File interfaces/vendor/ICurveSwapEth.sol
pragma solidity 0.8.9;
interface ICurveSwapEth {
function get_virtual_price() external view returns (uint256);
function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external payable;
function remove_liquidity_imbalance(uint256[3] calldata amounts, uint256 max_burn_amount)
external;
function remove_liquidity_imbalance(uint256[2] calldata amounts, uint256 max_burn_amount)
external;
function remove_liquidity(uint256 _amount, uint256[3] calldata min_amounts) external;
function exchange(
uint256 i,
uint256 j,
uint256 dx,
uint256 min_dy
) external payable;
function coins(uint256 i) external view returns (address);
function get_dy(
uint256 i,
uint256 j,
uint256 dx
) external view returns (uint256);
function calc_token_amount(uint256[3] calldata amounts, bool deposit)
external
view
returns (uint256);
function calc_token_amount(uint256[2] calldata amounts, bool deposit)
external
view
returns (uint256);
function calc_withdraw_one_coin(uint256 _token_amount, int128 i)
external
view
returns (uint256);
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 min_amount
) external;
}
// File interfaces/vendor/IRewardStaking.sol
pragma solidity 0.8.9;
interface IRewardStaking {
function stakeFor(address, uint256) external;
function stake(uint256) external;
function stakeAll() external returns (bool);
function withdraw(uint256 amount, bool claim) external returns (bool);
function withdrawAndUnwrap(uint256 amount, bool claim) external returns (bool);
function earned(address account) external view returns (uint256);
function getReward() external;
function getReward(address _account, bool _claimExtras) external;
function extraRewardsLength() external view returns (uint256);
function extraRewards(uint256 _pid) external view returns (address);
function rewardToken() external view returns (address);
function balanceOf(address account) external view returns (uint256);
}
// File interfaces/vendor/UniswapRouter02.sol
pragma solidity 0.8.9;
interface UniswapRouter02 {
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external returns (uint256 amountIn);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external view returns (uint256 amountOut);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsOut(uint256 amountIn, address[] memory path)
external
view
returns (uint256[] memory amounts);
function getReserves(
address factory,
address tokenA,
address tokenB
) external view returns (uint256 reserveA, uint256 reserveB);
function WETH() external pure returns (address);
}
interface UniswapV2Pair {
function getReserves()
external
view
returns (
uint112 _reserve0,
uint112 _reserve1,
uint32 _blockTimestampLast
);
}
interface UniswapV2Factory {
function getPair(address tokenA, address tokenB) external view returns (address pair);
}
// File interfaces/vendor/IWETH.sol
pragma solidity 0.8.9;
/**
* @notice Interface for WETH9
* @dev https://etherscan.io/address/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2#code
*/
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256 wad) external;
}
// File contracts/strategies/BkdEthCvx.sol
pragma solidity 0.8.9;
/**
* This is the BkdEthCvx strategy, which is designed to be used by a Backd ETH Vault.
* The strategy holds ETH as it's underlying and allocates liquidity to Convex via given Curve Pool with 2 underlying tokens.
* Rewards received on Convex (CVX, CRV), are sold in part for the underlying.
* A share of earned CVX & CRV are retained on behalf of the Backd community to participate in governance.
*/
contract BkdEthCvx is IStrategy, CvxMintAmount, SlippageTolerance {
using ScaledMath for uint256;
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
using AddressProviderHelpers for IAddressProvider;
uint256 private constant _CURVE_CVX_INDEX = 1;
uint256 private constant _CURVE_ETH_INDEX = 0;
IBooster private constant _BOOSTER = IBooster(0xF403C135812408BFbE8713b5A23a04b3D48AAE31); // Convex Booster Contract
IERC20 private constant _CVX = IERC20(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); // CVX
IWETH private constant _WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // WETH
IERC20 private constant _CRV = IERC20(0xD533a949740bb3306d119CC777fa900bA034cd52); // CRV
UniswapRouter02 private constant _SUSHISWAP =
UniswapRouter02(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // Sushiswap Router for swaps
UniswapRouter02 private constant _UNISWAP =
UniswapRouter02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Uniswap Router for swaps
ICurveSwapEth internal constant _CVX_ETH_CURVE_POOL =
ICurveSwapEth(0xB576491F1E6e5E62f1d8F26062Ee822B40B0E0d4); // CVX/ETH Curve Pool
IAddressProvider internal immutable _addressProvider; // Address provider used for getting oracle provider
address payable public immutable vault; // Backd Vault
ICurveSwapEth public immutable curvePool; // Curve Pool
IERC20 public immutable lp; // Curve Pool LP Token
IRewardStaking public immutable rewards; // Rewards Contract for claiming Convex Rewards
uint256 public immutable convexPid; // Index of Convex Pool in Booster Contract
uint256 public immutable curveIndex; // Underlying index in Curve Pool
uint256 public imbalanceToleranceIn; // Maximum allowed slippage from Curve Pool Imbalance for depositing
uint256 public imbalanceToleranceOut; // Maximum allowed slippage from Curve Pool Imbalance for withdrawing
address public communityReserve; // Address for sending CVX & CRV Community Reserve share
uint256 public cvxCommunityReserveShare; // Share of CVX sent to Community Reserve
uint256 public crvCommunityReserveShare; // Share of CRV sent to Community Reserve
address public override strategist; // The strategist for the strategy
bool public isShutdown; // If the strategy is shutdown, stops all deposits
mapping(address => UniswapRouter02) public tokenDex; // Dex to use for swapping for a given token
EnumerableSet.AddressSet private _rewardTokens; // List of additional reward tokens when claiming rewards on Convex
event Deposit(uint256 amount); // Emitted after a successfull deposit
event Withdraw(uint256 amount); // Emitted after a successful withdrawal
event WithdrawAll(uint256 amount); // Emitted after successfully withdrwaing all
event Harvest(uint256 amount); // Emitted after a successful harvest
event Shutdown(); // Emitted after a successful shutdown
event SetCommunityReserve(address reserve); // Emitted after a succuessful setting of reserve
event SetCrvCommunityReserveShare(uint256 value); // Emitted after a succuessful setting of CRV Community Reserve Share
event SetCvxCommunityReserveShare(uint256 value); // Emitted after a succuessful setting of CVX Community Reserve Share
event SetImbalanceToleranceIn(uint256 value); // Emitted after a succuessful setting of imbalance tolerance in
event SetImbalanceToleranceOut(uint256 value); // Emitted after a succuessful setting of imbalance tolerance out
event SetStrategist(address strategist); // Emitted after a succuessful setting of strategist
event AddRewardToken(address token); // Emitted after successfully adding a new reward token
event RemoveRewardToken(address token); // Emitted after successfully removing a reward token
event SwapDex(address token, address newDex); // Emitted after successfully swapping a tokens dex
modifier onlyVault() {
require(msg.sender == vault, Error.UNAUTHORIZED_ACCESS);
_;
}
constructor(
address vault_,
address strategist_,
address curvePool_,
uint256 convexPid_,
uint256 curveIndex_,
IAddressProvider addressProvider_
) SlippageTolerance(addressProvider_.getRoleManager()) {
// Setting inputs
vault = payable(vault_);
strategist = strategist_;
curvePool = ICurveSwapEth(curvePool_);
convexPid = convexPid_;
curveIndex = curveIndex_;
_addressProvider = addressProvider_;
// Setting LP and Rewards contracts
(address lp_, , , address rewards_, , ) = _BOOSTER.poolInfo(convexPid_);
lp = IERC20(lp_);
rewards = IRewardStaking(rewards_);
// Setting default values
imbalanceToleranceIn = 0.0007e18;
imbalanceToleranceOut = 0.0104e18;
// Setting dexes
_setDex(address(_CRV), _SUSHISWAP);
_setDex(address(_CVX), _SUSHISWAP);
// Approvals
IERC20(lp_).safeApprove(address(_BOOSTER), type(uint256).max);
_CVX.safeApprove(address(_CVX_ETH_CURVE_POOL), type(uint256).max);
_CRV.safeApprove(address(_SUSHISWAP), type(uint256).max);
}
receive() external payable {}
/**
* @notice Deposit all available underlying into Convex pool.
* @dev Liquidity is added to Curve Pool then Curve LP tokens are deposited
* into Convex and Convex LP tokens are staked for rewards by default.
* @return True if successful deposit.
*/
function deposit() external payable override onlyVault returns (bool) {
require(!isShutdown, Error.STRATEGY_SHUT_DOWN);
// Depositing into Curve Pool
uint256 underlyingBalance = _underlyingBalance();
if (underlyingBalance == 0) return false;
uint256[2] memory amounts;
amounts[curveIndex] = underlyingBalance;
curvePool.add_liquidity{value: underlyingBalance}(
amounts,
_minLpAccepted(underlyingBalance)
);
// Depositing into Convex and Staking
if (!_BOOSTER.depositAll(convexPid, true)) return false;
emit Deposit(underlyingBalance);
return true;
}
/**
* @notice Withdraw an amount of underlying to the vault.
* @dev This can only be called by the vault.
* If the amount is not available, it will be made liquid.
* @param amount Amount of underlying to withdraw.
* @return True if successful withdrawal.
*/
function withdraw(uint256 amount) external override onlyVault returns (bool) {
if (amount == 0) return false;
uint256 underlyingBalance = _underlyingBalance();
// Transferring from idle balance if enough
if (underlyingBalance >= amount) {
if (!vault.send(amount)) return false;
emit Withdraw(amount);
return true;
}
// Unstaking needed LP Tokens from Convex
uint256 requiredUnderlyingAmount = amount - underlyingBalance;
uint256 maxLpBurned = _maxLpBurned(requiredUnderlyingAmount);
uint256 requiredLpAmount = maxLpBurned - _lpBalance();
if (!rewards.withdrawAndUnwrap(requiredLpAmount, false)) return false;
// Removing needed liquidity from Curve
uint256[2] memory amounts;
// solhint-disable-next-line reentrancy
amounts[curveIndex] = requiredUnderlyingAmount;
curvePool.remove_liquidity_imbalance(amounts, maxLpBurned);
vault.transfer(amount);
emit Withdraw(amount);
return true;
}
/**
* @notice Withdraw all underlying to vault.
* @dev This does not liquidate reward tokens and only considers
* idle underlying, idle lp tokens and staked lp tokens.
* @return Amount of underlying withdrawn
*/
function withdrawAll() external override returns (uint256) {
require(
msg.sender == vault || _roleManager().hasRole(Roles.GOVERNANCE, msg.sender),
Error.UNAUTHORIZED_ACCESS
);
// Unstaking and withdrawing from Convex pool
uint256 stakedBalance = _stakedBalance();
if (stakedBalance > 0) {
if (!rewards.withdrawAndUnwrap(stakedBalance, false)) return 0;
}
// Removing liquidity from Curve
uint256 lpBalance = _lpBalance();
if (lpBalance > 0) {
curvePool.remove_liquidity_one_coin(
lpBalance,
int128(uint128(curveIndex)),
_minUnderlyingAccepted(lpBalance)
);
}
// Transferring underlying to vault
uint256 underlyingBalance = _underlyingBalance();
if (underlyingBalance == 0) return 0;
vault.transfer(underlyingBalance);
emit WithdrawAll(underlyingBalance);
return underlyingBalance;
}
/**
* @notice Harvests reward tokens and sells these for the underlying.
* @dev Any underlying harvested is not redeposited by this method.
* @return Amount of underlying harvested.
*/
function harvest() external override onlyVault returns (uint256) {
uint256 underlyingBalance = _underlyingBalance();
// Claim Convex rewards
rewards.getReward(address(this), false);
// Sending share to Community Reserve
_sendCommunityReserveShare();
// Swap CVX for WETH
_swapAllForWeth(_CVX);
// Swap CRV for WETH
_swapAllForWeth(_CRV);
// Swap Extra Rewards for WETH
for (uint256 i = 0; i < _rewardTokens.length(); i++) {
_swapAllForWeth(IERC20(_rewardTokens.at(i)));
}
// Swap WETH for underlying
_swapWethForUnderlying();
uint256 harvested = _underlyingBalance() - underlyingBalance;
emit Harvest(harvested);
return harvested;
}
/**
* @notice Shuts down the strategy, disabling deposits.
* @return True if the strategy was succesfully shutdown
*/
function shutdown() external override onlyVault returns (bool) {
if (isShutdown) return false;
isShutdown = true;
emit Shutdown();
return true;
}
/**
* @notice Set the address of the communit reserve.
* @dev CRV & CVX will be taxed and allocated to the reserve,
* such that Backd can participate in governance.
* @param _communityReserve Address of the community reserve.
* @return True if successfully set.
*/
function setCommunityReserve(address _communityReserve) external onlyGovernance returns (bool) {
communityReserve = _communityReserve;
emit SetCommunityReserve(_communityReserve);
return true;
}
/**
* @notice Set the share of CRV to send to the Community Reserve.
* @param crvCommunityReserveShare_ New fee charged on CRV rewards for governance.
* @return True if successfully set.
*/
function setCrvCommunityReserveShare(uint256 crvCommunityReserveShare_)
external
onlyGovernance
returns (bool)
{
require(crvCommunityReserveShare_ <= ScaledMath.ONE, Error.INVALID_AMOUNT);
require(communityReserve != address(0), "Community reserve must be set");
crvCommunityReserveShare = crvCommunityReserveShare_;
emit SetCrvCommunityReserveShare(crvCommunityReserveShare_);
return true;
}
/**
* @notice Set the share of CVX to send to the Community Reserve.
* @param cvxCommunityReserveShare_ New fee charged on CVX rewards for governance.
* @return True if successfully set.
*/
function setCvxCommunityReserveShare(uint256 cvxCommunityReserveShare_)
external
onlyGovernance
returns (bool)
{
require(cvxCommunityReserveShare_ <= ScaledMath.ONE, Error.INVALID_AMOUNT);
require(communityReserve != address(0), "Community reserve must be set");
cvxCommunityReserveShare = cvxCommunityReserveShare_;
emit SetCvxCommunityReserveShare(cvxCommunityReserveShare_);
return true;
}
/**
* @notice Set imbalance tolerance for Curve Pool deposits.
* @dev Stored as a percent, e.g. 1% would be set as 0.01
* @param _imbalanceToleranceIn New imbalance tolarance in.
* @return True if successfully set.
*/
function setImbalanceToleranceIn(uint256 _imbalanceToleranceIn)
external
onlyGovernance
returns (bool)
{
imbalanceToleranceIn = _imbalanceToleranceIn;
emit SetImbalanceToleranceIn(_imbalanceToleranceIn);
return true;
}
/**
* @notice Set imbalance tolerance for Curve Pool withdrawals.
* @dev Stored as a percent, e.g. 1% would be set as 0.01
* @param _imbalanceToleranceOut New imbalance tolarance out.
* @return True if successfully set.
*/
function setImbalanceToleranceOut(uint256 _imbalanceToleranceOut)
external
onlyGovernance
returns (bool)
{
imbalanceToleranceOut = _imbalanceToleranceOut;
emit SetImbalanceToleranceOut(_imbalanceToleranceOut);
return true;
}
/**
* @notice Set strategist.
* @dev Can only be set by current strategist.
* @param _strategist Address of new strategist.
* @return True if successfully set.
*/
function setStrategist(address _strategist) external returns (bool) {
require(msg.sender == strategist, Error.UNAUTHORIZED_ACCESS);
strategist = _strategist;
emit SetStrategist(_strategist);
return true;
}
/**
* @notice Add a reward token to list of extra reward tokens.
* @dev These are tokens that are not the main assets of the strategy. For instance, temporary incentives.
* @param token Address of token to add to reward token list.
* @return True if successfully added.
*/
function addRewardToken(address token) external onlyGovernance returns (bool) {
require(
token != address(_CVX) && token != address(_CRV) && token != address(_WETH),
Error.INVALID_TOKEN_TO_ADD
);
if (_rewardTokens.contains(token)) return false;
_rewardTokens.add(token);
_setDex(token, _SUSHISWAP);
IERC20(token).safeApprove(address(_SUSHISWAP), 0);
IERC20(token).safeApprove(address(_SUSHISWAP), type(uint256).max);
emit AddRewardToken(token);
return true;
}
/**
* @notice Remove a reward token.
* @param token Address of token to remove from reward token list.
* @return True if successfully removed.
*/
function removeRewardToken(address token) external onlyGovernance returns (bool) {
if (!_rewardTokens.contains(token)) return false;
if (!_rewardTokens.remove(token)) return false;
emit RemoveRewardToken(token);
return true;
}
/**
* @notice Set the DEX that should be used for swapping for a specific coin.
* If Uniswap is active, it will switch to SushiSwap and vice versa.
* @dev Only SushiSwap and Uniswap are supported.
* @param token Address of token for which the DEX should be updated.
*/
function swapDex(address token) external onlyGovernance returns (bool) {
UniswapRouter02 currentDex = tokenDex[token];
require(address(currentDex) != address(0), Error.NO_DEX_SET);
UniswapRouter02 newDex = currentDex == _SUSHISWAP ? _UNISWAP : _SUSHISWAP;
_setDex(token, newDex);
IERC20(token).safeApprove(address(newDex), 0);
IERC20(token).safeApprove(address(newDex), type(uint256).max);
emit SwapDex(token, address(newDex));
return true;
}
/**
* @notice Returns the name of the strategy.
* @return The name of the strategy.
*/
function name() external view override returns (string memory) {
return "BkdEthCvx";
}
/**
* @notice Amount of rewards that can be harvested in the underlying.
* @dev Includes rewards for CRV & CVX.
* @return Estimated amount of underlying available to harvest.
*/
function harvestable() external view override returns (uint256) {
uint256 crvAmount_ = rewards.earned(address(this));
if (crvAmount_ == 0) return 0;
return
_underlyingAmountOut(
_CRV,
crvAmount_.scaledMul(ScaledMath.ONE - crvCommunityReserveShare)
) +
_underlyingAmountOut(
_CVX,
getCvxMintAmount(crvAmount_).scaledMul(ScaledMath.ONE - cvxCommunityReserveShare)
);
}
/**
* @dev Contract does not stash tokens.
*/
function hasPendingFunds() external pure override returns (bool) {
return false;
}
/**
* @notice Get the total underlying balance of the strategy.
* @dev This includes idle underlying, idle LP and LP deposited on Convex.
* @return Underlying balance of strategy.
*/
function balance() public view override returns (uint256) {
return _underlyingBalance() + _lpToUnderlying(_stakedBalance() + _lpBalance());
}
/**
* @dev Set the dex to use for a token.
* @param token Address of token to set the dex for.
* @param dex Dex to use for swaps with that token.
*/
function _setDex(address token, UniswapRouter02 dex) internal {
tokenDex[token] = dex;
}
/**
* @notice Swaps all balance of a token for WETH.
* @param token Address of the token to swap for WETH.
*/
function _swapAllForWeth(IERC20 token) internal {
uint256 amount = token.balanceOf(address(this));
return _swapForWeth(token, amount);
}
/**
* @notice Swaps a token for WETH.
* @param token Address of the token to swap for WETH.
* @param amount Amount of the token to swap for WETH.
*/
function _swapForWeth(IERC20 token, uint256 amount) internal {
if (amount == 0) return;
// Handling CVX Swaps
if (token == _CVX) {
_CVX_ETH_CURVE_POOL.exchange(
_CURVE_CVX_INDEX,
_CURVE_ETH_INDEX,
amount,
amount
.scaledMul(_addressProvider.getOracleProvider().getPriceETH(address(_CVX)))
.scaledMul(slippageTolerance)
);
return;
}
// Handling other swaps
address[] memory path = new address[](2);
path[0] = address(token);
path[1] = address(_WETH);
tokenDex[address(token)].swapExactTokensForTokens(
amount,
amount
.scaledMul(_addressProvider.getOracleProvider().getPriceETH(address(token)))
.scaledMul(slippageTolerance),
path,
address(this),
block.timestamp
);
}
/**
* @notice Swaps all available WETH for underlying.
*/
function _swapWethForUnderlying() internal {
uint256 wethBalance = _WETH.balanceOf(address(this));
if (wethBalance == 0) return;
_WETH.withdraw(wethBalance);
}
/**
* @notice Sends a share of the current balance of CRV and CVX to the Community Reserve.
*/
function _sendCommunityReserveShare() internal {
address communityReserve_ = communityReserve;
if (communityReserve_ == address(0)) return;
uint256 cvxCommunityReserveShare_ = cvxCommunityReserveShare;
if (cvxCommunityReserveShare_ > 0) {
uint256 cvxBalance_ = _CVX.balanceOf(address(this));
if (cvxBalance_ > 0) {
_CVX.safeTransfer(
communityReserve_,
cvxBalance_.scaledMul(cvxCommunityReserveShare_)
);
}
}
uint256 crvCommunityReserveShare_ = crvCommunityReserveShare;
if (crvCommunityReserveShare_ > 0) {
uint256 crvBalance_ = _CRV.balanceOf(address(this));
if (crvBalance_ > 0) {
_CRV.safeTransfer(
communityReserve_,
crvBalance_.scaledMul(crvCommunityReserveShare_)
);
}
}
}
/**
* @dev Get the balance of the underlying.
*/
function _underlyingBalance() internal view returns (uint256) {
return address(this).balance;
}
/**
* @dev Get the balance of the lp.
*/
function _lpBalance() internal view returns (uint256) {
return lp.balanceOf(address(this));
}
/**
* @dev Get the balance of the underlying staked in the Curve pool.
*/
function _stakedBalance() internal view returns (uint256) {
return rewards.balanceOf(address(this));
}
/**
* @notice Gets the amount of underlying that would be received by selling the token.
* @return Underlying amount that would be received.
*/
function _underlyingAmountOut(IERC20 token, uint256 amountIn) internal view returns (uint256) {
if (amountIn == 0) return 0;
if (token == _CVX) {
return _CVX_ETH_CURVE_POOL.get_dy(_CURVE_CVX_INDEX, _CURVE_ETH_INDEX, amountIn);
}
address[] memory path = new address[](2);
path[0] = address(token);
path[1] = address(_WETH);
return tokenDex[address(token)].getAmountsOut(amountIn, path)[1];
}
/**
* @notice Calculates the minimum LP to accept when depositing underlying into Curve Pool.
* @param _underlyingAmount Amount of underlying that is being deposited into Curve Pool.
* @return The minimum LP balance to accept.
*/
function _minLpAccepted(uint256 _underlyingAmount) internal view returns (uint256) {
return _underlyingToLp(_underlyingAmount).scaledMul(ScaledMath.ONE - imbalanceToleranceIn);
}
/**
* @notice Calculates the maximum LP to accept burning when withdrawing amount from Curve Pool.
* @param _underlyingAmount Amount of underlying that is being widthdrawn from Curve Pool.
* @return The maximum LP balance to accept burning.
*/
function _maxLpBurned(uint256 _underlyingAmount) internal view returns (uint256) {
return _underlyingToLp(_underlyingAmount).scaledMul(ScaledMath.ONE + imbalanceToleranceOut);
}
/**
* @notice Calculates the minimum underlying to accept when burning LP tokens to withdraw from Curve Pool.
* @param _lpAmount Amount of LP tokens being burned to withdraw from Curve Pool.
* @return The minimum underlying balance to accept.
*/
function _minUnderlyingAccepted(uint256 _lpAmount) internal view returns (uint256) {
return _lpToUnderlying(_lpAmount).scaledMul(ScaledMath.ONE - imbalanceToleranceOut);
}
/**
* @notice Converts an amount of underlying into their estimated LP value.
* @dev Uses get_virtual_price which is less suceptible to manipulation.
* But is also less accurate to how much could be withdrawn.
* @param _underlyingAmount Amount of underlying to convert.
* @return The estimated value in the LP.
*/
function _underlyingToLp(uint256 _underlyingAmount) internal view returns (uint256) {
return _underlyingAmount.scaledDiv(curvePool.get_virtual_price());
}
/**
* @notice Converts an amount of LP into their estimated underlying value.
* @dev Uses get_virtual_price which is less suceptible to manipulation.
* But is also less accurate to how much could be withdrawn.
* @param _lpAmount Amount of LP to convert.
* @return The estimated value in the underlying.
*/
function _lpToUnderlying(uint256 _lpAmount) internal view returns (uint256) {
return _lpAmount.scaledMul(curvePool.get_virtual_price());
}
}
|
Swaps all available WETH for underlying./
|
function _swapWethForUnderlying() internal {
uint256 wethBalance = _WETH.balanceOf(address(this));
if (wethBalance == 0) return;
_WETH.withdraw(wethBalance);
}
| 14,732,540
|
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Global Enums and Structs
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 rateLimit;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
// Part: ChefLike
interface ChefLike {
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt.
}
struct PoolInfo {
address stakingToken; // Address of staking token contract.
uint256 allocPoint; // How many allocation points assigned to this pool.
uint256 lastRewardBlock; // Last block number that distribution occurs.
uint256 accRewardPerShare; // Accumulated reward tokens per share, times 1e24. See below.
uint16 earlyWithdrawalFeeBP; // Early withdrawal fee in basis points
}
function deposit(uint256 _pid, uint256 _amount) external;
function withdraw(uint256 _pid, uint256 _amount) external;
function emergencyWithdraw(uint256 _pid) external;
function poolInfo(uint256 _pid) external view returns (PoolInfo memory);
function userInfo(uint256 _pid, address user)
external
view
returns (UserInfo memory);
function harvest(uint256 _pid) external;
function pendingReward(uint256 _pid, address _user)
external
view
returns (uint256);
}
// Part: IUniswapV2Router01
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts);
}
// Part: OpenZeppelin/openzeppelin-contracts@3.1.0/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: OpenZeppelin/openzeppelin-contracts@3.1.0/IERC20
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Part: OpenZeppelin/openzeppelin-contracts@3.1.0/Math
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// Part: OpenZeppelin/openzeppelin-contracts@3.1.0/SafeMath
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Part: IUniswapV2Router02
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
// Part: OpenZeppelin/openzeppelin-contracts@3.1.0/SafeERC20
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
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'
// solhint-disable-next-line max-line-length
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).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_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
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Part: VaultAPI
interface VaultAPI is IERC20 {
function name() external view returns (string calldata);
function symbol() external view returns (string calldata);
function decimals() external view returns (uint256);
function apiVersion() external pure returns (string memory);
function permit(
address owner,
address spender,
uint256 amount,
uint256 expiry,
bytes calldata signature
) external returns (bool);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function deposit() external returns (uint256);
function deposit(uint256 amount) external returns (uint256);
function deposit(uint256 amount, address recipient)
external
returns (uint256);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function withdraw() external returns (uint256);
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw(uint256 maxShares, address recipient)
external
returns (uint256);
function token() external view returns (address);
function strategies(address _strategy)
external
view
returns (StrategyParams memory);
function pricePerShare() external view returns (uint256);
function totalAssets() external view returns (uint256);
function depositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
// Part: BaseStrategyLegacy
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategyLegacy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.3.0";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external view virtual returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external view virtual returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(
uint256 profit,
uint256 loss,
uint256 debtPayment,
uint256 debtOutstanding
);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(
msg.sender == strategist || msg.sender == governance(),
"!authorized"
);
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI)
external
onlyAuthorized
{
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public view virtual returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return
vault.strategies(address(this)).debtRatio > 0 ||
estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit - _loss`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded)
internal
virtual
returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCost The keeper's estimated cast cost to call `tend()`.
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCost) public view virtual returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCost The keeper's estimated cast cost to call `harvest()`.
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCost)
public
view
virtual
returns (bool)
{
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay)
return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay)
return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 totalAssets = estimatedTotalAssets();
// NOTE: use the larger of total assets or debt outstanding to book losses properly
(debtPayment, loss) = liquidatePosition(
totalAssets > debtOutstanding ? totalAssets : debtOutstanding
);
// NOTE: take up any remainder here as profit
if (debtPayment > debtOutstanding) {
profit = debtPayment.sub(debtOutstanding);
debtPayment = debtOutstanding;
}
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by governance or the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault) || msg.sender == governance());
require(BaseStrategyLegacy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
*
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
*/
function protectedTokens() internal view virtual returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++)
require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(
governance(),
IERC20(_token).balanceOf(address(this))
);
}
}
// File: StrategyLegacy.sol
//This strategy is for 0.3.0 Vaults
contract StrategyLegacy is BaseStrategyLegacy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
ChefLike public masterchef;
IERC20 public reward;
address private constant uniswapRouter =
address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address private constant sushiswapRouter =
address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F);
address private constant weth =
address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IUniswapV2Router02 public router;
uint256 public pid;
address[] public path;
bool public harvestOnLiq;
event Cloned(address indexed clone);
modifier onlyGuardians() {
require(
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
constructor(
address _vault,
address _masterchef,
address _reward,
address _router,
uint256 _pid
) public BaseStrategyLegacy(_vault) {
_initializeStrat(_masterchef, _reward, _router, _pid);
}
function initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper,
address _masterchef,
address _reward,
address _router,
uint256 _pid
) external {
//note: initialise can only be called once. in _initialize in BaseStrategyLegacy we have: require(address(want) == address(0), "Strategy already initialized");
_initialize(_vault, _strategist, _rewards, _keeper);
_initializeStrat(_masterchef, _reward, _router, _pid);
}
function _initializeStrat(
address _masterchef,
address _reward,
address _router,
uint256 _pid
) internal {
require(
address(router) == address(0),
"Masterchef Strategy already initialized"
);
require(
_router == uniswapRouter || _router == sushiswapRouter,
"incorrect router"
);
// You can set these parameters on deployment to whatever you want
maxReportDelay = 6300;
profitFactor = 1500;
debtThreshold = 1_000_000 * 1e18;
masterchef = ChefLike(_masterchef);
reward = IERC20(_reward);
router = IUniswapV2Router02(_router);
pid = _pid;
path = getTokenOutPath(_reward, address(want));
harvestOnLiq = true;
require(
address(want) == masterchef.poolInfo(pid).stakingToken,
"wrong pid"
);
want.safeApprove(_masterchef, type(uint256).max);
reward.safeApprove(_router, type(uint256).max);
}
function cloneStrategy(
address _vault,
address _strategist,
address _rewards,
address _keeper,
address _masterchef,
address _reward,
address _router,
uint256 _pid
) external returns (address newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(address(this));
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(
clone_code,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(clone_code, 0x14), addressBytes)
mstore(
add(clone_code, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
newStrategy := create(0, clone_code, 0x37)
}
StrategyLegacy(newStrategy).initialize(
_vault,
_strategist,
_rewards,
_keeper,
_masterchef,
_reward,
_router,
_pid
);
emit Cloned(newStrategy);
}
function setRouter(address _router) public onlyAuthorized {
require(
_router == uniswapRouter || _router == sushiswapRouter,
"incorrect router"
);
router = IUniswapV2Router02(_router);
reward.safeApprove(_router, 0);
reward.safeApprove(_router, type(uint256).max);
}
function getTokenOutPath(address _token_in, address _token_out)
internal
view
returns (address[] memory _path)
{
bool is_weth =
_token_in == address(weth) || _token_out == address(weth);
_path = new address[](is_weth ? 2 : 3);
_path[0] = _token_in;
if (is_weth) {
_path[1] = _token_out;
} else {
_path[1] = address(weth);
_path[2] = _token_out;
}
}
function setPath(address[] calldata _path) public onlyGuardians {
path = _path;
}
// ******** OVERRIDE THESE METHODS FROM BASE CONTRACT ************
function name() external view override returns (string memory) {
return "StrategyMasterchefGenericMod";
}
function estimatedTotalAssets() public view override returns (uint256) {
uint256 deposited = masterchef.userInfo(pid, address(this)).amount;
return want.balanceOf(address(this)).add(deposited);
}
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
if (masterchef.pendingReward(pid, address(this)) > 0)
masterchef.deposit(pid, 0);
_sell();
uint256 assets = estimatedTotalAssets();
uint256 wantBal = want.balanceOf(address(this));
uint256 debt = vault.strategies(address(this)).totalDebt;
if (assets >= debt) {
_debtPayment = _debtOutstanding;
_profit = assets.sub(debt);
uint256 amountToFree = _profit.add(_debtPayment);
if (amountToFree > 0 && wantBal < amountToFree) {
liquidatePosition(amountToFree);
uint256 newLoose = want.balanceOf(address(this));
//if we dont have enough money adjust _debtOutstanding and only change profit if needed
if (newLoose < amountToFree) {
if (_profit > newLoose) {
_profit = newLoose;
_debtPayment = 0;
} else {
_debtPayment = Math.min(
newLoose - _profit,
_debtPayment
);
}
}
}
} else {
//serious loss should never happen but if it does lets record it accurately
_loss = debt - assets;
}
}
function adjustPosition(uint256 _debtOutstanding) internal override {
if (emergencyExit) {
return;
}
uint256 wantBalance = want.balanceOf(address(this));
masterchef.deposit(pid, wantBalance);
}
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
uint256 totalAssets = want.balanceOf(address(this));
if (_amountNeeded > totalAssets) {
uint256 amountToFree = _amountNeeded.sub(totalAssets);
uint256 deposited = masterchef.userInfo(pid, address(this)).amount;
if (deposited < amountToFree) {
amountToFree = deposited;
}
if (deposited > 0) {
//Workaround to get rewards even if we withdraw early
if (
masterchef.pendingReward(pid, address(this)) > 0 &&
harvestOnLiq
) {
masterchef.deposit(pid, 0);
}
//Withdraw all funds to get max funds
masterchef.emergencyWithdraw(pid);
uint256 newWantBal = want.balanceOf(address(this));
if (newWantBal > amountToFree) {
//Deposit back excess to farm
masterchef.deposit(pid, newWantBal.sub(amountToFree));
}
}
_liquidatedAmount = want.balanceOf(address(this));
} else {
_liquidatedAmount = _amountNeeded;
}
}
// NOTE: Can override `tendTrigger` and `harvestTrigger` if necessary
function prepareMigration(address _newStrategy) internal override {
liquidatePosition(type(uint256).max); //withdraw all. does not matter if we ask for too much
_sell();
}
function emergencyWithdrawal(uint256 _pid) external onlyGuardians {
masterchef.emergencyWithdraw(_pid);
}
function toggleharvestOnLiq() external onlyGuardians {
harvestOnLiq = !harvestOnLiq;
}
//sell all function
function _sell() internal {
uint256 rewardBal = reward.balanceOf(address(this));
if (rewardBal == 0) {
return;
}
if (path.length == 0) {
router.swapExactTokensForTokens(
rewardBal,
uint256(0),
getTokenOutPath(address(reward), address(want)),
address(this),
now
);
} else {
router.swapExactTokensForTokens(
rewardBal,
uint256(0),
path,
address(this),
now
);
}
}
function protectedTokens()
internal
view
override
returns (address[] memory)
{}
}
|
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 ====/ According to EIP-1052, 0x0 is the value returned for not-yet created accounts and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned for accounts without code, i.e. `keccak256('')` solhint-disable-next-line no-inline-assembly
|
function deposit(uint256 _pid, uint256 _amount) external;
function withdraw(uint256 _pid, uint256 _amount) external;
function emergencyWithdraw(uint256 _pid) external;
function poolInfo(uint256 _pid) external view returns (PoolInfo memory);
function userInfo(uint256 _pid, address user)
external
view
returns (UserInfo memory);
function harvest(uint256 _pid) external;
function pendingReward(uint256 _pid, address _user)
external
view
returns (uint256);
}
}
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
return (codehash != accountHash && codehash != 0x0);
}
| 1,610,343
|
/**
*Submitted for verification at Etherscan.io on 2020-05-28
*/
pragma solidity 0.5.16;
/**
* @title ModuleKeys
* @author Stability Labs Pty. Ltd.
* @notice Provides system wide access to the byte32 represntations of system modules
* This allows each system module to be able to reference and update one another in a
* friendly way
* @dev keccak256() values are hardcoded to avoid re-evaluation of the constants at runtime.
*/
contract ModuleKeys {
// keccak256("Governance");
bytes32 internal constant KEY_GOVERNANCE = 0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d;
//keccak256("Staking");
bytes32 internal constant KEY_STAKING = 0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034;
//keccak256("ProxyAdmin");
bytes32 internal constant KEY_PROXY_ADMIN = 0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1;
// keccak256("OracleHub");
bytes32 internal constant KEY_ORACLE_HUB = 0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040;
// keccak256("Manager");
bytes32 internal constant KEY_MANAGER = 0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f;
//keccak256("Recollateraliser");
bytes32 internal constant KEY_RECOLLATERALISER = 0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f;
//keccak256("MetaToken");
bytes32 internal constant KEY_META_TOKEN = 0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2;
// keccak256("SavingsManager");
bytes32 internal constant KEY_SAVINGS_MANAGER = 0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1;
}
/**
* @title INexus
* @dev Basic interface for interacting with the Nexus i.e. SystemKernel
*/
interface INexus {
function governor() external view returns (address);
function getModule(bytes32 key) external view returns (address);
function proposeModule(bytes32 _key, address _addr) external;
function cancelProposedModule(bytes32 _key) external;
function acceptProposedModule(bytes32 _key) external;
function acceptProposedModules(bytes32[] calldata _keys) external;
function requestLockModule(bytes32 _key) external;
function cancelLockModule(bytes32 _key) external;
function lockModule(bytes32 _key) external;
}
/**
* @title Module
* @author Stability Labs Pty. Ltd.
* @dev Subscribes to module updates from a given publisher by reading from its registry
*/
contract Module is ModuleKeys {
INexus public nexus;
/**
* @dev Initialises the Module by setting publisher addresses,
* and reading all available system module information
*/
constructor(address _nexus) internal {
require(_nexus != address(0), "Nexus is zero address");
nexus = INexus(_nexus);
}
/**
* @dev Modifier to allow function calls only from the Governor.
*/
modifier onlyGovernor() {
require(msg.sender == _governor(), "Only governor can execute");
_;
}
/**
* @dev Modifier to allow function calls only from the Governance.
* Governance is either Governor address or Governance address.
*/
modifier onlyGovernance() {
require(
msg.sender == _governor() || msg.sender == _governance(),
"Only governance can execute"
);
_;
}
/**
* @dev Modifier to allow function calls only from the ProxyAdmin.
*/
modifier onlyProxyAdmin() {
require(
msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute"
);
_;
}
/**
* @dev Modifier to allow function calls only from the Manager.
*/
modifier onlyManager() {
require(msg.sender == _manager(), "Only manager can execute");
_;
}
/**
* @dev Returns Governor address from the Nexus
* @return Address of Governor Contract
*/
function _governor() internal view returns (address) {
return nexus.governor();
}
/**
* @dev Returns Governance Module address from the Nexus
* @return Address of the Governance (Phase 2)
*/
function _governance() internal view returns (address) {
return nexus.getModule(KEY_GOVERNANCE);
}
/**
* @dev Return Staking Module address from the Nexus
* @return Address of the Staking Module contract
*/
function _staking() internal view returns (address) {
return nexus.getModule(KEY_STAKING);
}
/**
* @dev Return ProxyAdmin Module address from the Nexus
* @return Address of the ProxyAdmin Module contract
*/
function _proxyAdmin() internal view returns (address) {
return nexus.getModule(KEY_PROXY_ADMIN);
}
/**
* @dev Return MetaToken Module address from the Nexus
* @return Address of the MetaToken Module contract
*/
function _metaToken() internal view returns (address) {
return nexus.getModule(KEY_META_TOKEN);
}
/**
* @dev Return OracleHub Module address from the Nexus
* @return Address of the OracleHub Module contract
*/
function _oracleHub() internal view returns (address) {
return nexus.getModule(KEY_ORACLE_HUB);
}
/**
* @dev Return Manager Module address from the Nexus
* @return Address of the Manager Module contract
*/
function _manager() internal view returns (address) {
return nexus.getModule(KEY_MANAGER);
}
/**
* @dev Return SavingsManager Module address from the Nexus
* @return Address of the SavingsManager Module contract
*/
function _savingsManager() internal view returns (address) {
return nexus.getModule(KEY_SAVINGS_MANAGER);
}
/**
* @dev Return Recollateraliser Module address from the Nexus
* @return Address of the Recollateraliser Module contract (Phase 2)
*/
function _recollateraliser() internal view returns (address) {
return nexus.getModule(KEY_RECOLLATERALISER);
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/
contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
function () payable external {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize)
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal {
}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
/**
* Utility library of inline functions on addresses
*
* Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol
* This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts
* when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the
* build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version.
*/
library OpenZeppelinUpgradesAddress {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
/**
* @title BaseUpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/
contract BaseUpgradeabilityProxy is Proxy {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation.
* @return Address of the current implementation
*/
function _implementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
/**
* @title UpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
* implementation and init data.
*/
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if(_data.length > 0) {
(bool success,) = _logic.delegatecall(_data);
require(success);
}
}
}
/**
* @title BaseAdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/
contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function admin() external ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {
_upgradeTo(newImplementation);
(bool success,) = newImplementation.delegatecall(data);
require(success);
}
/**
* @return The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
}
/**
* @title AdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for
* initializing the implementation, admin, and init data.
*/
contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy {
/**
* Contract constructor.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, address _admin, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable {
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
}
/**
* @title DelayedProxyAdmin
* @author Stability Labs Pty. Ltd.
* @notice Proxy admin contract to upgrade the upgradable contracts. The upgradable contracts
* are transparent proxy contracts from OpenZeppelin-SDK.
* @dev The contract has a delyed upgradability. The Governor can propose a new implementation
* for a proxy contract. After 1 week of opt-out delay, upgrade request can be accepted
* and upgrade of contract is performed.
* Part of the code taken from OpenZeppelin-SDK's ProxyAdmin.sol
*/
contract DelayedProxyAdmin is Module {
using SafeMath for uint256;
event UpgradeProposed(address indexed proxy, address implementation, bytes data);
event UpgradeCancelled(address indexed proxy);
event Upgraded(address indexed proxy, address oldImpl, address newImpl, bytes data);
// Request struct to store proposed upgrade requests
struct Request{
address implementation; // New contract implementation address
bytes data; // Data to call a function on new contract implementation
uint256 timestamp; // Timestamp when upgrade request is proposed
}
// Opt-out upgrade delay
uint256 public constant UPGRADE_DELAY = 1 weeks;
// ProxyAddress => Request
mapping(address => Request) public requests;
/**
* @dev Constructor
* @param _nexus Nexus contract address
*/
constructor(address _nexus) public Module(_nexus) {}
/**
* @dev The Governor can propose a new contract implementation for a given proxy.
* @param _proxy Proxy address which is to be upgraded
* @param _implementation Contract address of new implementation
* @param _data calldata to execute initialization function upon upgrade
*/
function proposeUpgrade(
address _proxy,
address _implementation,
bytes calldata _data
)
external
onlyGovernor
{
require(_proxy != address(0), "Proxy address is zero");
require(_implementation != address(0), "Implementation address is zero");
require(requests[_proxy].implementation == address(0), "Upgrade already proposed");
validateProxy(_proxy, _implementation);
Request storage request = requests[_proxy];
request.implementation = _implementation;
request.data = _data;
request.timestamp = now;
emit UpgradeProposed(_proxy, _implementation, _data);
}
/**
* @dev The Governor can cancel any existing upgrade request.
* @param _proxy The proxy address of the existing request
*/
function cancelUpgrade(address _proxy) external onlyGovernor {
require(_proxy != address(0), "Proxy address is zero");
require(requests[_proxy].implementation != address(0), "No request found");
delete requests[_proxy];
emit UpgradeCancelled(_proxy);
}
/**
* @dev The Governor can accept upgrade request after opt-out delay over. The function is
* `payable`, to forward ETH to initialize function call upon upgrade.
* @param _proxy The address of the proxy
*/
function acceptUpgradeRequest(address payable _proxy) external payable onlyGovernor {
// _proxy is payable, because AdminUpgradeabilityProxy has fallback function
require(_proxy != address(0), "Proxy address is zero");
Request memory request = requests[_proxy];
require(_isDelayOver(request.timestamp), "Delay not over");
address newImpl = request.implementation;
bytes memory data = request.data;
address oldImpl = getProxyImplementation(_proxy);
// Deleting before to avoid re-entrancy
delete requests[_proxy];
if(data.length == 0) {
require(msg.value == 0, "msg.value should be zero");
AdminUpgradeabilityProxy(_proxy).upgradeTo(newImpl);
} else {
AdminUpgradeabilityProxy(_proxy).upgradeToAndCall.value(msg.value)(newImpl, data);
}
emit Upgraded(_proxy, oldImpl, newImpl, data);
}
/**
* @dev Checks that the opt-out delay is over
* @param _timestamp Timestamp when upgrade requested
* @return Returns `true` when upgrade delay is over, otherwise `false`
*/
function _isDelayOver(uint256 _timestamp) private view returns (bool) {
if(_timestamp > 0 && now >= _timestamp.add(UPGRADE_DELAY))
return true;
return false;
}
/**
* @dev Checks the given proxy address is a valid proxy for this contract
* @param _proxy The address of the proxy
* @param _newImpl New implementation contract address
*/
function validateProxy(address _proxy, address _newImpl) internal view {
// Proxy has an implementation
address currentImpl = getProxyImplementation(_proxy);
// Existing implementation must not be same as new one
require(_newImpl != currentImpl, "Implementation must be different");
// This contract is the Proxy admin of the given _proxy address
address admin = getProxyAdmin(_proxy);
require(admin == address(this), "Proxy admin not matched");
}
/**
* @dev Returns the admin of a proxy. Only the admin can query it.
* @param _proxy Contract address of Proxy
* @return The address of the current admin of the proxy.
*/
function getProxyAdmin(address _proxy) public view returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("admin()")) == 0xf851a440
(bool success, bytes memory returndata) = _proxy.staticcall(hex"f851a440");
require(success, "Call failed");
return abi.decode(returndata, (address));
}
/**
* @dev Returns the current implementation of a proxy.
* This is needed because only the proxy admin can query it.
* @param _proxy Contract address of Proxy
* @return The address of the current implementation of the proxy.
*/
function getProxyImplementation(address _proxy) public view returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("implementation()")) == 0x5c60da1b
(bool success, bytes memory returndata) = _proxy.staticcall(hex"5c60da1b");
require(success, "Call failed");
return abi.decode(returndata, (address));
}
// NOTICE: This can be removed. However, kept it for us to remind that we are not calling this fn.
// We are not allowing this function call from Governor or Governance.
/**
* @dev Changes the admin of a proxy.
* @param proxy Proxy to change admin.
* @param newAdmin Address to transfer proxy administration to.
*/
// function changeProxyAdmin(AdminUpgradeabilityProxy proxy, address newAdmin) public onlyGovernor {
// proxy.changeAdmin(newAdmin);
// }
}
|
Checks that the opt-out delay is over _timestamp Timestamp when upgrade requested return Returns `true` when upgrade delay is over, otherwise `false`/
|
function _isDelayOver(uint256 _timestamp) private view returns (bool) {
if(_timestamp > 0 && now >= _timestamp.add(UPGRADE_DELAY))
return true;
return false;
}
| 13,064,845
|
/**
* Copyright 2017-2020, bZeroX, LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
import "./AdvancedToken.sol";
import "./ProtocolLike.sol";
import "./FeedsLike.sol";
contract LegacyBZxObjects {
struct LoanOrder {
address loanTokenAddress;
address interestTokenAddress;
address collateralTokenAddress;
address oracleAddress;
uint256 loanTokenAmount;
uint256 interestAmount;
uint256 initialMarginAmount;
uint256 maintenanceMarginAmount;
uint256 maxDurationUnixTimestampSec;
bytes32 loanOrderHash;
}
struct LoanPosition {
address trader;
address collateralTokenAddressFilled;
address positionTokenAddressFilled;
uint256 loanTokenAmountFilled;
uint256 loanTokenAmountUsed;
uint256 collateralTokenAmountFilled;
uint256 positionTokenAmountFilled;
uint256 loanStartUnixTimestampSec;
uint256 loanEndUnixTimestampSec;
bool active;
uint256 positionId;
}
}
interface LegacyBZxLike {
function payInterestForOracle(
address oracleAddress,
address interestTokenAddress)
external
returns (uint256);
function getLenderInterestForOracle(
address lender,
address oracleAddress,
address interestTokenAddress)
external
view
returns (
uint256 interestPaid,
uint256 interestPaidDate,
uint256 interestOwedPerDay,
uint256 interestUnPaid);
}
contract LoanTokenLogicStandard is AdvancedToken {
using SafeMath for uint256;
address internal target_;
uint256 public constant VERSION = 5;
address internal constant arbitraryCaller = 0x000F400e6818158D541C3EBE45FE3AA0d47372FF;
function()
external
{
revert("fallback not allowed");
}
/* Public functions */
function mint(
address receiver,
uint256 depositAmount)
external
nonReentrant
returns (uint256 mintAmount)
{
return _mintToken(
receiver,
depositAmount
);
}
function burn(
address receiver,
uint256 burnAmount)
external
nonReentrant
returns (uint256 loanAmountPaid)
{
loanAmountPaid = _burnToken(
burnAmount
);
if (loanAmountPaid != 0) {
_safeTransfer(loanTokenAddress, receiver, loanAmountPaid, "5");
}
}
function flashBorrow(
uint256 borrowAmount,
address borrower,
address target,
string calldata signature,
bytes calldata data)
external
payable
nonReentrant
returns (bytes memory)
{
_checkPause();
_settleInterest();
// save before balances
uint256 beforeEtherBalance = address(this).balance.sub(msg.value);
uint256 beforeAssetsBalance = _underlyingBalance()
.add(totalAssetBorrows());
// lock totalAssetSupply for duration of flash loan
burntTokenReserved = beforeAssetsBalance;
// transfer assets to calling contract
if (borrowAmount != 0) {
_safeTransfer(loanTokenAddress, borrower, borrowAmount, "39");
}
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
// arbitrary call
(bool success, bytes memory returnData) = arbitraryCaller.call.value(msg.value)(
abi.encodeWithSelector(
0xde064e0d, // sendCall(address,bytes)
target,
callData
)
);
require(success, "call failed");
// unlock totalAssetSupply
burntTokenReserved = 0;
// verifies return of flash loan
require(
address(this).balance >= beforeEtherBalance &&
_underlyingBalance()
.add(totalAssetBorrows()) >= beforeAssetsBalance,
"40"
);
return returnData;
}
// ***** NOTE: Reentrancy is allowed here to allow flashloan use cases *****
function borrow(
bytes32 loanId, // 0 if new loan
uint256 withdrawAmount,
uint256 initialLoanDuration, // duration in seconds
uint256 collateralTokenSent, // if 0, loanId must be provided; any ETH sent must equal this value
address collateralTokenAddress, // if address(0), this means ETH and ETH must be sent with the call or loanId must be provided
address borrower,
address receiver,
bytes memory /*loanDataBytes*/) // arbitrary order data (for future use)
public
payable
returns (uint256, uint256) // returns new principal and new collateral added to loan
{
require(withdrawAmount != 0, "6");
_checkPause();
require(msg.value == 0 || msg.value == collateralTokenSent, "7");
require(collateralTokenSent != 0 || loanId != 0, "8");
require(collateralTokenAddress != address(0) || msg.value != 0 || loanId != 0, "9");
if (collateralTokenAddress == address(0)) {
collateralTokenAddress = wethToken;
}
require(collateralTokenAddress != loanTokenAddress, "10");
_settleInterest();
uint256[5] memory sentAmounts;
sentAmounts[1] = withdrawAmount;
// interestRate, interestInitialAmount, borrowAmount (newBorrowAmount)
(sentAmounts[0], sentAmounts[2], sentAmounts[1]) = _getInterestRateAndBorrowAmount(
sentAmounts[1],
_totalAssetSupplies(0), // interest is settled above
initialLoanDuration
);
return _borrowOrTrade(
loanId,
withdrawAmount,
2 * 10**18, // leverageAmount (translates to 150% margin for a Torque loan)
collateralTokenAddress,
[
address(this), // lender
borrower,
receiver,
address(0) // manager
],
[
sentAmounts[0], // interestRate
sentAmounts[1],
sentAmounts[2], // interestInitialAmount
0, // loanTokenSent
collateralTokenSent
],
"" // loanDataBytes
);
}
// Called to borrow and immediately get into a positions
// ***** NOTE: Reentrancy is allowed here to allow flashloan use cases *****
function marginTrade(
bytes32 loanId, // 0 if new loan
uint256 leverageAmount,
uint256 loanTokenSent,
uint256 collateralTokenSent,
address collateralTokenAddress,
address trader,
bytes memory loanDataBytes) // arbitrary order data
public
payable
returns (uint256, uint256) // returns new principal and new collateral added to trade
{
_checkPause();
if (collateralTokenAddress == address(0)) {
collateralTokenAddress = wethToken;
}
require(collateralTokenAddress != loanTokenAddress, "11");
uint256 totalDeposit = _totalDeposit(
collateralTokenAddress,
collateralTokenSent,
loanTokenSent
);
require(totalDeposit != 0, "12");
address[4] memory sentAddresses;
uint256[5] memory sentAmounts;
sentAddresses[0] = address(this); // lender
sentAddresses[1] = trader;
sentAddresses[2] = trader;
//sentAddresses[3] = address(0); // manager
//sentAmounts[0] = 0; // interestRate (found later)
sentAmounts[1] = totalDeposit; // total amount of deposit
//sentAmounts[2] = 0; // interestInitialAmount (interest is calculated based on fixed-term loan)
sentAmounts[3] = loanTokenSent;
sentAmounts[4] = collateralTokenSent;
_settleInterest();
(sentAmounts[1], sentAmounts[0]) = _getMarginBorrowAmountAndRate( // borrowAmount, interestRate
leverageAmount,
sentAmounts[1] // depositAmount
);
return _borrowOrTrade(
loanId,
0, // withdrawAmount
leverageAmount,
collateralTokenAddress,
sentAddresses,
sentAmounts,
loanDataBytes
);
}
function transfer(
address _to,
uint256 _value)
external
returns (bool)
{
return _internalTransferFrom(
msg.sender,
_to,
_value,
uint256(-1)
);
}
function transferFrom(
address _from,
address _to,
uint256 _value)
external
returns (bool)
{
return _internalTransferFrom(
_from,
_to,
_value,
ProtocolLike(bZxContract).isLoanPool(msg.sender) ?
uint256(-1) :
allowed[_from][msg.sender]
);
}
function _internalTransferFrom(
address _from,
address _to,
uint256 _value,
uint256 _allowanceAmount)
internal
returns (bool)
{
if (_allowanceAmount != uint256(-1)) {
require(_value <= _allowanceAmount, "14");
allowed[_from][msg.sender] = _allowanceAmount.sub(_value);
}
uint256 _balancesFrom = balances[_from];
uint256 _balancesTo = balances[_to];
require(_value <= _balancesFrom &&
_to != address(0),
"14"
);
uint256 _balancesFromNew = _balancesFrom
.sub(_value);
balances[_from] = _balancesFromNew;
uint256 _balancesToNew = _balancesTo
.add(_value);
balances[_to] = _balancesToNew;
// handle checkpoint update
uint256 _currentPrice = tokenPrice();
_updateCheckpoints(
_from,
_balancesFrom,
_balancesFromNew,
_currentPrice
);
_updateCheckpoints(
_to,
_balancesTo,
_balancesToNew,
_currentPrice
);
emit Transfer(_from, _to, _value);
return true;
}
event Debug(
bytes32 slot,
uint256 one,
uint256 two
);
function _updateCheckpoints(
address _user,
uint256 _oldBalance,
uint256 _newBalance,
uint256 _currentPrice)
internal
{
// keccak256("iToken_ProfitSoFar")
bytes32 slot = keccak256(
abi.encodePacked(_user, uint256(0x37aa2b7d583612f016e4a4de4292cb015139b3d7762663d06a53964912ea2fb6))
);
uint256 _currentProfit;
if (_oldBalance != 0 && _newBalance != 0) {
_currentProfit = _profitOf(
slot,
_oldBalance,
_currentPrice,
checkpointPrices_[_user]
);
} else if (_newBalance == 0) {
_currentPrice = 0;
}
assembly {
sstore(slot, _currentProfit)
}
checkpointPrices_[_user] = _currentPrice;
emit Debug(
slot,
_currentProfit,
_currentPrice
);
}
/* Public View functions */
function profitOf(
address user)
public
view
returns (uint256)
{
// keccak256("iToken_ProfitSoFar")
bytes32 slot = keccak256(
abi.encodePacked(user, uint256(0x37aa2b7d583612f016e4a4de4292cb015139b3d7762663d06a53964912ea2fb6))
);
return _profitOf(
slot,
balances[user],
tokenPrice(),
checkpointPrices_[user]
);
}
function _profitOf(
bytes32 slot,
uint256 _balance,
uint256 _currentPrice,
uint256 _checkpointPrice)
internal
view
returns (uint256)
{
if (_checkpointPrice == 0) {
return 0;
}
uint256 profitSoFar;
uint256 profitDiff;
assembly {
profitSoFar := sload(slot)
}
if (_currentPrice > _checkpointPrice) {
profitDiff = _balance
.mul(_currentPrice - _checkpointPrice)
.div(10**18);
profitSoFar = profitSoFar
.add(profitDiff);
} else {
profitDiff = _balance
.mul(_checkpointPrice - _currentPrice)
.div(10**18);
if (profitSoFar > profitDiff) {
profitSoFar = profitSoFar - profitDiff;
} else {
profitSoFar = 0;
}
}
return profitSoFar;
}
function tokenPrice()
public
view
returns (uint256 price)
{
uint256 interestUnPaid;
if (lastSettleTime_ != block.timestamp) {
(,interestUnPaid) = _getAllInterest();
}
return _tokenPrice(_totalAssetSupplies(interestUnPaid));
}
function checkpointPrice(
address _user)
public
view
returns (uint256 price)
{
return checkpointPrices_[_user];
}
function marketLiquidity()
public
view
returns (uint256)
{
uint256 totalSupply = _totalAssetSupplies(0);
uint256 totalBorrow = totalAssetBorrows();
if (totalSupply > totalBorrow) {
return totalSupply.sub(totalBorrow);
}
}
function avgBorrowInterestRate()
public
view
returns (uint256)
{
return _avgBorrowInterestRate(totalAssetBorrows());
}
// the minimum rate the next base protocol borrower will receive for variable-rate loans
function borrowInterestRate()
public
view
returns (uint256)
{
return _nextBorrowInterestRate(
0, // borrowAmount
false // useFixedInterestModel
);
}
function nextBorrowInterestRate(
uint256 borrowAmount)
public
view
returns (uint256)
{
return _nextBorrowInterestRate(
borrowAmount,
false // useFixedInterestModel
);
}
function nextBorrowInterestRateWithOption(
uint256 borrowAmount,
bool useFixedInterestModel)
public
view
returns (uint256)
{
return _nextBorrowInterestRate(
borrowAmount,
useFixedInterestModel
);
}
// interest that lenders are currently receiving when supplying to the pool
function supplyInterestRate()
public
view
returns (uint256)
{
return totalSupplyInterestRate(_totalAssetSupplies(0));
}
function nextSupplyInterestRate(
uint256 supplyAmount)
public
view
returns (uint256)
{
return totalSupplyInterestRate(_totalAssetSupplies(0).add(supplyAmount));
}
function totalSupplyInterestRate(
uint256 assetSupply)
public
view
returns (uint256)
{
uint256 assetBorrow = totalAssetBorrows();
if (assetBorrow != 0) {
return _supplyInterestRate(
assetBorrow,
assetSupply
);
}
}
function totalAssetBorrows()
public
view
returns (uint256)
{
return ProtocolLike(bZxContract).getTotalPrincipal(
address(this),
loanTokenAddress
).add(totalAssetBorrow);
}
function totalAssetSupply()
public
view
returns (uint256)
{
return totalAssetSupplies();
}
function totalAssetSupplies()
public
view
returns (uint256)
{
uint256 interestUnPaid;
if (lastSettleTime_ != block.timestamp) {
(,interestUnPaid) = _getAllInterest();
}
return _totalAssetSupplies(interestUnPaid);
}
function getMaxEscrowAmount(
uint256 leverageAmount)
public
view
returns (uint256)
{
uint256 initialMargin = SafeMath.div(10**38, leverageAmount);
return marketLiquidity()
.mul(initialMargin)
.div(_adjustValue(
10**20, // maximum possible interest (100%)
2419200, // 28 day duration for margin trades
initialMargin));
}
// returns the user's balance of underlying token
function assetBalanceOf(
address _owner)
public
view
returns (uint256)
{
return balanceOf(_owner)
.mul(tokenPrice())
.div(10**18);
}
function getEstimatedMarginDetails(
uint256 leverageAmount,
uint256 loanTokenSent,
uint256 collateralTokenSent,
address collateralTokenAddress) // address(0) means ETH
public
view
returns (uint256 principal, uint256 collateral, uint256 interestRate)
{
if (collateralTokenAddress == address(0)) {
collateralTokenAddress = wethToken;
}
uint256 totalDeposit = _totalDeposit(
collateralTokenAddress,
collateralTokenSent,
loanTokenSent
);
(principal, interestRate) = _getMarginBorrowAmountAndRate(
leverageAmount,
totalDeposit
);
if (principal > _underlyingBalance()) {
return (0, 0, 0);
}
loanTokenSent = loanTokenSent
.add(principal);
collateral = ProtocolLike(bZxContract).getEstimatedMarginExposure(
loanTokenAddress,
collateralTokenAddress,
loanTokenSent,
collateralTokenSent,
interestRate,
principal
);
}
function getDepositAmountForBorrow(
uint256 borrowAmount,
uint256 initialLoanDuration, // duration in seconds
address collateralTokenAddress) // address(0) means ETH
public
view
returns (uint256 depositAmount)
{
if (borrowAmount != 0) {
// adjust value since interest is also borrowed
borrowAmount = borrowAmount
.mul(_getTargetNextRateMultiplierValue(initialLoanDuration))
.div(10**22);
if (borrowAmount <= _underlyingBalance()) {
return ProtocolLike(bZxContract).getRequiredCollateral(
loanTokenAddress,
collateralTokenAddress != address(0) ? collateralTokenAddress : wethToken,
borrowAmount,
50 * 10**18, // initialMargin
true // isTorqueLoan
).add(10); // some dust to compensate for rounding errors
}
}
}
function getBorrowAmountForDeposit(
uint256 depositAmount,
uint256 initialLoanDuration, // duration in seconds
address collateralTokenAddress) // address(0) means ETH
public
view
returns (uint256 borrowAmount)
{
if (depositAmount != 0) {
borrowAmount = ProtocolLike(bZxContract).getBorrowAmount(
loanTokenAddress,
collateralTokenAddress != address(0) ? collateralTokenAddress : wethToken,
depositAmount,
50 * 10**18, // initialMargin,
true // isTorqueLoan
);
// adjust value since interest is also borrowed
borrowAmount = borrowAmount
.mul(10**22)
.div(_getTargetNextRateMultiplierValue(initialLoanDuration));
if (borrowAmount > _underlyingBalance()) {
borrowAmount = 0;
}
}
}
/* Internal functions */
function _mintToken(
address receiver,
uint256 depositAmount)
internal
returns (uint256 mintAmount)
{
require (depositAmount != 0, "17");
_settleInterest();
uint256 currentPrice = _tokenPrice(_totalAssetSupplies(0));
mintAmount = depositAmount
.mul(10**18)
.div(currentPrice);
if (msg.value == 0) {
_safeTransferFrom(loanTokenAddress, msg.sender, address(this), depositAmount, "18");
} else {
IWeth(wethToken).deposit.value(depositAmount)();
}
uint256 oldBalance = balances[receiver];
_updateCheckpoints(
receiver,
oldBalance,
_mint(receiver, mintAmount, depositAmount, currentPrice), // newBalance
currentPrice
);
}
function _burnToken(
uint256 burnAmount)
internal
returns (uint256 loanAmountPaid)
{
require(burnAmount != 0, "19");
if (burnAmount > balanceOf(msg.sender)) {
burnAmount = balanceOf(msg.sender);
}
_settleInterest();
uint256 currentPrice = _tokenPrice(_totalAssetSupplies(0));
uint256 loanAmountOwed = burnAmount
.mul(currentPrice)
.div(10**18);
uint256 loanAmountAvailableInContract = _underlyingBalance();
loanAmountPaid = loanAmountOwed;
require(loanAmountPaid <= loanAmountAvailableInContract, "37");
uint256 oldBalance = balances[msg.sender];
_updateCheckpoints(
msg.sender,
oldBalance,
_burn(msg.sender, burnAmount, loanAmountPaid, currentPrice), // newBalance
currentPrice
);
}
function _settleInterest()
internal
{
if (lastSettleTime_ != block.timestamp) {
ProtocolLike(bZxContract).withdrawAccruedInterest(
loanTokenAddress
);
// legacy interest handling
_getLegacyProtocol().payInterestForOracle(
bZxOracle,
loanTokenAddress
);
lastSettleTime_ = block.timestamp;
}
}
function _totalDeposit(
address collateralTokenAddress,
uint256 collateralTokenSent,
uint256 loanTokenSent)
internal
view
returns (uint256 totalDeposit)
{
totalDeposit = loanTokenSent;
if (collateralTokenSent != 0) {
(uint256 sourceToDestRate, uint256 sourceToDestPrecision) = FeedsLike(ProtocolLike(bZxContract).priceFeeds()).queryRate(
collateralTokenAddress,
loanTokenAddress
);
if (sourceToDestPrecision != 0) {
totalDeposit = collateralTokenSent
.mul(sourceToDestRate)
.div(sourceToDestPrecision)
.add(totalDeposit);
}
}
}
function _getTargetNextRateMultiplierValue(
uint256 initialLoanDuration)
internal
view
returns (uint256)
{
uint256 thisBaseRate;
uint256 thisRateMultiplier;
//keccak256("iToken_FixedInterestBaseRate")
//keccak256("iToken_FixedInterestRateMultiplier")
assembly {
thisBaseRate := sload(0x185a40c6b6d3f849f72c71ea950323d21149c27a9d90f7dc5e5ea2d332edcf7f)
thisRateMultiplier := sload(0x9ff54bc0049f5eab56ca7cd14591be3f7ed6355b856d01e3770305c74a004ea2)
}
return thisRateMultiplier
.mul(80 ether)
.div(10**20)
.add(thisBaseRate)
.mul(initialLoanDuration)
.div(315360) // 365 * 86400 / 100
.add(10**22);
}
function _getInterestRateAndBorrowAmount(
uint256 borrowAmount,
uint256 assetSupply,
uint256 initialLoanDuration) // duration in seconds
internal
view
returns (uint256 interestRate, uint256 interestInitialAmount, uint256 newBorrowAmount)
{
interestRate = _nextBorrowInterestRate2(
borrowAmount,
assetSupply,
true // useFixedInterestModel
);
// newBorrowAmount = borrowAmount * 10^18 / (10^18 - interestRate * 7884000 * 10^18 / 31536000 / 10^20)
newBorrowAmount = borrowAmount
.mul(10**18)
.div(
SafeMath.sub(10**18,
interestRate
.mul(initialLoanDuration)
.mul(10**18)
.div(31536000 * 10**20) // 365 * 86400 * 10**20
)
);
interestInitialAmount = newBorrowAmount
.sub(borrowAmount);
}
// returns newPrincipal
function _borrowOrTrade(
bytes32 loanId,
uint256 withdrawAmount,
uint256 leverageAmount,
address collateralTokenAddress,
address[4] memory sentAddresses,
uint256[5] memory sentAmounts,
bytes memory loanDataBytes)
internal
returns (uint256, uint256)
{
_checkPause();
require (sentAmounts[1] <= _underlyingBalance() && // newPrincipal
sentAddresses[1] != address(0), // borrower
"24"
);
if (sentAddresses[2] == address(0)) {
sentAddresses[2] = sentAddresses[1]; // receiver = borrower
}
// handle transfers prior to adding newPrincipal to loanTokenSent
_verifyTransfers(
collateralTokenAddress,
sentAddresses,
sentAmounts,
withdrawAmount
);
// adding the loan token portion from the lender to loanTokenSent
sentAmounts[3] = sentAmounts[3]
.add(sentAmounts[1]); // newPrincipal
if (withdrawAmount != 0) {
// withdrawAmount already sent to the borrower, so we aren't sending it to the protocol
sentAmounts[3] = sentAmounts[3]
.sub(withdrawAmount);
}
uint256 msgValue;
if (msg.value != 0) {
msgValue = address(this).balance;
if (msgValue > msg.value) {
msgValue = msg.value;
}
}
bytes32 loanParamsId = loanOrderHashes[uint256(keccak256(abi.encodePacked(
collateralTokenAddress,
withdrawAmount != 0 ? // isTorqueLoan
true :
false
)))];
// converting to initialMargin
leverageAmount = SafeMath.div(10**38, leverageAmount);
(sentAmounts[1], sentAmounts[4]) = ProtocolLike(bZxContract).borrowOrTradeFromPool.value(msgValue)( // newPrincipal, newCollateral
loanParamsId,
loanId,
withdrawAmount != 0 ? // isTorqueLoan
true :
false,
leverageAmount, // initialMargin
sentAddresses,
sentAmounts,
loanDataBytes
);
require (sentAmounts[1] != 0, "25");
return (sentAmounts[1], sentAmounts[4]); // newPrincipal, newCollateral
}
// sentAddresses[0]: lender
// sentAddresses[1]: borrower
// sentAddresses[2]: receiver
// sentAddresses[3]: manager
// sentAmounts[0]: interestRate
// sentAmounts[1]: newPrincipal
// sentAmounts[2]: interestInitialAmount
// sentAmounts[3]: loanTokenSent
// sentAmounts[4]: collateralTokenSent
function _verifyTransfers(
address collateralTokenAddress,
address[4] memory sentAddresses,
uint256[5] memory sentAmounts,
uint256 withdrawalAmount)
internal
{
address _wethToken = wethToken;
address _loanTokenAddress = loanTokenAddress;
address receiver = sentAddresses[2];
uint256 newPrincipal = sentAmounts[1];
uint256 loanTokenSent = sentAmounts[3];
uint256 collateralTokenSent = sentAmounts[4];
require(_loanTokenAddress != collateralTokenAddress, "26");
if (withdrawalAmount != 0) { // withdrawOnOpen == true
_safeTransfer(_loanTokenAddress, receiver, withdrawalAmount, "");
if (newPrincipal > withdrawalAmount) {
_safeTransfer(_loanTokenAddress, bZxContract, newPrincipal - withdrawalAmount, "");
}
} else {
_safeTransfer(_loanTokenAddress, bZxContract, newPrincipal, "27");
}
if (collateralTokenSent != 0) {
if (collateralTokenAddress == _wethToken && msg.value != 0 && msg.value >= collateralTokenSent) {
IWeth(_wethToken).deposit.value(collateralTokenSent)();
_safeTransfer(collateralTokenAddress, bZxContract, collateralTokenSent, "28");
} else {
_safeTransferFrom(collateralTokenAddress, msg.sender, bZxContract, collateralTokenSent, "28");
}
}
if (loanTokenSent != 0) {
_safeTransferFrom(_loanTokenAddress, msg.sender, bZxContract, loanTokenSent, "29");
}
}
function _safeTransfer(
address token,
address to,
uint256 amount,
string memory errorMsg)
internal
{
_callOptionalReturn(
token,
abi.encodeWithSelector(IERC20(token).transfer.selector, to, amount),
errorMsg
);
}
function _safeTransferFrom(
address token,
address from,
address to,
uint256 amount,
string memory errorMsg)
internal
{
_callOptionalReturn(
token,
abi.encodeWithSelector(IERC20(token).transferFrom.selector, from, to, amount),
errorMsg
);
}
function _callOptionalReturn(
address token,
bytes memory data,
string memory errorMsg)
internal
{
(bool success, bytes memory returndata) = token.call(data);
require(success, errorMsg);
if (returndata.length != 0) {
require(abi.decode(returndata, (bool)), errorMsg);
}
}
function _underlyingBalance()
internal
view
returns (uint256)
{
return IERC20(loanTokenAddress).balanceOf(address(this));
}
/* Internal View functions */
function _tokenPrice(
uint256 assetSupply)
internal
view
returns (uint256)
{
uint256 totalTokenSupply = totalSupply_;
return totalTokenSupply != 0 ?
assetSupply
.mul(10**18)
.div(totalTokenSupply) : initialPrice;
}
function _avgBorrowInterestRate(
uint256 assetBorrow)
internal
view
returns (uint256)
{
if (assetBorrow != 0) {
(uint256 interestOwedPerDay,) = _getAllInterest();
return interestOwedPerDay
.mul(10**20)
.div(assetBorrow)
.mul(365);
}
}
// next supply interest adjustment
function _supplyInterestRate(
uint256 assetBorrow,
uint256 assetSupply)
public
view
returns (uint256)
{
if (assetBorrow != 0 && assetSupply >= assetBorrow) {
return _avgBorrowInterestRate(assetBorrow)
.mul(_utilizationRate(assetBorrow, assetSupply))
.mul(spreadMultiplier)
.div(10**40);
}
}
function _nextBorrowInterestRate(
uint256 borrowAmount,
bool useFixedInterestModel)
internal
view
returns (uint256)
{
uint256 interestUnPaid;
if (borrowAmount != 0) {
if (lastSettleTime_ != block.timestamp) {
(,interestUnPaid) = _getAllInterest();
}
uint256 balance = _underlyingBalance()
.add(interestUnPaid);
if (borrowAmount > balance) {
borrowAmount = balance;
}
}
return _nextBorrowInterestRate2(
borrowAmount,
_totalAssetSupplies(interestUnPaid),
useFixedInterestModel
);
}
function _nextBorrowInterestRate2(
uint256 newBorrowAmount,
uint256 assetSupply,
bool /*useFixedInterestModel*/) // kept for legacy reasons since calling functions have the param (now always assumed "true")
internal
view
returns (uint256 nextRate)
{
uint256 utilRate = _utilizationRate(
totalAssetBorrows().add(newBorrowAmount),
assetSupply
);
uint256 minRate;
uint256 maxRate;
uint256 thisBaseRate;
uint256 thisRateMultiplier;
/*if (useFixedInterestModel) {
if (utilRate < 80 ether) {
// target 80% utilization when loan is fixed-rate and utilization is under 80%
utilRate = 80 ether;
}
//keccak256("iToken_FixedInterestBaseRate")
//keccak256("iToken_FixedInterestRateMultiplier")
assembly {
thisBaseRate := sload(0x185a40c6b6d3f849f72c71ea950323d21149c27a9d90f7dc5e5ea2d332edcf7f)
thisRateMultiplier := sload(0x9ff54bc0049f5eab56ca7cd14591be3f7ed6355b856d01e3770305c74a004ea2)
}
} else if (utilRate < 50 ether) {
thisBaseRate = _getLowUtilBaseRate();
//keccak256("iToken_LowUtilRateMultiplier")
assembly {
thisRateMultiplier := sload(0x2b4858b1bc9e2d14afab03340ce5f6c81b703c86a0c570653ae586534e095fb1)
}
} else {
thisBaseRate = baseRate;
thisRateMultiplier = rateMultiplier;
}*/
if (utilRate < 80 ether) {
// target 80% utilization when loan is fixed-rate and utilization is under 80%
utilRate = 80 ether;
}
//keccak256("iToken_FixedInterestBaseRate")
//keccak256("iToken_FixedInterestRateMultiplier")
assembly {
thisBaseRate := sload(0x185a40c6b6d3f849f72c71ea950323d21149c27a9d90f7dc5e5ea2d332edcf7f)
thisRateMultiplier := sload(0x9ff54bc0049f5eab56ca7cd14591be3f7ed6355b856d01e3770305c74a004ea2)
}
if (utilRate > 90 ether) {
// scale rate proportionally up to 100%
utilRate = utilRate.sub(90 ether);
if (utilRate > 10 ether)
utilRate = 10 ether;
maxRate = thisRateMultiplier
.add(thisBaseRate)
.mul(90)
.div(100);
nextRate = utilRate
.mul(SafeMath.sub(100 ether, maxRate))
.div(10 ether)
.add(maxRate);
} else {
nextRate = utilRate
.mul(thisRateMultiplier)
.div(10**20)
.add(thisBaseRate);
minRate = thisBaseRate;
maxRate = thisRateMultiplier
.add(thisBaseRate);
if (nextRate < minRate)
nextRate = minRate;
else if (nextRate > maxRate)
nextRate = maxRate;
}
}
function _getAllInterest()
internal
view
returns (
uint256 interestOwedPerDay,
uint256 interestUnPaid)
{
// interestPaid, interestPaidDate, interestOwedPerDay, interestUnPaid, principalTotal
(,,interestOwedPerDay,interestUnPaid,) = ProtocolLike(bZxContract).getLenderInterestData(
address(this),
loanTokenAddress
);
// legacy interest handling
(,,uint256 interestOwedPerDayExtra, uint256 interestUnPaidExtra) = _getLegacyProtocol().getLenderInterestForOracle(
address(this),
bZxOracle,
loanTokenAddress
);
interestOwedPerDay = interestOwedPerDay
.add(interestOwedPerDayExtra);
interestUnPaid = interestUnPaid
.add(interestUnPaidExtra);
interestUnPaid = interestUnPaid
.mul(spreadMultiplier)
.div(10**20);
}
function _getLegacyProtocol()
internal
view
returns (LegacyBZxLike)
{
//keccak256("iToken_LegacyProtocolContract")
LegacyBZxLike bzx;
assembly {
bzx := sload(0xb63afa61a70d23f8df32ca45a46641070aaebe46fca63e7727aa8423b712a13d)
}
return bzx;
}
function _getMarginBorrowAmountAndRate(
uint256 leverageAmount,
uint256 depositAmount)
internal
view
returns (uint256 borrowAmount, uint256 interestRate)
{
uint256 initialMargin = SafeMath.div(10**38, leverageAmount);
interestRate = _nextBorrowInterestRate2(
depositAmount
.mul(10**20)
.div(initialMargin),
_totalAssetSupplies(0),
false // useFixedInterestModel
);
// assumes that loan, collateral, and interest token are the same
borrowAmount = depositAmount
.mul(10**40)
.div(_adjustValue(
interestRate,
2419200, // 28 day duration for margin trades
initialMargin))
.div(initialMargin);
}
function _totalAssetSupplies(
uint256 interestUnPaid)
internal
view
returns (uint256 assetSupply)
{
if (totalSupply_ != 0) {
uint256 assetsBalance = burntTokenReserved; // temporary holder when flash lending
if (assetsBalance == 0) {
assetsBalance = _underlyingBalance()
.add(totalAssetBorrows());
}
return assetsBalance
.add(interestUnPaid);
}
}
function _getLowUtilBaseRate()
internal
view
returns (uint256 lowUtilBaseRate)
{
//keccak256("iToken_LowUtilBaseRate")
assembly {
lowUtilBaseRate := sload(0x3d82e958c891799f357c1316ae5543412952ae5c423336f8929ed7458039c995)
}
}
function _checkPause()
internal
view
{
//keccak256("iToken_FunctionPause")
bytes32 slot = keccak256(abi.encodePacked(msg.sig, uint256(0xd46a704bc285dbd6ff5ad3863506260b1df02812f4f857c8cc852317a6ac64f2)));
bool isPaused;
assembly {
isPaused := sload(slot)
}
require(!isPaused, "unauthorized");
}
function _adjustValue(
uint256 interestRate,
uint256 maxDuration,
uint256 marginAmount)
internal
pure
returns (uint256)
{
return maxDuration != 0 ?
interestRate
.mul(10**20)
.div(31536000) // 86400 * 365
.mul(maxDuration)
.div(marginAmount)
.add(10**20) :
10**20;
}
function _utilizationRate(
uint256 assetBorrow,
uint256 assetSupply)
internal
pure
returns (uint256)
{
if (assetBorrow != 0 && assetSupply != 0) {
// U = total_borrow / total_supply
return assetBorrow
.mul(10**20)
.div(assetSupply);
}
}
// Called only by BZxOracle when a loan is partially or fully closed
// Used for backwards compatibility with bZx v1
function closeLoanNotifier(
LegacyBZxObjects.LoanOrder memory,
LegacyBZxObjects.LoanPosition memory,
address /*loanCloser*/,
uint256 closeAmount,
bool /*isLiquidation*/)
public
returns (bool)
{
require(msg.sender == ProtocolLike(bZxContract).getLegacyOracle(bZxOracle), "1");
_settleInterest();
totalAssetBorrow = totalAssetBorrow > closeAmount ?
totalAssetBorrow.sub(closeAmount) : 0;
return true;
}
/* Owner-Only functions */
// once the pools are migrated, patch again with this removed
function tmpMigratePool(
address oldBZxContract,
address newBZxContract)
external
onlyOwner
{
bZxContract = newBZxContract;
bZxVault = newBZxContract;
// keccak256("iToken_LegacyProtocolContract")
assembly {
sstore(0xb63afa61a70d23f8df32ca45a46641070aaebe46fca63e7727aa8423b712a13d, oldBZxContract)
}
}
function updateSettings(
address settingsTarget,
bytes memory callData)
public
{
if (msg.sender != owner()) {
address _lowerAdmin;
address _lowerAdminContract;
//keccak256("iToken_LowerAdminAddress")
//keccak256("iToken_LowerAdminContract")
assembly {
_lowerAdmin := sload(0x7ad06df6a0af6bd602d90db766e0d5f253b45187c3717a0f9026ea8b10ff0d4b)
_lowerAdminContract := sload(0x34b31cff1dbd8374124bd4505521fc29cab0f9554a5386ba7d784a4e611c7e31)
}
require(msg.sender == _lowerAdmin && settingsTarget == _lowerAdminContract);
}
address currentTarget = target_;
target_ = settingsTarget;
(bool result,) = address(this).call(callData);
uint256 size;
uint256 ptr;
assembly {
size := returndatasize
ptr := mload(0x40)
returndatacopy(ptr, 0, size)
if eq(result, 0) { revert(ptr, size) }
}
target_ = currentTarget;
assembly {
return(ptr, size)
}
}
}
|
keccak256("iToken_FunctionPause")
|
{
bytes32 slot = keccak256(abi.encodePacked(msg.sig, uint256(0xd46a704bc285dbd6ff5ad3863506260b1df02812f4f857c8cc852317a6ac64f2)));
bool isPaused;
function _checkPause()
internal
view
assembly {
isPaused := sload(slot)
}
require(!isPaused, "unauthorized");
}
| 975,831
|
pragma solidity ^0.8.13;
/// @title A Hello world example
contract HelloWorld {
/// Some example struct
struct Person {
uint age;
address wallet;
}
/**
Here's a more double asterix comment
*/
Person public theDude;
/// Constructs the dude
/// @param age The dude's age
constructor(uint256 age) {
theDude = Person({
age: age,
wallet: msg.sender
});
}
/** @dev does nothing */
function example() public {}
/** @dev Calculates a rectangle's surface and perimeter.
* @param w Width of the rectangle.
* @param h Height of the rectangle.
* @return s The calculated surface.
* @return p The calculated perimeter.
*/
function rectangle(uint256 w, uint256 h) public pure returns (uint256 s, uint256 p) {
s = w * h;
p = 2 * (w + h);
}
}
|
does nothing /
|
function example() public {}
| 5,422,100
|
./full_match/43113/0x64C79De9386428Ef48378a2099e6211459e9c37D/sources/Insurance/investedPoolIntegration.sol
|
Interface of the ERC20 standard as defined in the EIP./
|
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
| 7,170,299
|
pragma solidity ^0.5.13;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "./interfaces/IAccounts.sol";
import "../common/Initializable.sol";
import "../common/interfaces/ICeloVersionedContract.sol";
import "../common/Signatures.sol";
import "../common/UsingRegistry.sol";
import "../common/libraries/ReentrancyGuard.sol";
contract Accounts is
IAccounts,
ICeloVersionedContract,
Ownable,
ReentrancyGuard,
Initializable,
UsingRegistry
{
using SafeMath for uint256;
struct Signers {
// The address that is authorized to vote in governance and validator elections on behalf of the
// account. The account can vote as well, whether or not a vote signing key has been specified.
address vote;
// The address that is authorized to manage a validator or validator group and sign consensus
// messages on behalf of the account. The account can manage the validator, whether or not a
// validator signing key has been specified. However, if a validator signing key has been
// specified, only that key may actually participate in consensus.
address validator;
// The address of the key with which this account wants to sign attestations on the Attestations
// contract
address attestation;
}
struct SignerAuthorization {
bool started;
bool completed;
}
struct Account {
bool exists;
// [Deprecated] Each account may authorize signing keys to use for voting,
// validating or attestation. These keys may not be keys of other accounts,
// and may not be authorized by any other account for any purpose.
Signers signers;
// The address at which the account expects to receive transfers. If it's empty/0x0, the
// account indicates that an address exchange should be initiated with the dataEncryptionKey
address walletAddress;
// An optional human readable identifier for the account
string name;
// The ECDSA public key used to encrypt and decrypt data for this account
bytes dataEncryptionKey;
// The URL under which an account adds metadata and claims
string metadataURL;
}
mapping(address => Account) internal accounts;
// Maps authorized signers to the account that provided the authorization.
mapping(address => address) public authorizedBy;
// Default signers by account (replaces the legacy Signers struct on Account)
mapping(address => mapping(bytes32 => address)) defaultSigners;
// All signers and their roles for a given account
// solhint-disable-next-line max-line-length
mapping(address => mapping(bytes32 => mapping(address => SignerAuthorization))) signerAuthorizations;
bytes32 public constant EIP712_AUTHORIZE_SIGNER_TYPEHASH = keccak256(
"AuthorizeSigner(address account,address signer,bytes32 role)"
);
bytes32 public eip712DomainSeparator;
bytes32 constant ValidatorSigner = keccak256(abi.encodePacked("celo.org/core/validator"));
bytes32 constant AttestationSigner = keccak256(abi.encodePacked("celo.org/core/attestation"));
bytes32 constant VoteSigner = keccak256(abi.encodePacked("celo.org/core/vote"));
event AttestationSignerAuthorized(address indexed account, address signer);
event VoteSignerAuthorized(address indexed account, address signer);
event ValidatorSignerAuthorized(address indexed account, address signer);
event SignerAuthorized(address indexed account, address signer, bytes32 indexed role);
event SignerAuthorizationStarted(address indexed account, address signer, bytes32 indexed role);
event SignerAuthorizationCompleted(address indexed account, address signer, bytes32 indexed role);
event AttestationSignerRemoved(address indexed account, address oldSigner);
event VoteSignerRemoved(address indexed account, address oldSigner);
event ValidatorSignerRemoved(address indexed account, address oldSigner);
event IndexedSignerSet(address indexed account, address signer, bytes32 role);
event IndexedSignerRemoved(address indexed account, address oldSigner, bytes32 role);
event DefaultSignerSet(address indexed account, address signer, bytes32 role);
event DefaultSignerRemoved(address indexed account, address oldSigner, bytes32 role);
event LegacySignerSet(address indexed account, address signer, bytes32 role);
event LegacySignerRemoved(address indexed account, address oldSigner, bytes32 role);
event SignerRemoved(address indexed account, address oldSigner, bytes32 indexed role);
event AccountDataEncryptionKeySet(address indexed account, bytes dataEncryptionKey);
event AccountNameSet(address indexed account, string name);
event AccountMetadataURLSet(address indexed account, string metadataURL);
event AccountWalletAddressSet(address indexed account, address walletAddress);
event AccountCreated(address indexed account);
/**
* @notice Sets initialized == true on implementation contracts
* @param test Set to true to skip implementation initialization
*/
constructor(bool test) public Initializable(test) {}
/**
* @notice Returns the storage, major, minor, and patch version of the contract.
* @return The storage, major, minor, and patch version of the contract.
*/
function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) {
return (1, 1, 2, 1);
}
/**
* @notice Used in place of the constructor to allow the contract to be upgradable via proxy.
* @param registryAddress The address of the registry core smart contract.
*/
function initialize(address registryAddress) external initializer {
_transferOwnership(msg.sender);
setRegistry(registryAddress);
setEip712DomainSeparator();
}
/**
* @notice Sets the EIP712 domain separator for the Celo Accounts abstraction.
*/
function setEip712DomainSeparator() public {
uint256 chainId;
assembly {
chainId := chainid
}
eip712DomainSeparator = keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
keccak256(bytes("Celo Core Contracts")),
keccak256("1.0"),
chainId,
address(this)
)
);
}
/**
* @notice Convenience Setter for the dataEncryptionKey and wallet address for an account
* @param name A string to set as the name of the account
* @param dataEncryptionKey secp256k1 public key for data encryption. Preferably compressed.
* @param walletAddress The wallet address to set for the account
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev v, r, s constitute `signer`'s signature on `msg.sender` (unless the wallet address
* is 0x0 or msg.sender).
*/
function setAccount(
string calldata name,
bytes calldata dataEncryptionKey,
address walletAddress,
uint8 v,
bytes32 r,
bytes32 s
) external {
if (!isAccount(msg.sender)) {
createAccount();
}
setName(name);
setAccountDataEncryptionKey(dataEncryptionKey);
setWalletAddress(walletAddress, v, r, s);
}
/**
* @notice Creates an account.
* @return True if account creation succeeded.
*/
function createAccount() public returns (bool) {
require(isNotAccount(msg.sender) && isNotAuthorizedSigner(msg.sender), "Account exists");
Account storage account = accounts[msg.sender];
account.exists = true;
emit AccountCreated(msg.sender);
return true;
}
/**
* @notice Setter for the name of an account.
* @param name The name to set.
*/
function setName(string memory name) public {
require(isAccount(msg.sender), "Unknown account");
Account storage account = accounts[msg.sender];
account.name = name;
emit AccountNameSet(msg.sender, name);
}
/**
* @notice Setter for the wallet address for an account
* @param walletAddress The wallet address to set for the account
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev Wallet address can be zero. This means that the owner of the wallet
* does not want to be paid directly without interaction, and instead wants users to
* contact them, using the data encryption key, and arrange a payment.
* @dev v, r, s constitute `signer`'s signature on `msg.sender` (unless the wallet address
* is 0x0 or msg.sender).
*/
function setWalletAddress(address walletAddress, uint8 v, bytes32 r, bytes32 s) public {
require(isAccount(msg.sender), "Unknown account");
if (!(walletAddress == msg.sender || walletAddress == address(0x0))) {
address signer = Signatures.getSignerOfAddress(msg.sender, v, r, s);
require(signer == walletAddress, "Invalid signature");
}
Account storage account = accounts[msg.sender];
account.walletAddress = walletAddress;
emit AccountWalletAddressSet(msg.sender, walletAddress);
}
/**
* @notice Setter for the data encryption key and version.
* @param dataEncryptionKey secp256k1 public key for data encryption. Preferably compressed.
*/
function setAccountDataEncryptionKey(bytes memory dataEncryptionKey) public {
require(dataEncryptionKey.length >= 33, "data encryption key length <= 32");
Account storage account = accounts[msg.sender];
account.dataEncryptionKey = dataEncryptionKey;
emit AccountDataEncryptionKeySet(msg.sender, dataEncryptionKey);
}
/**
* @notice Setter for the metadata of an account.
* @param metadataURL The URL to access the metadata.
*/
function setMetadataURL(string calldata metadataURL) external {
require(isAccount(msg.sender), "Unknown account");
Account storage account = accounts[msg.sender];
account.metadataURL = metadataURL;
emit AccountMetadataURLSet(msg.sender, metadataURL);
}
/**
* @notice Set the indexed signer for a specific role
* @param signer the address to set as default
* @param role the role to register a default signer for
*/
function setIndexedSigner(address signer, bytes32 role) public {
require(isAccount(msg.sender), "Not an account");
require(isNotAccount(signer), "Cannot authorize account as signer");
require(
isNotAuthorizedSignerForAnotherAccount(msg.sender, signer),
"Not a signer for this account"
);
require(isSigner(msg.sender, signer, role), "Must authorize signer before setting as default");
Account storage account = accounts[msg.sender];
if (isLegacyRole(role)) {
if (role == VoteSigner) {
account.signers.vote = signer;
} else if (role == AttestationSigner) {
account.signers.attestation = signer;
} else if (role == ValidatorSigner) {
account.signers.validator = signer;
}
emit LegacySignerSet(msg.sender, signer, role);
} else {
defaultSigners[msg.sender][role] = signer;
emit DefaultSignerSet(msg.sender, signer, role);
}
emit IndexedSignerSet(msg.sender, signer, role);
}
/**
* @notice Authorizes an address to act as a signer, for `role`, on behalf of the account.
* @param signer The address of the signing key to authorize.
* @param role The role to authorize signing for.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev v, r, s constitute `signer`'s EIP712 signature over `role`, `msg.sender`
* and `signer`.
*/
function authorizeSignerWithSignature(address signer, bytes32 role, uint8 v, bytes32 r, bytes32 s)
public
{
authorizeAddressWithRole(signer, role, v, r, s);
signerAuthorizations[msg.sender][role][signer] = SignerAuthorization({
started: true,
completed: true
});
emit SignerAuthorized(msg.sender, signer, role);
}
function legacyAuthorizeSignerWithSignature(
address signer,
bytes32 role,
uint8 v,
bytes32 r,
bytes32 s
) private {
authorizeAddress(signer, v, r, s);
signerAuthorizations[msg.sender][role][signer] = SignerAuthorization({
started: true,
completed: true
});
emit SignerAuthorized(msg.sender, signer, role);
}
/**
* @notice Authorizes an address to sign votes on behalf of the account.
* @param signer The address of the signing key to authorize.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev v, r, s constitute `signer`'s signature on `msg.sender`.
*/
function authorizeVoteSigner(address signer, uint8 v, bytes32 r, bytes32 s)
external
nonReentrant
{
legacyAuthorizeSignerWithSignature(signer, VoteSigner, v, r, s);
setIndexedSigner(signer, VoteSigner);
emit VoteSignerAuthorized(msg.sender, signer);
}
/**
* @notice Authorizes an address to sign consensus messages on behalf of the account.
* @param signer The address of the signing key to authorize.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev v, r, s constitute `signer`'s signature on `msg.sender`.
*/
function authorizeValidatorSigner(address signer, uint8 v, bytes32 r, bytes32 s)
external
nonReentrant
{
legacyAuthorizeSignerWithSignature(signer, ValidatorSigner, v, r, s);
setIndexedSigner(signer, ValidatorSigner);
require(!getValidators().isValidator(msg.sender), "Cannot authorize validator signer");
emit ValidatorSignerAuthorized(msg.sender, signer);
}
/**
* @notice Authorizes an address to sign consensus messages on behalf of the account.
* @param signer The address of the signing key to authorize.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @param ecdsaPublicKey The ECDSA public key corresponding to `signer`.
* @dev v, r, s constitute `signer`'s signature on `msg.sender`.
*/
function authorizeValidatorSignerWithPublicKey(
address signer,
uint8 v,
bytes32 r,
bytes32 s,
bytes calldata ecdsaPublicKey
) external nonReentrant {
legacyAuthorizeSignerWithSignature(signer, ValidatorSigner, v, r, s);
setIndexedSigner(signer, ValidatorSigner);
require(
getValidators().updateEcdsaPublicKey(msg.sender, signer, ecdsaPublicKey),
"Failed to update ECDSA public key"
);
emit ValidatorSignerAuthorized(msg.sender, signer);
}
/**
* @notice Authorizes an address to sign consensus messages on behalf of the account.
* @param signer The address of the signing key to authorize.
* @param ecdsaPublicKey The ECDSA public key corresponding to `signer`.
* @param blsPublicKey The BLS public key that the validator is using for consensus, should pass
* proof of possession. 96 bytes.
* @param blsPop The BLS public key proof-of-possession, which consists of a signature on the
* account address. 48 bytes.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev v, r, s constitute `signer`'s signature on `msg.sender`.
*/
function authorizeValidatorSignerWithKeys(
address signer,
uint8 v,
bytes32 r,
bytes32 s,
bytes calldata ecdsaPublicKey,
bytes calldata blsPublicKey,
bytes calldata blsPop
) external nonReentrant {
legacyAuthorizeSignerWithSignature(signer, ValidatorSigner, v, r, s);
setIndexedSigner(signer, ValidatorSigner);
require(
getValidators().updatePublicKeys(msg.sender, signer, ecdsaPublicKey, blsPublicKey, blsPop),
"Failed to update validator keys"
);
emit ValidatorSignerAuthorized(msg.sender, signer);
}
/**
* @notice Authorizes an address to sign attestations on behalf of the account.
* @param signer The address of the signing key to authorize.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev v, r, s constitute `signer`'s signature on `msg.sender`.
*/
function authorizeAttestationSigner(address signer, uint8 v, bytes32 r, bytes32 s) public {
legacyAuthorizeSignerWithSignature(signer, AttestationSigner, v, r, s);
setIndexedSigner(signer, AttestationSigner);
emit AttestationSignerAuthorized(msg.sender, signer);
}
/**
* @notice Begin the process of authorizing an address to sign on behalf of the account
* @param signer The address of the signing key to authorize.
* @param role The role to authorize signing for.
*/
function authorizeSigner(address signer, bytes32 role) public {
require(isAccount(msg.sender), "Unknown account");
require(
isNotAccount(signer) && isNotAuthorizedSignerForAnotherAccount(msg.sender, signer),
"Cannot re-authorize address signer"
);
signerAuthorizations[msg.sender][role][signer] = SignerAuthorization({
started: true,
completed: false
});
emit SignerAuthorizationStarted(msg.sender, signer, role);
}
/**
* @notice Finish the process of authorizing an address to sign on behalf of the account.
* @param account The address of account that authorized signing.
* @param role The role to finish authorizing for.
*/
function completeSignerAuthorization(address account, bytes32 role) public {
require(isAccount(account), "Unknown account");
require(
isNotAccount(msg.sender) && isNotAuthorizedSignerForAnotherAccount(account, msg.sender),
"Cannot re-authorize address signer"
);
require(
signerAuthorizations[account][role][msg.sender].started == true,
"Signer authorization not started"
);
authorizedBy[msg.sender] = account;
signerAuthorizations[account][role][msg.sender].completed = true;
emit SignerAuthorizationCompleted(account, msg.sender, role);
}
/**
* @notice Whether or not the signer has been registered as the legacy signer for role
* @param _account The address of account that authorized signing.
* @param signer The address of the signer.
* @param role The role that has been authorized.
*/
function isLegacySigner(address _account, address signer, bytes32 role)
public
view
returns (bool)
{
Account storage account = accounts[_account];
if (role == ValidatorSigner && account.signers.validator == signer) {
return true;
} else if (role == AttestationSigner && account.signers.attestation == signer) {
return true;
} else if (role == VoteSigner && account.signers.vote == signer) {
return true;
} else {
return false;
}
}
/**
* @notice Whether or not the signer has been registered as the default signer for role
* @param account The address of account that authorized signing.
* @param signer The address of the signer.
* @param role The role that has been authorized.
*/
function isDefaultSigner(address account, address signer, bytes32 role)
public
view
returns (bool)
{
return defaultSigners[account][role] == signer;
}
/**
* @notice Whether or not the signer has been registered as an indexed signer for role
* @param account The address of account that authorized signing.
* @param signer The address of the signer.
* @param role The role that has been authorized.
*/
function isIndexedSigner(address account, address signer, bytes32 role)
public
view
returns (bool)
{
return
isLegacyRole(role)
? isLegacySigner(account, signer, role)
: isDefaultSigner(account, signer, role);
}
/**
* @notice Whether or not the signer has been registered as a signer for role
* @param account The address of account that authorized signing.
* @param signer The address of the signer.
* @param role The role that has been authorized.
*/
function isSigner(address account, address signer, bytes32 role) public view returns (bool) {
return
isLegacySigner(account, signer, role) ||
(signerAuthorizations[account][role][signer].completed && authorizedBy[signer] == account);
}
/**
* @notice Removes the signer for a default role.
* @param role The role that has been authorized.
*/
function removeDefaultSigner(bytes32 role) public {
address signer = defaultSigners[msg.sender][role];
defaultSigners[msg.sender][role] = address(0);
emit DefaultSignerRemoved(msg.sender, signer, role);
}
/**
* @notice Remove one of the Validator, Attestation or
* Vote signers from an account. Should only be called from
* methods that check the role is a legacy signer.
* @param role The role that has been authorized.
*/
function removeLegacySigner(bytes32 role) private {
Account storage account = accounts[msg.sender];
address signer;
if (role == ValidatorSigner) {
signer = account.signers.validator;
account.signers.validator = address(0);
} else if (role == AttestationSigner) {
signer = account.signers.attestation;
account.signers.attestation = address(0);
} else if (role == VoteSigner) {
signer = account.signers.vote;
account.signers.vote = address(0);
}
emit LegacySignerRemoved(msg.sender, signer, role);
}
/**
* @notice Removes the currently authorized and indexed signer
* for a specific role
* @param role The role of the signer.
*/
function removeIndexedSigner(bytes32 role) public {
address oldSigner = getIndexedSigner(msg.sender, role);
isLegacyRole(role) ? removeLegacySigner(role) : removeDefaultSigner(role);
emit IndexedSignerRemoved(msg.sender, oldSigner, role);
}
/**
* @notice Removes the currently authorized signer for a specific role and
* if the signer is indexed, remove that as well.
* @param signer The address of the signer.
* @param role The role that has been authorized.
*/
function removeSigner(address signer, bytes32 role) public {
if (isIndexedSigner(msg.sender, signer, role)) {
removeIndexedSigner(role);
}
delete signerAuthorizations[msg.sender][role][signer];
emit SignerRemoved(msg.sender, signer, role);
}
/**
* @notice Removes the currently authorized vote signer for the account.
* Note that the signers cannot be reauthorized after they have been removed.
*/
function removeVoteSigner() public {
address signer = getLegacySigner(msg.sender, VoteSigner);
removeSigner(signer, VoteSigner);
emit VoteSignerRemoved(msg.sender, signer);
}
/**
* @notice Removes the currently authorized validator signer for the account
* Note that the signers cannot be reauthorized after they have been removed.
*/
function removeValidatorSigner() public {
address signer = getLegacySigner(msg.sender, ValidatorSigner);
removeSigner(signer, ValidatorSigner);
emit ValidatorSignerRemoved(msg.sender, signer);
}
/**
* @notice Removes the currently authorized attestation signer for the account
* Note that the signers cannot be reauthorized after they have been removed.
*/
function removeAttestationSigner() public {
address signer = getLegacySigner(msg.sender, AttestationSigner);
removeSigner(signer, AttestationSigner);
emit AttestationSignerRemoved(msg.sender, signer);
}
function signerToAccountWithRole(address signer, bytes32 role) internal view returns (address) {
address account = authorizedBy[signer];
if (account != address(0)) {
require(isSigner(account, signer, role), "not active authorized signer for role");
return account;
}
require(isAccount(signer), "not an account");
return signer;
}
/**
* @notice Returns the account associated with `signer`.
* @param signer The address of the account or currently authorized attestation signer.
* @dev Fails if the `signer` is not an account or currently authorized attestation signer.
* @return The associated account.
*/
function attestationSignerToAccount(address signer) external view returns (address) {
return signerToAccountWithRole(signer, AttestationSigner);
}
/**
* @notice Returns the account associated with `signer`.
* @param signer The address of an account or currently authorized validator signer.
* @dev Fails if the `signer` is not an account or currently authorized validator.
* @return The associated account.
*/
function validatorSignerToAccount(address signer) public view returns (address) {
return signerToAccountWithRole(signer, ValidatorSigner);
}
/**
* @notice Returns the account associated with `signer`.
* @param signer The address of the account or currently authorized vote signer.
* @dev Fails if the `signer` is not an account or currently authorized vote signer.
* @return The associated account.
*/
function voteSignerToAccount(address signer) external view returns (address) {
return signerToAccountWithRole(signer, VoteSigner);
}
/**
* @notice Returns the account associated with `signer`.
* @param signer The address of the account or previously authorized signer.
* @dev Fails if the `signer` is not an account or previously authorized signer.
* @return The associated account.
*/
function signerToAccount(address signer) external view returns (address) {
address authorizingAccount = authorizedBy[signer];
if (authorizingAccount != address(0)) {
return authorizingAccount;
} else {
require(isAccount(signer), "Not an account");
return signer;
}
}
/**
* @notice Checks whether the role is one of Vote, Validator or Attestation
* @param role The role to check
*/
function isLegacyRole(bytes32 role) public pure returns (bool) {
return role == VoteSigner || role == ValidatorSigner || role == AttestationSigner;
}
/**
* @notice Returns the legacy signer for the specified account and
* role. If no signer has been specified it will return the account itself.
* @param _account The address of the account.
* @param role The role of the signer.
*/
function getLegacySigner(address _account, bytes32 role) public view returns (address) {
require(isLegacyRole(role), "Role is not a legacy signer");
Account storage account = accounts[_account];
address signer;
if (role == ValidatorSigner) {
signer = account.signers.validator;
} else if (role == AttestationSigner) {
signer = account.signers.attestation;
} else if (role == VoteSigner) {
signer = account.signers.vote;
}
return signer == address(0) ? _account : signer;
}
/**
* @notice Returns the default signer for the specified account and
* role. If no signer has been specified it will return the account itself.
* @param account The address of the account.
* @param role The role of the signer.
*/
function getDefaultSigner(address account, bytes32 role) public view returns (address) {
address defaultSigner = defaultSigners[account][role];
return defaultSigner == address(0) ? account : defaultSigner;
}
/**
* @notice Returns the indexed signer for the specified account and role.
* If no signer has been specified it will return the account itself.
* @param account The address of the account.
* @param role The role of the signer.
*/
function getIndexedSigner(address account, bytes32 role) public view returns (address) {
return isLegacyRole(role) ? getLegacySigner(account, role) : getDefaultSigner(account, role);
}
/**
* @notice Returns the vote signer for the specified account.
* @param account The address of the account.
* @return The address with which the account can sign votes.
*/
function getVoteSigner(address account) public view returns (address) {
return getLegacySigner(account, VoteSigner);
}
/**
* @notice Returns the validator signer for the specified account.
* @param account The address of the account.
* @return The address with which the account can register a validator or group.
*/
function getValidatorSigner(address account) public view returns (address) {
return getLegacySigner(account, ValidatorSigner);
}
/**
* @notice Returns the attestation signer for the specified account.
* @param account The address of the account.
* @return The address with which the account can sign attestations.
*/
function getAttestationSigner(address account) public view returns (address) {
return getLegacySigner(account, AttestationSigner);
}
/**
* @notice Checks whether or not the account has an indexed signer
* registered for one of the legacy roles
*/
function hasLegacySigner(address account, bytes32 role) public view returns (bool) {
return getLegacySigner(account, role) != account;
}
/**
* @notice Checks whether or not the account has an indexed signer
* registered for a role
*/
function hasDefaultSigner(address account, bytes32 role) public view returns (bool) {
return getDefaultSigner(account, role) != account;
}
/**
* @notice Checks whether or not the account has an indexed signer
* registered for the role
*/
function hasIndexedSigner(address account, bytes32 role) public view returns (bool) {
return isLegacyRole(role) ? hasLegacySigner(account, role) : hasDefaultSigner(account, role);
}
/**
* @notice Checks whether or not the account has a signer
* registered for the plaintext role.
* @dev See `hasIndexedSigner` for more gas efficient call.
*/
function hasAuthorizedSigner(address account, string calldata role) external view returns (bool) {
return hasIndexedSigner(account, keccak256(abi.encodePacked(role)));
}
/**
* @notice Returns if account has specified a dedicated vote signer.
* @param account The address of the account.
* @return Whether the account has specified a dedicated vote signer.
*/
function hasAuthorizedVoteSigner(address account) external view returns (bool) {
return hasLegacySigner(account, VoteSigner);
}
/**
* @notice Returns if account has specified a dedicated validator signer.
* @param account The address of the account.
* @return Whether the account has specified a dedicated validator signer.
*/
function hasAuthorizedValidatorSigner(address account) external view returns (bool) {
return hasLegacySigner(account, ValidatorSigner);
}
/**
* @notice Returns if account has specified a dedicated attestation signer.
* @param account The address of the account.
* @return Whether the account has specified a dedicated attestation signer.
*/
function hasAuthorizedAttestationSigner(address account) external view returns (bool) {
return hasLegacySigner(account, AttestationSigner);
}
/**
* @notice Getter for the name of an account.
* @param account The address of the account to get the name for.
* @return name The name of the account.
*/
function getName(address account) external view returns (string memory) {
return accounts[account].name;
}
/**
* @notice Getter for the metadata of an account.
* @param account The address of the account to get the metadata for.
* @return metadataURL The URL to access the metadata.
*/
function getMetadataURL(address account) external view returns (string memory) {
return accounts[account].metadataURL;
}
/**
* @notice Getter for the metadata of multiple accounts.
* @param accountsToQuery The addresses of the accounts to get the metadata for.
* @return (stringLengths[] - the length of each string in bytes
* data - all strings concatenated
* )
*/
function batchGetMetadataURL(address[] calldata accountsToQuery)
external
view
returns (uint256[] memory, bytes memory)
{
uint256 totalSize = 0;
uint256[] memory sizes = new uint256[](accountsToQuery.length);
for (uint256 i = 0; i < accountsToQuery.length; i = i.add(1)) {
sizes[i] = bytes(accounts[accountsToQuery[i]].metadataURL).length;
totalSize = totalSize.add(sizes[i]);
}
bytes memory data = new bytes(totalSize);
uint256 pointer = 0;
for (uint256 i = 0; i < accountsToQuery.length; i = i.add(1)) {
for (uint256 j = 0; j < sizes[i]; j = j.add(1)) {
data[pointer] = bytes(accounts[accountsToQuery[i]].metadataURL)[j];
pointer = pointer.add(1);
}
}
return (sizes, data);
}
/**
* @notice Getter for the data encryption key and version.
* @param account The address of the account to get the key for
* @return dataEncryptionKey secp256k1 public key for data encryption. Preferably compressed.
*/
function getDataEncryptionKey(address account) external view returns (bytes memory) {
return accounts[account].dataEncryptionKey;
}
/**
* @notice Getter for the wallet address for an account
* @param account The address of the account to get the wallet address for
* @return Wallet address
*/
function getWalletAddress(address account) external view returns (address) {
return accounts[account].walletAddress;
}
/**
* @notice Check if an account already exists.
* @param account The address of the account
* @return Returns `true` if account exists. Returns `false` otherwise.
*/
function isAccount(address account) public view returns (bool) {
return (accounts[account].exists);
}
/**
* @notice Check if an account already exists.
* @param account The address of the account
* @return Returns `false` if account exists. Returns `true` otherwise.
*/
function isNotAccount(address account) internal view returns (bool) {
return (!accounts[account].exists);
}
/**
* @notice Check if an address has been an authorized signer for an account.
* @param signer The possibly authorized address.
* @return Returns `true` if authorized. Returns `false` otherwise.
*/
function isAuthorizedSigner(address signer) external view returns (bool) {
return (authorizedBy[signer] != address(0));
}
/**
* @notice Check if an address has not been an authorized signer for an account.
* @param signer The possibly authorized address.
* @return Returns `false` if authorized. Returns `true` otherwise.
*/
function isNotAuthorizedSigner(address signer) internal view returns (bool) {
return (authorizedBy[signer] == address(0));
}
/**
* @notice Check if `signer` has not been authorized, and if it has been previously
* authorized that it was authorized by `account`.
* @param account The authorizing account address.
* @param signer The possibly authorized address.
* @return Returns `false` if authorized. Returns `true` otherwise.
*/
function isNotAuthorizedSignerForAnotherAccount(address account, address signer)
internal
view
returns (bool)
{
return (authorizedBy[signer] == address(0) || authorizedBy[signer] == account);
}
/**
* @notice Authorizes some role of `msg.sender`'s account to another address.
* @param authorized The address to authorize.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev Fails if the address is already authorized to another account or is an account itself.
* @dev Note that once an address is authorized, it may never be authorized again.
* @dev v, r, s constitute `authorized`'s signature on `msg.sender`.
*/
function authorizeAddress(address authorized, uint8 v, bytes32 r, bytes32 s) private {
address signer = Signatures.getSignerOfAddress(msg.sender, v, r, s);
require(signer == authorized, "Invalid signature");
authorize(authorized);
}
/**
* @notice Returns the address that signed the provided role authorization.
* @param account The `account` property signed over in the EIP712 signature
* @param signer The `signer` property signed over in the EIP712 signature
* @param role The `role` property signed over in the EIP712 signature
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @return The address that signed the provided role authorization.
*/
function getRoleAuthorizationSigner(
address account,
address signer,
bytes32 role,
uint8 v,
bytes32 r,
bytes32 s
) public view returns (address) {
bytes32 structHash = keccak256(
abi.encode(EIP712_AUTHORIZE_SIGNER_TYPEHASH, account, signer, role)
);
return Signatures.getSignerOfTypedDataHash(eip712DomainSeparator, structHash, v, r, s);
}
/**
* @notice Authorizes a role of `msg.sender`'s account to another address (`authorized`).
* @param authorized The address to authorize.
* @param role The role to authorize.
* @param v The recovery id of the incoming ECDSA signature.
* @param r Output value r of the ECDSA signature.
* @param s Output value s of the ECDSA signature.
* @dev Fails if the address is already authorized to another account or is an account itself.
* @dev Note that this signature is EIP712 compliant over the authorizing `account`
* (`msg.sender`), `signer` (`authorized`) and `role`.
*/
function authorizeAddressWithRole(address authorized, bytes32 role, uint8 v, bytes32 r, bytes32 s)
private
{
address signer = getRoleAuthorizationSigner(msg.sender, authorized, role, v, r, s);
require(signer == authorized, "Invalid signature");
authorize(authorized);
}
/**
* @notice Authorizes an address to `msg.sender`'s account
* @param authorized The address to authorize.
* @dev Fails if the address is already authorized for another account or is an account itself.
*/
function authorize(address authorized) private {
require(isAccount(msg.sender), "Unknown account");
require(
isNotAccount(authorized) && isNotAuthorizedSignerForAnotherAccount(msg.sender, authorized),
"Cannot re-authorize address or locked gold account for another account"
);
authorizedBy[authorized] = msg.sender;
}
}
|
Returns if account has specified a dedicated vote signer. account The address of the account. return Whether the account has specified a dedicated vote signer./
|
function hasAuthorizedVoteSigner(address account) external view returns (bool) {
return hasLegacySigner(account, VoteSigner);
}
| 1,012,319
|
/* Copyright (C) 2021 Soteria.fund
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.17;
import "../../abstract/Iupgradable.sol";
import "../../libraries/SafeMath.sol";
import "../capital/MCR.sol";
import "../governance/MemberRoles.sol";
import "../capital/PoolData.sol";
contract TokenFunctions is Iupgradable {
using SafeMath for uint;
MCR internal m1;
MemberRoles internal mr;
SOTEToken public tk;
TokenController internal tc;
TokenData internal td;
QuotationData internal qd;
ClaimsReward internal cr;
Governance internal gv;
PoolData internal pd;
IPooledStaking pooledStaking;
event BurnCATokens(uint claimId, address addr, uint amount);
/**
* @dev Rewards stakers on purchase of cover on smart contract.
* @param _contractAddress smart contract address.
* @param _coverPriceSOTE cover price in SOTE.
*/
function pushStakerRewards(address _contractAddress, uint _coverPriceSOTE) external onlyInternal {
uint rewardValue = _coverPriceSOTE.mul(td.stakerCommissionPer()).div(100);
pooledStaking.accumulateReward(_contractAddress, rewardValue);
}
/**
* @dev Deprecated in favor of burnStakedTokens
*/
function burnStakerLockedToken(uint, bytes4, uint) external {
// noop
}
/**
* @dev Burns tokens staked on smart contract covered by coverId. Called when a payout is succesfully executed.
* @param coverId cover id
* @param coverCurrency cover currency
* @param sumAssured amount of $curr to burn
*/
function burnStakedTokens(uint coverId, bytes4 coverCurrency, uint sumAssured) external onlyInternal {
(, address scAddress) = qd.getscAddressOfCover(coverId);
uint tokenPrice = m1.calculateTokenPrice(coverCurrency);
uint burnSOTEAmount = sumAssured.mul(1e18).div(tokenPrice);
pooledStaking.pushBurn(scAddress, burnSOTEAmount);
}
/**
* @dev Gets the total staked SOTE tokens against
* Smart contract by all stakers
* @param _stakedContractAddress smart contract address.
* @return amount total staked SOTE tokens.
*/
function deprecated_getTotalStakedTokensOnSmartContract(
address _stakedContractAddress
)
external
view
returns(uint)
{
uint stakedAmount = 0;
address stakerAddress;
uint staketLen = td.getStakedContractStakersLength(_stakedContractAddress);
for (uint i = 0; i < staketLen; i++) {
stakerAddress = td.getStakedContractStakerByIndex(_stakedContractAddress, i);
uint stakerIndex = td.getStakedContractStakerIndex(
_stakedContractAddress, i);
uint currentlyStaked;
(, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(stakerAddress,
_stakedContractAddress, stakerIndex);
stakedAmount = stakedAmount.add(currentlyStaked);
}
return stakedAmount;
}
/**
* @dev Returns amount of SOTE Tokens locked as Cover Note for given coverId.
* @param _of address of the coverHolder.
* @param _coverId coverId of the cover.
*/
function getUserLockedCNTokens(address _of, uint _coverId) external view returns(uint) {
return _getUserLockedCNTokens(_of, _coverId);
}
/**
* @dev to get the all the cover locked tokens of a user
* @param _of is the user address in concern
* @return amount locked
*/
function getUserAllLockedCNTokens(address _of) external view returns(uint amount) {
for (uint i = 0; i < qd.getUserCoverLength(_of); i++) {
amount = amount.add(_getUserLockedCNTokens(_of, qd.getAllCoversOfUser(_of)[i]));
}
}
/**
* @dev Returns amount of SOTE Tokens locked as Cover Note against given coverId.
* @param _coverId coverId of the cover.
*/
function getLockedCNAgainstCover(uint _coverId) external view returns(uint) {
return _getLockedCNAgainstCover(_coverId);
}
/**
* @dev Returns total amount of staked SOTE Tokens on all smart contracts.
* @param _stakerAddress address of the Staker.
*/
function deprecated_getStakerAllLockedTokens(address _stakerAddress) external view returns (uint amount) {
uint stakedAmount = 0;
address scAddress;
uint scIndex;
for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) {
scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i);
scIndex = td.getStakerStakedContractIndex(_stakerAddress, i);
uint currentlyStaked;
(, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress, scAddress, i);
stakedAmount = stakedAmount.add(currentlyStaked);
}
amount = stakedAmount;
}
/**
* @dev Returns total unlockable amount of staked SOTE Tokens on all smart contract .
* @param _stakerAddress address of the Staker.
*/
function deprecated_getStakerAllUnlockableStakedTokens(
address _stakerAddress
)
external
view
returns (uint amount)
{
uint unlockableAmount = 0;
address scAddress;
uint scIndex;
for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) {
scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i);
scIndex = td.getStakerStakedContractIndex(_stakerAddress, i);
unlockableAmount = unlockableAmount.add(
_deprecated_getStakerUnlockableTokensOnSmartContract(_stakerAddress, scAddress,
scIndex));
}
amount = unlockableAmount;
}
/**
* @dev Change Dependent Contract Address
*/
function changeDependentContractAddress() public {
tk = SOTEToken(ms.tokenAddress());
td = TokenData(ms.getLatestAddress("TD"));
tc = TokenController(ms.getLatestAddress("TC"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
qd = QuotationData(ms.getLatestAddress("QD"));
m1 = MCR(ms.getLatestAddress("MC"));
gv = Governance(ms.getLatestAddress("GV"));
mr = MemberRoles(ms.getLatestAddress("MR"));
pd = PoolData(ms.getLatestAddress("PD"));
pooledStaking = IPooledStaking(ms.getLatestAddress("PS"));
}
/**
* @dev Gets the Token price in a given currency
* @param curr Currency name.
* @return price Token Price.
*/
function getTokenPrice(bytes4 curr) public view returns(uint price) {
price = m1.calculateTokenPrice(curr);
}
/**
* @dev Set the flag to check if cover note is deposited against the cover id
* @param coverId Cover Id.
*/
function depositCN(uint coverId) public onlyInternal returns (bool success) {
require(_getLockedCNAgainstCover(coverId) > 0, "No cover note available");
td.setDepositCN(coverId, true);
success = true;
}
/**
* @param _of address of Member
* @param _coverId Cover Id
* @param _lockTime Pending Time + Cover Period 7*1 days
*/
function extendCNEPOff(address _of, uint _coverId, uint _lockTime) public onlyInternal {
uint timeStamp = now.add(_lockTime);
uint coverValidUntil = qd.getValidityOfCover(_coverId);
if (timeStamp >= coverValidUntil) {
bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId));
tc.extendLockOf(_of, reason, timeStamp);
}
}
/**
* @dev to burn the deposited cover tokens
* @param coverId is id of cover whose tokens have to be burned
* @return the status of the successful burning
*/
function burnDepositCN(uint coverId) public onlyInternal returns (bool success) {
address _of = qd.getCoverMemberAddress(coverId);
uint amount;
(amount, ) = td.depositedCN(coverId);
amount = (amount.mul(50)).div(100);
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId));
tc.burnLockedTokens(_of, reason, amount);
success = true;
}
/**
* @dev Unlocks covernote locked against a given cover
* @param coverId id of cover
*/
function unlockCN(uint coverId) public onlyInternal {
(, bool isDeposited) = td.depositedCN(coverId);
require(!isDeposited,"Cover note is deposited and can not be released");
uint lockedCN = _getLockedCNAgainstCover(coverId);
if (lockedCN != 0) {
address coverHolder = qd.getCoverMemberAddress(coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, coverId));
tc.releaseLockedTokens(coverHolder, reason, lockedCN);
}
}
/**
* @dev Burns tokens used for fraudulent voting against a claim
* @param claimid Claim Id.
* @param _value number of tokens to be burned
* @param _of Claim Assessor's address.
*/
function burnCAToken(uint claimid, uint _value, address _of) public {
require(ms.checkIsAuthToGoverned(msg.sender));
tc.burnLockedTokens(_of, "CLA", _value);
emit BurnCATokens(claimid, _of, _value);
}
/**
* @dev to lock cover note tokens
* @param coverNoteAmount is number of tokens to be locked
* @param coverPeriod is cover period in concern
* @param coverId is the cover id of cover in concern
* @param _of address whose tokens are to be locked
*/
function lockCN(
uint coverNoteAmount,
uint coverPeriod,
uint coverId,
address _of
)
public
onlyInternal
{
uint validity = (coverPeriod * 1 days).add(td.lockTokenTimeAfterCoverExp());
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId));
td.setDepositCNAmount(coverId, coverNoteAmount);
tc.lockOf(_of, reason, coverNoteAmount, validity);
}
/**
* @dev to check if a member is locked for member vote
* @param _of is the member address in concern
* @return the boolean status
*/
function isLockedForMemberVote(address _of) public view returns(bool) {
return now < tk.isLockedForMV(_of);
}
/**
* @dev Internal function to gets amount of locked SOTE tokens,
* staked against smartcontract by index
* @param _stakerAddress address of user
* @param _stakedContractAddress staked contract address
* @param _stakedContractIndex index of staking
*/
function deprecated_getStakerLockedTokensOnSmartContract (
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns
(uint amount)
{
amount = _deprecated_getStakerLockedTokensOnSmartContract(_stakerAddress,
_stakedContractAddress, _stakedContractIndex);
}
/**
* @dev Function to gets unlockable amount of locked SOTE
* tokens, staked against smartcontract by index
* @param stakerAddress address of staker
* @param stakedContractAddress staked contract address
* @param stakerIndex index of staking
*/
function deprecated_getStakerUnlockableTokensOnSmartContract (
address stakerAddress,
address stakedContractAddress,
uint stakerIndex
)
public
view
returns (uint)
{
return _deprecated_getStakerUnlockableTokensOnSmartContract(stakerAddress, stakedContractAddress,
td.getStakerStakedContractIndex(stakerAddress, stakerIndex));
}
/**
* @dev releases unlockable staked tokens to staker
*/
function deprecated_unlockStakerUnlockableTokens(address _stakerAddress) public checkPause {
uint unlockableAmount;
address scAddress;
bytes32 reason;
uint scIndex;
for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) {
scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i);
scIndex = td.getStakerStakedContractIndex(_stakerAddress, i);
unlockableAmount = _deprecated_getStakerUnlockableTokensOnSmartContract(
_stakerAddress, scAddress,
scIndex);
td.setUnlockableBeforeLastBurnTokens(_stakerAddress, i, 0);
td.pushUnlockedStakedTokens(_stakerAddress, i, unlockableAmount);
reason = keccak256(abi.encodePacked("UW", _stakerAddress, scAddress, scIndex));
tc.releaseLockedTokens(_stakerAddress, reason, unlockableAmount);
}
}
/**
* @dev to get tokens of staker locked before burning that are allowed to burn
* @param stakerAdd is the address of the staker
* @param stakedAdd is the address of staked contract in concern
* @param stakerIndex is the staker index in concern
* @return amount of unlockable tokens
* @return amount of tokens that can burn
*/
function _deprecated_unlockableBeforeBurningAndCanBurn(
address stakerAdd,
address stakedAdd,
uint stakerIndex
)
public
view
returns
(uint amount, uint canBurn) {
uint dateAdd;
uint initialStake;
uint totalBurnt;
uint ub;
(, , dateAdd, initialStake, , totalBurnt, ub) = td.stakerStakedContracts(stakerAdd, stakerIndex);
canBurn = _deprecated_calculateStakedTokens(initialStake, now.sub(dateAdd).div(1 days), td.scValidDays());
// Can't use SafeMaths for int.
int v = int(initialStake - (canBurn) - (totalBurnt) - (
td.getStakerUnlockedStakedTokens(stakerAdd, stakerIndex)) - (ub));
uint currentLockedTokens = _deprecated_getStakerLockedTokensOnSmartContract(
stakerAdd, stakedAdd, td.getStakerStakedContractIndex(stakerAdd, stakerIndex));
if (v < 0) {
v = 0;
}
amount = uint(v);
if (canBurn > currentLockedTokens.sub(amount).sub(ub)) {
canBurn = currentLockedTokens.sub(amount).sub(ub);
}
}
/**
* @dev to get tokens of staker that are unlockable
* @param _stakerAddress is the address of the staker
* @param _stakedContractAddress is the address of staked contract in concern
* @param _stakedContractIndex is the staked contract index in concern
* @return amount of unlockable tokens
*/
function _deprecated_getStakerUnlockableTokensOnSmartContract (
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns
(uint amount)
{
uint initialStake;
uint stakerIndex = td.getStakedContractStakerIndex(
_stakedContractAddress, _stakedContractIndex);
uint burnt;
(, , , initialStake, , burnt,) = td.stakerStakedContracts(_stakerAddress, stakerIndex);
uint alreadyUnlocked = td.getStakerUnlockedStakedTokens(_stakerAddress, stakerIndex);
uint currentStakedTokens;
(, currentStakedTokens) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress,
_stakedContractAddress, stakerIndex);
amount = initialStake.sub(currentStakedTokens).sub(alreadyUnlocked).sub(burnt);
}
/**
* @dev Internal function to get the amount of locked SOTE tokens,
* staked against smartcontract by index
* @param _stakerAddress address of user
* @param _stakedContractAddress staked contract address
* @param _stakedContractIndex index of staking
*/
function _deprecated_getStakerLockedTokensOnSmartContract (
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex
)
internal
view
returns
(uint amount)
{
bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress,
_stakedContractAddress, _stakedContractIndex));
amount = tc.tokensLocked(_stakerAddress, reason);
}
/**
* @dev Returns amount of SOTE Tokens locked as Cover Note for given coverId.
* @param _coverId coverId of the cover.
*/
function _getLockedCNAgainstCover(uint _coverId) internal view returns(uint) {
address coverHolder = qd.getCoverMemberAddress(_coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, _coverId));
return tc.tokensLockedAtTime(coverHolder, reason, now);
}
/**
* @dev Returns amount of SOTE Tokens locked as Cover Note for given coverId.
* @param _of address of the coverHolder.
* @param _coverId coverId of the cover.
*/
function _getUserLockedCNTokens(address _of, uint _coverId) internal view returns(uint) {
bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId));
return tc.tokensLockedAtTime(_of, reason, now);
}
/**
* @dev Internal function to gets remaining amount of staked SOTE tokens,
* against smartcontract by index
* @param _stakeAmount address of user
* @param _stakeDays staked contract address
* @param _validDays index of staking
*/
function _deprecated_calculateStakedTokens(
uint _stakeAmount,
uint _stakeDays,
uint _validDays
)
internal
pure
returns (uint amount)
{
if (_validDays > _stakeDays) {
uint rf = ((_validDays.sub(_stakeDays)).mul(100000)).div(_validDays);
amount = (rf.mul(_stakeAmount)).div(100000);
} else {
amount = 0;
}
}
/**
* @dev Gets the total staked SOTE tokens against Smart contract
* by all stakers
* @param _stakedContractAddress smart contract address.
* @return amount total staked SOTE tokens.
*/
function _deprecated_burnStakerTokenLockedAgainstSmartContract(
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex,
uint _amount
)
internal
{
uint stakerIndex = td.getStakedContractStakerIndex(
_stakedContractAddress, _stakedContractIndex);
td.pushBurnedTokens(_stakerAddress, stakerIndex, _amount);
bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress,
_stakedContractAddress, _stakedContractIndex));
tc.burnLockedTokens(_stakerAddress, reason, _amount);
}
}
|
to get the all the cover locked tokens of a user _of is the user address in concern return amount locked/
|
function getUserAllLockedCNTokens(address _of) external view returns(uint amount) {
for (uint i = 0; i < qd.getUserCoverLength(_of); i++) {
amount = amount.add(_getUserLockedCNTokens(_of, qd.getAllCoversOfUser(_of)[i]));
}
}
| 7,238,576
|
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
import {SafeERC20} from '@aave/aave-stake/contracts/lib/SafeERC20.sol';
import {SafeMath} from '../lib/SafeMath.sol';
import {DistributionTypes} from '../lib/DistributionTypes.sol';
import {VersionedInitializable} from '@aave/aave-stake/contracts/utils/VersionedInitializable.sol';
import {DistributionManager} from './DistributionManager.sol';
import {IStakedTokenWithConfig} from '../interfaces/IStakedTokenWithConfig.sol';
import {IERC20} from '@aave/aave-stake/contracts/interfaces/IERC20.sol';
import {IScaledBalanceToken} from '../interfaces/IScaledBalanceToken.sol';
import {IAaveIncentivesController} from '../interfaces/IAaveIncentivesController.sol';
/**
* @title StakedTokenIncentivesController
* @notice Distributor contract for rewards to the Aave protocol, using a staked token as rewards asset.
* The contract stakes the rewards before redistributing them to the Aave protocol participants.
* The reference staked token implementation is at https://github.com/aave/aave-stake-v2
* @author Aave
**/
contract StakedTokenIncentivesController is
IAaveIncentivesController,
VersionedInitializable,
DistributionManager
{
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 public constant REVISION = 1;
IStakedTokenWithConfig public immutable STAKE_TOKEN;
mapping(address => uint256) internal _usersUnclaimedRewards;
// this mapping allows whitelisted addresses to claim on behalf of others
// useful for contracts that hold tokens to be rewarded but don't have any native logic to claim Liquidity Mining rewards
mapping(address => address) internal _authorizedClaimers;
modifier onlyAuthorizedClaimers(address claimer, address user) {
require(_authorizedClaimers[user] == claimer, 'CLAIMER_UNAUTHORIZED');
_;
}
constructor(IStakedTokenWithConfig stakeToken, address emissionManager)
DistributionManager(emissionManager)
{
STAKE_TOKEN = stakeToken;
}
/**
* @dev Initialize IStakedTokenIncentivesController
* @param addressesProvider the address of the corresponding addresses provider
**/
function initialize(address addressesProvider) external initializer {
//approves the safety module to allow staking
IERC20(STAKE_TOKEN.STAKED_TOKEN()).safeApprove(address(STAKE_TOKEN), type(uint256).max);
}
/// @inheritdoc IAaveIncentivesController
function configureAssets(address[] calldata assets, uint256[] calldata emissionsPerSecond)
external
override
onlyEmissionManager
{
require(assets.length == emissionsPerSecond.length, 'INVALID_CONFIGURATION');
DistributionTypes.AssetConfigInput[] memory assetsConfig =
new DistributionTypes.AssetConfigInput[](assets.length);
for (uint256 i = 0; i < assets.length; i++) {
assetsConfig[i].underlyingAsset = assets[i];
assetsConfig[i].emissionPerSecond = uint104(emissionsPerSecond[i]);
require(assetsConfig[i].emissionPerSecond == emissionsPerSecond[i], 'INVALID_CONFIGURATION');
assetsConfig[i].totalStaked = IScaledBalanceToken(assets[i]).scaledTotalSupply();
}
_configureAssets(assetsConfig);
}
/// @inheritdoc IAaveIncentivesController
function handleAction(
address user,
uint256 totalSupply,
uint256 userBalance
) external override {
uint256 accruedRewards = _updateUserAssetInternal(user, msg.sender, userBalance, totalSupply);
if (accruedRewards != 0) {
_usersUnclaimedRewards[user] = _usersUnclaimedRewards[user].add(accruedRewards);
emit RewardsAccrued(user, accruedRewards);
}
}
/// @inheritdoc IAaveIncentivesController
function getRewardsBalance(address[] calldata assets, address user)
external
view
override
returns (uint256)
{
uint256 unclaimedRewards = _usersUnclaimedRewards[user];
DistributionTypes.UserStakeInput[] memory userState =
new DistributionTypes.UserStakeInput[](assets.length);
for (uint256 i = 0; i < assets.length; i++) {
userState[i].underlyingAsset = assets[i];
(userState[i].stakedByUser, userState[i].totalStaked) = IScaledBalanceToken(assets[i])
.getScaledUserBalanceAndSupply(user);
}
unclaimedRewards = unclaimedRewards.add(_getUnclaimedRewards(user, userState));
return unclaimedRewards;
}
/// @inheritdoc IAaveIncentivesController
function claimRewards(
address[] calldata assets,
uint256 amount,
address to
) external override returns (uint256) {
require(to != address(0), 'INVALID_TO_ADDRESS');
return _claimRewards(assets, amount, msg.sender, msg.sender, to);
}
/// @inheritdoc IAaveIncentivesController
function claimRewardsOnBehalf(
address[] calldata assets,
uint256 amount,
address user,
address to
) external override onlyAuthorizedClaimers(msg.sender, user) returns (uint256) {
require(user != address(0), 'INVALID_USER_ADDRESS');
require(to != address(0), 'INVALID_TO_ADDRESS');
return _claimRewards(assets, amount, msg.sender, user, to);
}
/**
* @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards.
* @param amount Amount of rewards to claim
* @param user Address to check and claim rewards
* @param to Address that will be receiving the rewards
* @return Rewards claimed
**/
/// @inheritdoc IAaveIncentivesController
function setClaimer(address user, address caller) external override onlyEmissionManager {
_authorizedClaimers[user] = caller;
emit ClaimerSet(user, caller);
}
/// @inheritdoc IAaveIncentivesController
function getClaimer(address user) external view override returns (address) {
return _authorizedClaimers[user];
}
/// @inheritdoc IAaveIncentivesController
function getUserUnclaimedRewards(address _user) external view override returns (uint256) {
return _usersUnclaimedRewards[_user];
}
/// @inheritdoc IAaveIncentivesController
function REWARD_TOKEN() external view override returns (address) {
return address(STAKE_TOKEN);
}
/**
* @dev returns the revision of the implementation contract
*/
function getRevision() internal pure override returns (uint256) {
return REVISION;
}
/**
* @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards.
* @param amount Amount of rewards to claim
* @param user Address to check and claim rewards
* @param to Address that will be receiving the rewards
* @return Rewards claimed
**/
function _claimRewards(
address[] calldata assets,
uint256 amount,
address claimer,
address user,
address to
) internal returns (uint256) {
if (amount == 0) {
return 0;
}
uint256 unclaimedRewards = _usersUnclaimedRewards[user];
DistributionTypes.UserStakeInput[] memory userState =
new DistributionTypes.UserStakeInput[](assets.length);
for (uint256 i = 0; i < assets.length; i++) {
userState[i].underlyingAsset = assets[i];
(userState[i].stakedByUser, userState[i].totalStaked) = IScaledBalanceToken(assets[i])
.getScaledUserBalanceAndSupply(user);
}
uint256 accruedRewards = _claimRewards(user, userState);
if (accruedRewards != 0) {
unclaimedRewards = unclaimedRewards.add(accruedRewards);
emit RewardsAccrued(user, accruedRewards);
}
if (unclaimedRewards == 0) {
return 0;
}
uint256 amountToClaim = amount > unclaimedRewards ? unclaimedRewards : amount;
_usersUnclaimedRewards[user] = unclaimedRewards - amountToClaim; // Safe due to the previous line
STAKE_TOKEN.stake(to, amountToClaim);
emit RewardsClaimed(user, to, claimer, amountToClaim);
return amountToClaim;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import {IERC20} from '../interfaces/IERC20.sol';
import {SafeMath} from './SafeMath.sol';
import {Address} from './Address.sol';
/**
* @title SafeERC20
* @dev From https://github.com/OpenZeppelin/openzeppelin-contracts
* Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
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));
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
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 callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), 'SafeERC20: call to non-contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, 'SafeERC20: low-level call failed');
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed');
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
* From https://github.com/OpenZeppelin/openzeppelin-contracts
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.5;
/**
* @dev From https://github.com/OpenZeppelin/openzeppelin-contracts
* Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, 'SafeMath: addition overflow');
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, 'SafeMath: subtraction overflow');
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, 'SafeMath: multiplication overflow');
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, 'SafeMath: division by zero');
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, 'SafeMath: modulo by zero');
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @dev Collection of functions related to the address type
* From https://github.com/OpenZeppelin/openzeppelin-contracts
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, 'Address: insufficient balance');
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}('');
require(success, 'Address: unable to send value, recipient may have reverted');
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.7.5;
/// @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
/// inspired by uniswap V3
library SafeMath {
/// @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);
}
function div(uint256 x, uint256 y) internal pure returns(uint256) {
// no need to check for division by zero - solidity already reverts
return x / y;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
library DistributionTypes {
struct AssetConfigInput {
uint104 emissionPerSecond;
uint256 totalStaked;
address underlyingAsset;
}
struct UserStakeInput {
address underlyingAsset;
uint256 stakedByUser;
uint256 totalStaked;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.5;
/**
* @title VersionedInitializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*
* @author Aave, inspired by the OpenZeppelin Initializable contract
*/
abstract contract VersionedInitializable {
/**
* @dev Indicates that the contract has been initialized.
*/
uint256 internal lastInitializedRevision = 0;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
uint256 revision = getRevision();
require(revision > lastInitializedRevision, 'Contract instance has already been initialized');
lastInitializedRevision = revision;
_;
}
/// @dev returns the revision number of the contract.
/// Needs to be defined in the inherited class as a constant.
function getRevision() internal pure virtual returns (uint256);
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
import {IAaveDistributionManager} from '../interfaces/IAaveDistributionManager.sol';
import {SafeMath} from '../lib/SafeMath.sol';
import {DistributionTypes} from '../lib/DistributionTypes.sol';
/**
* @title DistributionManager
* @notice Accounting contract to manage multiple staking distributions
* @author Aave
**/
contract DistributionManager is IAaveDistributionManager {
using SafeMath for uint256;
struct AssetData {
uint104 emissionPerSecond;
uint104 index;
uint40 lastUpdateTimestamp;
mapping(address => uint256) users;
}
address public immutable EMISSION_MANAGER;
uint8 public constant PRECISION = 18;
mapping(address => AssetData) public assets;
uint256 internal _distributionEnd;
modifier onlyEmissionManager() {
require(msg.sender == EMISSION_MANAGER, 'ONLY_EMISSION_MANAGER');
_;
}
constructor(address emissionManager) {
EMISSION_MANAGER = emissionManager;
}
/// @inheritdoc IAaveDistributionManager
function setDistributionEnd(uint256 distributionEnd) external override onlyEmissionManager {
_distributionEnd = distributionEnd;
emit DistributionEndUpdated(distributionEnd);
}
/// @inheritdoc IAaveDistributionManager
function getDistributionEnd() external view override returns (uint256) {
return _distributionEnd;
}
/// @inheritdoc IAaveDistributionManager
function DISTRIBUTION_END() external view override returns (uint256) {
return _distributionEnd;
}
/// @inheritdoc IAaveDistributionManager
function getUserAssetData(address user, address asset) public view override returns (uint256) {
return assets[asset].users[user];
}
/**
* @dev Configure the assets for a specific emission
* @param assetsConfigInput The array of each asset configuration
**/
function _configureAssets(DistributionTypes.AssetConfigInput[] memory assetsConfigInput)
internal
{
for (uint256 i = 0; i < assetsConfigInput.length; i++) {
AssetData storage assetConfig = assets[assetsConfigInput[i].underlyingAsset];
_updateAssetStateInternal(
assetsConfigInput[i].underlyingAsset,
assetConfig,
assetsConfigInput[i].totalStaked
);
assetConfig.emissionPerSecond = assetsConfigInput[i].emissionPerSecond;
emit AssetConfigUpdated(
assetsConfigInput[i].underlyingAsset,
assetsConfigInput[i].emissionPerSecond
);
}
}
/**
* @dev Updates the state of one distribution, mainly rewards index and timestamp
* @param asset The address of the asset being updated
* @param assetConfig Storage pointer to the distribution's config
* @param totalStaked Current total of staked assets for this distribution
* @return The new distribution index
**/
function _updateAssetStateInternal(
address asset,
AssetData storage assetConfig,
uint256 totalStaked
) internal returns (uint256) {
uint256 oldIndex = assetConfig.index;
uint256 emissionPerSecond = assetConfig.emissionPerSecond;
uint128 lastUpdateTimestamp = assetConfig.lastUpdateTimestamp;
if (block.timestamp == lastUpdateTimestamp) {
return oldIndex;
}
uint256 newIndex =
_getAssetIndex(oldIndex, emissionPerSecond, lastUpdateTimestamp, totalStaked);
if (newIndex != oldIndex) {
require(uint104(newIndex) == newIndex, 'Index overflow');
//optimization: storing one after another saves one SSTORE
assetConfig.index = uint104(newIndex);
assetConfig.lastUpdateTimestamp = uint40(block.timestamp);
emit AssetIndexUpdated(asset, newIndex);
} else {
assetConfig.lastUpdateTimestamp = uint40(block.timestamp);
}
return newIndex;
}
/**
* @dev Updates the state of an user in a distribution
* @param user The user's address
* @param asset The address of the reference asset of the distribution
* @param stakedByUser Amount of tokens staked by the user in the distribution at the moment
* @param totalStaked Total tokens staked in the distribution
* @return The accrued rewards for the user until the moment
**/
function _updateUserAssetInternal(
address user,
address asset,
uint256 stakedByUser,
uint256 totalStaked
) internal returns (uint256) {
AssetData storage assetData = assets[asset];
uint256 userIndex = assetData.users[user];
uint256 accruedRewards = 0;
uint256 newIndex = _updateAssetStateInternal(asset, assetData, totalStaked);
if (userIndex != newIndex) {
if (stakedByUser != 0) {
accruedRewards = _getRewards(stakedByUser, newIndex, userIndex);
}
assetData.users[user] = newIndex;
emit UserIndexUpdated(user, asset, newIndex);
}
return accruedRewards;
}
/**
* @dev Used by "frontend" stake contracts to update the data of an user when claiming rewards from there
* @param user The address of the user
* @param stakes List of structs of the user data related with his stake
* @return The accrued rewards for the user until the moment
**/
function _claimRewards(address user, DistributionTypes.UserStakeInput[] memory stakes)
internal
returns (uint256)
{
uint256 accruedRewards = 0;
for (uint256 i = 0; i < stakes.length; i++) {
accruedRewards = accruedRewards.add(
_updateUserAssetInternal(
user,
stakes[i].underlyingAsset,
stakes[i].stakedByUser,
stakes[i].totalStaked
)
);
}
return accruedRewards;
}
/**
* @dev Return the accrued rewards for an user over a list of distribution
* @param user The address of the user
* @param stakes List of structs of the user data related with his stake
* @return The accrued rewards for the user until the moment
**/
function _getUnclaimedRewards(address user, DistributionTypes.UserStakeInput[] memory stakes)
internal
view
returns (uint256)
{
uint256 accruedRewards = 0;
for (uint256 i = 0; i < stakes.length; i++) {
AssetData storage assetConfig = assets[stakes[i].underlyingAsset];
uint256 assetIndex =
_getAssetIndex(
assetConfig.index,
assetConfig.emissionPerSecond,
assetConfig.lastUpdateTimestamp,
stakes[i].totalStaked
);
accruedRewards = accruedRewards.add(
_getRewards(stakes[i].stakedByUser, assetIndex, assetConfig.users[user])
);
}
return accruedRewards;
}
/**
* @dev Internal function for the calculation of user's rewards on a distribution
* @param principalUserBalance Amount staked by the user on a distribution
* @param reserveIndex Current index of the distribution
* @param userIndex Index stored for the user, representation his staking moment
* @return The rewards
**/
function _getRewards(
uint256 principalUserBalance,
uint256 reserveIndex,
uint256 userIndex
) internal pure returns (uint256) {
return principalUserBalance.mul(reserveIndex.sub(userIndex)) / 10**uint256(PRECISION);
}
/**
* @dev Calculates the next value of an specific distribution index, with validations
* @param currentIndex Current index of the distribution
* @param emissionPerSecond Representing the total rewards distributed per second per asset unit, on the distribution
* @param lastUpdateTimestamp Last moment this distribution was updated
* @param totalBalance of tokens considered for the distribution
* @return The new index.
**/
function _getAssetIndex(
uint256 currentIndex,
uint256 emissionPerSecond,
uint128 lastUpdateTimestamp,
uint256 totalBalance
) internal view returns (uint256) {
uint256 distributionEnd = _distributionEnd;
if (
emissionPerSecond == 0 ||
totalBalance == 0 ||
lastUpdateTimestamp == block.timestamp ||
lastUpdateTimestamp >= distributionEnd
) {
return currentIndex;
}
uint256 currentTimestamp =
block.timestamp > distributionEnd ? distributionEnd : block.timestamp;
uint256 timeDelta = currentTimestamp.sub(lastUpdateTimestamp);
return
emissionPerSecond.mul(timeDelta).mul(10**uint256(PRECISION)).div(totalBalance).add(
currentIndex
);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
import {DistributionTypes} from '../lib/DistributionTypes.sol';
interface IAaveDistributionManager {
event AssetConfigUpdated(address indexed asset, uint256 emission);
event AssetIndexUpdated(address indexed asset, uint256 index);
event UserIndexUpdated(address indexed user, address indexed asset, uint256 index);
event DistributionEndUpdated(uint256 newDistributionEnd);
/**
* @dev Sets the end date for the distribution
* @param distributionEnd The end date timestamp
**/
function setDistributionEnd(uint256 distributionEnd) external;
/**
* @dev Gets the end date for the distribution
* @return The end of the distribution
**/
function getDistributionEnd() external view returns (uint256);
/**
* @dev for backwards compatibility with the previous DistributionManager used
* @return The end of the distribution
**/
function DISTRIBUTION_END() external view returns(uint256);
/**
* @dev Returns the data of an user on a distribution
* @param user Address of the user
* @param asset The address of the reference asset of the distribution
* @return The new index
**/
function getUserAssetData(address user, address asset) external view returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
import {IStakedToken} from '@aave/aave-stake/contracts/interfaces/IStakedToken.sol';
interface IStakedTokenWithConfig is IStakedToken {
function STAKED_TOKEN() external view returns(address);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.5;
interface IStakedToken {
function stake(address to, uint256 amount) external;
function redeem(address to, uint256 amount) external;
function cooldown() external;
function claimRewards(address to, uint256 amount) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.5;
interface IScaledBalanceToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
/**
* @dev Returns the scaled balance of the user and the scaled total supply.
* @param user The address of the user
* @return The scaled balance of the user
* @return The scaled balance and the scaled total supply
**/
function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);
/**
* @dev Returns the scaled total supply of the token. Represents sum(debt/index)
* @return The scaled total supply
**/
function scaledTotalSupply() external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.7.5;
pragma experimental ABIEncoderV2;
import {IAaveDistributionManager} from '../interfaces/IAaveDistributionManager.sol';
interface IAaveIncentivesController is IAaveDistributionManager {
event RewardsAccrued(address indexed user, uint256 amount);
event RewardsClaimed(
address indexed user,
address indexed to,
address indexed claimer,
uint256 amount
);
event ClaimerSet(address indexed user, address indexed claimer);
/**
* @dev Whitelists an address to claim the rewards on behalf of another address
* @param user The address of the user
* @param claimer The address of the claimer
*/
function setClaimer(address user, address claimer) external;
/**
* @dev Returns the whitelisted claimer for a certain address (0x0 if not set)
* @param user The address of the user
* @return The claimer address
*/
function getClaimer(address user) external view returns (address);
/**
* @dev Configure assets for a certain rewards emission
* @param assets The assets to incentivize
* @param emissionsPerSecond The emission for each asset
*/
function configureAssets(address[] calldata assets, uint256[] calldata emissionsPerSecond)
external;
/**
* @dev Called by the corresponding asset on any update that affects the rewards distribution
* @param asset The address of the user
* @param userBalance The balance of the user of the asset in the lending pool
* @param totalSupply The total supply of the asset in the lending pool
**/
function handleAction(
address asset,
uint256 userBalance,
uint256 totalSupply
) external;
/**
* @dev Returns the total of rewards of an user, already accrued + not yet accrued
* @param user The address of the user
* @return The rewards
**/
function getRewardsBalance(address[] calldata assets, address user)
external
view
returns (uint256);
/**
* @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards
* @param amount Amount of rewards to claim
* @param to Address that will be receiving the rewards
* @return Rewards claimed
**/
function claimRewards(
address[] calldata assets,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. The caller must
* be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager
* @param amount Amount of rewards to claim
* @param user Address to check and claim rewards
* @param to Address that will be receiving the rewards
* @return Rewards claimed
**/
function claimRewardsOnBehalf(
address[] calldata assets,
uint256 amount,
address user,
address to
) external returns (uint256);
/**
* @dev returns the unclaimed rewards of the user
* @param user the address of the user
* @return the unclaimed user rewards
*/
function getUserUnclaimedRewards(address user) external view returns (uint256);
/**
* @dev for backward compatibility with previous implementation of the Incentives controller
*/
function REWARD_TOKEN() external view returns (address);
}
|
@inheritdoc IAaveIncentivesController
|
function setClaimer(address user, address caller) external override onlyEmissionManager {
_authorizedClaimers[user] = caller;
emit ClaimerSet(user, caller);
}
| 1,640,118
|
./full_match/10200/0x6e2CB44C51D6Ca432AE3252843fe0c234c466c6b/sources/newHashi/contracts/ownable/GiriGiriBashi.sol
|
Challenges the oracle adapter to provide a response. If the oracle adapter fails, it can be quarantined. domain Uint256 identifier for the domain for which to set the threshold. id Uint256 threshold to set for the given domain. adapter Address of the oracle adapter to challenge. Caller must pay a minimum bond to issue the challenge. This bond should be high enough to cover the gas costs for successfully completing the challenge. check if oracle is enabled, revert if false check that msg.value is => greater than minimum bond for oracle, revert if false check if oracle is quarantined, revert if true check if challenge already exists, revert if true check if id is lower than startId, revert if true. check if id is less than highestId + challengeRange, revert if false check if id is lower than highestId - idDepth, revert if true create challenge emit OracleAdapterChallenged
|
function challengeOracleAdapter(uint256 domain, uint256 id, IOracleAdapter adapter) public payable {
if (adapters[domain][adapter].previous == IOracleAdapter(address(0)))
revert AdapterNotEnabled(address(this), adapter);
if (msg.value < settings[adapter].minimumBond) revert NotEnoughtValue(address(this), adapter, msg.value);
if (settings[adapter].quarantined) revert AlreadyQuarantined(address(this), adapter);
bytes32 challengeId = getChallengeId(domain, id, adapter);
if (challenges[challengeId].challenger != address(0))
revert DuplicateChallenge(address(this), challengeId, domain, id, adapter);
uint256 challengeRange = challengeRanges[domain];
uint256 idDepth = settings[adapter].idDepth;
uint256 head = heads[domain];
if (
) revert OutOfRange(address(this), adapter, id);
Challenge storage challenge = challenges[challengeId];
challenge.challenger = payable(msg.sender);
challenge.timestamp = block.timestamp;
challenge.bond = msg.value;
emit ChallengeCreated(address(this), challengeId, domain, id, adapter, msg.sender, block.timestamp, msg.value);
}
| 3,784,662
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
/// @title A smart contract for a South African Burial Stokvel
/// @author Jurgen Schulte
/// @notice The contract allows for multiple owners and members After members pay a contribution they are able to submit requests for payment which need to be approved by owners.
/// @dev Deletion and non approval of request will be implemented in later version
contract BurialStokvelAccount is Pausable, AccessControl {
address[] public owners;
address[] public members;
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
bytes32 public constant MEMBER_ROLE = keccak256("MEMBER_ROLE");
uint256 public required;
uint256 public balance;
uint256 public contribution;
// Used to assign transactionID's by incrementing the value
uint256 public transactionCount;
uint256[] private transactionIDs;
mapping(uint256 => Transaction) public transactions;
mapping(uint256 => mapping(address => bool)) public confirmations;
enum State {
Executed,
Pending,
Approved
}
struct Transaction {
string name;
address destination;
uint256 value;
State state;
}
/// @notice Emitted when a request is submitted
/// @param transactionId Transaction ID
event Submission(uint256 indexed transactionId);
/// @notice Emitted when a submitted request is confirmed
/// @param sender Sender address
/// @param transactionId Transaction id
/// @param approved A boolean indication if the confirmed transaction is approved
event Confirmation(
address indexed sender,
uint256 indexed transactionId,
string approved
);
/// @notice Emitted when a transfer of funds is executed
/// @param transactionId Transaction ID
event Execution(uint256 indexed transactionId);
/// @notice Emitted when a transfer of funds fails
/// @param transactionId Transaction ID
event ExecutionFailure(uint256 indexed transactionId);
/// @notice Emitted when a address is enrolled as a member
/// @param accountAddress Account of member
event LogEnrolled(address indexed accountAddress);
/// @notice Emitted when a member deposits his contribution
/// @param sender Sender address
/// @param value Value of contribution
event Deposit(address indexed sender, uint256 value);
/// @notice Fallback function
/// @dev Fallback function allows to deposit ether.
fallback() external payable {
if (msg.value > 0) {
emit Deposit(msg.sender, msg.value);
balance++;
}
}
/// @notice Receive function
/// @dev Receive function allows to deposit ether.
receive() external payable {
if (msg.value > 0) {
emit Deposit(msg.sender, msg.value);
balance++;
}
}
modifier notMember(address _address) {
require(
!hasRole(MEMBER_ROLE, msg.sender),
"Applicant is already a member"
);
_;
}
modifier notOwner(address _address) {
require(
!hasRole(OWNER_ROLE, msg.sender),
"Applicant is already a approver"
);
_;
}
/// @notice Unpause the contract by owners only.
/// @dev This function controls the unpause/pause modifier which is used to prevent withdrawals in case an attack on the contract.
function unpause() public onlyRole(OWNER_ROLE) {
_unpause();
}
/// @notice Pause the contract by owners only.
/// @dev This function controls the unpause/pause modifier which is used to prevent withdrawals in case an attack on the contract.
function pause() public onlyRole(OWNER_ROLE) {
_pause();
}
/// @notice Contract constructor sets initial owners of the stokvel
// account and required number of confirmations.
/// @dev Contract constructor sets initial owners of the stokvel account
/// and required number of confirmations.
/// @param _required Number of required confirmations.
/// @param _contribution Required minimum contribution.
constructor(uint256 _required, uint256 _contribution) {
require(_contribution > 0, "Contribution has to be larger than 0");
require(
_required > 0,
"Number of required approvers has to be larger than 0"
);
required = _required;
contribution = _contribution;
}
/// @notice Enrolls the address as a member
/// @dev Checks that the address is not already a member
function applyAsApprover()
public
notMember(msg.sender)
notOwner(msg.sender)
{
_setupRole(OWNER_ROLE, msg.sender);
owners.push(msg.sender);
}
/// @notice Enrolls the address as a member
/// @dev Checks that the address is not already a member
function enroll()
public
payable
notMember(msg.sender)
notOwner(msg.sender)
{
require(
msg.value >= contribution,
"Amount sent has to be larger than minimum contribution amount"
);
_setupRole(MEMBER_ROLE, msg.sender);
members.push(msg.sender);
emit LogEnrolled(msg.sender);
balance += msg.value;
emit Deposit(msg.sender, msg.value);
}
/// @notice Allows member to submit a payment request
/// @dev The value of the contribution is checked aaginst the minimum contribution
/// stipulated during contract creation
/// @param _value Value of contribution in Wei
/// @param _name Name of request
function submitRequest(uint256 _value, string memory _name)
public
onlyRole(MEMBER_ROLE)
notOwner(msg.sender)
returns (uint256)
{
require(
_value <= balance,
"Amount requested has to be smaller or equal to balance in contract"
);
uint256 transactionId = addTransaction(msg.sender, _value, _name);
return transactionId;
}
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param _destination Transaction target address.
/// @param _value Transaction wei value.
/// @param _name Name of submitted request.
/// @return transactionId Returns transaction ID.
function addTransaction(
address _destination,
uint256 _value,
string memory _name
) internal returns (uint256 transactionId) {
transactionId = transactionCount;
transactions[transactionId] = Transaction({
name: _name,
destination: _destination,
value: _value,
state: State.Pending
});
transactionIDs.push(transactionId);
transactionCount += 1;
emit Submission(transactionId);
}
/// @dev Allows an owner to confirm a transaction.
/// @param _transactionId Transaction ID.
function confirmTransaction(uint256 _transactionId)
public
onlyRole(OWNER_ROLE)
{
//require(isOwner[msg.sender]);
require(
transactions[_transactionId].destination != address(0),
"Desination address cannot be 0"
);
require(
confirmations[_transactionId][msg.sender] == false,
"Sender address has to be equal to address of adress that submitted initial request"
);
confirmations[_transactionId][msg.sender] = true;
string memory approved = "false";
if (isConfirmed(_transactionId)) {
transactions[_transactionId].state = State.Approved;
approved = "true";
}
emit Confirmation(msg.sender, _transactionId, approved);
}
/// @notice Returns the confirmation status of a transaction.
/// @param _transactionId Transaction ID.
/// @return confirmed Confirmation status.
function isConfirmed(uint256 _transactionId)
public
view
returns (bool confirmed)
{
uint256 count = 0;
confirmed = false;
for (uint256 i = 0; i < owners.length; i++) {
if (confirmations[_transactionId][owners[i]]) count += 1;
if (count == required) confirmed = true;
}
return confirmed;
}
/// @notice Withdraws the reqiested amount by the member.
/// @dev The sender address is checked to ensure it matches that of the initial requestor
/// @param _transactionId Transaction ID.
function withdraw(uint256 _transactionId) public whenNotPaused {
require(
transactions[_transactionId].destination == msg.sender,
"Requester of withdrawal needs to be the same as the initiator of initial request"
);
executeTransaction(_transactionId);
}
/// @notice Executes the submitted request.
/// @dev Transaction is executed if enough confirmations have been
/// received and the balance is sufficient.
/// @param _transactionId Transaction ID.
function executeTransaction(uint256 _transactionId) internal {
require(
transactions[_transactionId].state == State.Approved,
"Transaction needs to be in Approved state"
);
// Check balance
require(
transactions[_transactionId].value <= balance,
"Balance needs to be equal or greater than requested amount"
);
if (isConfirmed(_transactionId)) {
Transaction storage t = transactions[_transactionId]; // using the "storage" keyword makes "t" a pointer to storage
t.state = State.Executed;
balance = balance - transactions[_transactionId].value;
(bool success, ) = t.destination.call{
value: transactions[_transactionId].value
}("");
if (success) emit Execution(_transactionId);
else {
emit ExecutionFailure(_transactionId);
t.state = State.Approved;
balance = balance + transactions[_transactionId].value;
require(success, "Failed to send money");
}
}
}
/// @notice Returns all transaction IDs.
/// @return memory All transaction IDs.
function getAllTransactionIDs() public view returns (uint256[] memory) {
return transactionIDs;
}
/// @notice Returns the details of a transaction.
/// @param _transactionId The transaction ID.
function fetchTransaction(uint256 _transactionId)
public
view
returns (
string memory name,
uint256 value,
address destination,
string memory state
)
{
name = transactions[_transactionId].name;
value = transactions[_transactionId].value;
destination = transactions[_transactionId].destination;
if (transactions[_transactionId].state == State.Executed) {
state = "Executed";
} else if (transactions[_transactionId].state == State.Pending) {
state = "Pending";
} else if (transactions[_transactionId].state == State.Approved) {
state = "Approved";
} else {
state = "";
}
return (name, value, destination, state);
}
/// @notice Get all owners.
/// @return memory All owner addresses.
function getOwners() public view returns (address[] memory) {
return owners;
}
/// @notice Get all members.
/// @return memory All member addresses.
function getMembers() public view returns (address[] memory) {
return members;
}
/// @notice Get minimum contribution required.
/// @return uint256 Minimum contribution.
function getMinimumContribution() public view returns (uint256) {
return contribution;
}
/// @notice Get number of required approvals.
/// @return uint256 Number of required approvals.
function getNumberofRequiredApprovals() public view returns (uint256) {
return required;
}
/// @notice Get balance of contract.
/// @return uint256 Balance of contract.
function getBalance() public view returns (uint256) {
return balance;
}
/// @notice Allows approver to cancel submitted transaction
/// @dev This function will allow owners to cancel submitted requests by members
function cancelTransaction() public onlyRole(OWNER_ROLE) {
// TODO: this will allow owners to cancel a transaction. We will need to ensure that a
// transaction is only cancelled when enough owners cancel.
}
/// @notice Allows approvers to remove members
/// @dev This function will allow owners to remove members members
function removeMember() public onlyRole(OWNER_ROLE) {
// TODO: this will allow owners to remove members and refund their contributions.
// This mechanism will ensure owners can remove misbehaving members.
}
}
|
Get minimum contribution required. return uint256 Minimum contribution.
|
function getMinimumContribution() public view returns (uint256) {
return contribution;
}
| 1,806,781
|
./full_match/97/0xD0945d6e56643F23A64257b738d81F4e27a23B48/sources/project_/contracts/diamond/libraries/LibTrading.sol
|
The takeProfit price must be set and the percentage of profit must not exceed the maximum allowed The takeProfit price must be set and the percentage of profit must not exceed the maximum allowed
|
function checkTp(
bool isLong, uint takeProfit, uint entryPrice,
uint leverage_10000, uint maxTakeProfitP
) internal pure {
if (isLong) {
require(
takeProfit > entryPrice &&
(takeProfit - entryPrice) * leverage_10000 <= maxTakeProfitP * entryPrice,
"LibTrading: takeProfit is not in the valid range"
);
require(
takeProfit > 0 &&
takeProfit < entryPrice &&
(entryPrice - takeProfit) * leverage_10000 <= maxTakeProfitP * takeProfit,
"LibTrading: takeProfit is not in the valid range"
);
}
}
| 3,275,988
|
./full_match/1/0xbbcec987E4C189FCbAB0a2534c77b3ba89229F11/sources/contracts/Pool.sol
|
Calculate amount for a value and token _value uint256 claim value _token address claim token return uint256 amount withdrawable/
|
function calculate(
uint256 _value,
address _token
) public view override returns (uint256) {
uint256 _balance = IERC20(_token).balanceOf(address(this));
uint256 _divisor = (uint256(10) ** scale) + _value;
return (max * _value * _balance) / _divisor / MAX_MAX;
}
| 8,386,362
|
// Verified using https://dapp.tools
// hevm: flattened sources of src/borrower/shelf.sol
// SPDX-License-Identifier: AGPL-3.0-only AND MIT
pragma solidity >=0.5.15 >=0.6.12 >=0.6.0 <0.8.0 >=0.7.0 <0.8.0;
////// lib/tinlake-auth/src/auth.sol
// Copyright (C) Centrifuge 2020, based on MakerDAO dss https://github.com/makerdao/dss
/* pragma solidity >=0.5.15; */
contract Auth {
mapping (address => uint256) public wards;
event Rely(address indexed usr);
event Deny(address indexed usr);
function rely(address usr) external auth {
wards[usr] = 1;
emit Rely(usr);
}
function deny(address usr) external auth {
wards[usr] = 0;
emit Deny(usr);
}
modifier auth {
require(wards[msg.sender] == 1, "not-authorized");
_;
}
}
////// lib/tinlake-math/src/math.sol
// Copyright (C) 2018 Rain <rainbreak@riseup.net>
/* pragma solidity >=0.5.15; */
contract Math {
uint256 constant ONE = 10 ** 27;
function safeAdd(uint x, uint y) public pure returns (uint z) {
require((z = x + y) >= x, "safe-add-failed");
}
function safeSub(uint x, uint y) public pure returns (uint z) {
require((z = x - y) <= x, "safe-sub-failed");
}
function safeMul(uint x, uint y) public pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "safe-mul-failed");
}
function safeDiv(uint x, uint y) public pure returns (uint z) {
z = x / y;
}
function rmul(uint x, uint y) public pure returns (uint z) {
z = safeMul(x, y) / ONE;
}
function rdiv(uint x, uint y) public pure returns (uint z) {
require(y > 0, "division by zero");
z = safeAdd(safeMul(x, ONE), y / 2) / y;
}
function rdivup(uint x, uint y) internal pure returns (uint z) {
require(y > 0, "division by zero");
// always rounds up
z = safeAdd(safeMul(x, ONE), safeSub(y, 1)) / y;
}
}
////// lib/tinlake-title/src/openzeppelin-solidity/introspection/IERC165.sol
/* pragma solidity ^0.7.0; */
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
////// lib/tinlake-title/src/openzeppelin-solidity/introspection/ERC165.sol
/* pragma solidity ^0.7.0; */
/* import "./IERC165.sol"; */
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
////// lib/tinlake-title/src/openzeppelin-solidity/math/SafeMath.sol
/* pragma solidity ^0.7.0; */
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, 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;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
////// lib/tinlake-title/src/openzeppelin-solidity/token/ERC721/IERC721.sol
/* pragma solidity ^0.7.0; */
/* import "../../introspection/IERC165.sol"; */
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
////// lib/tinlake-title/src/openzeppelin-solidity/token/ERC721/IERC721Enumerable.sol
/* pragma solidity ^0.7.0; */
/* import "./IERC721.sol"; */
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
////// lib/tinlake-title/src/openzeppelin-solidity/token/ERC721/IERC721Metadata.sol
/* pragma solidity ^0.7.0; */
/* import "./IERC721.sol"; */
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
////// lib/tinlake-title/src/openzeppelin-solidity/token/ERC721/IERC721Receiver.sol
/* pragma solidity ^0.7.0; */
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
////// lib/tinlake-title/src/openzeppelin-solidity/utils/Address.sol
/* pragma solidity ^0.7.0; */
/**
* @dev Collection of functions related to the address type
*/
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);
}
}
}
}
////// lib/tinlake-title/src/openzeppelin-solidity/utils/Context.sol
/* pragma solidity >=0.6.0 <0.8.0; */
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
////// lib/tinlake-title/src/openzeppelin-solidity/utils/EnumerableMap.sol
/* pragma solidity ^0.7.0; */
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
////// lib/tinlake-title/src/openzeppelin-solidity/utils/EnumerableSet.sol
/* pragma solidity ^0.7.0; */
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
////// lib/tinlake-title/src/openzeppelin-solidity/utils/Strings.sol
/* pragma solidity ^0.7.0; */
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
////// lib/tinlake-title/src/openzeppelin-solidity/token/ERC721/ERC721.sol
/* pragma solidity ^0.7.0; */
/* import "../../utils/Context.sol"; */
/* import "./IERC721.sol"; */
/* import "./IERC721Metadata.sol"; */
/* import "./IERC721Enumerable.sol"; */
/* import "./IERC721Receiver.sol"; */
/* import "../../introspection/ERC165.sol"; */
/* import "../../math/SafeMath.sol"; */
/* import "../../utils/Address.sol"; */
/* import "../../utils/EnumerableSet.sol"; */
/* import "../../utils/EnumerableMap.sol"; */
/* import "../../utils/Strings.sol"; */
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
////// lib/tinlake-title/src/title.sol
/* pragma solidity ^0.7.0; */
/* import { ERC721 } from "./openzeppelin-solidity/token/ERC721/ERC721.sol"; */
/* import { Auth } from "tinlake-auth/auth.sol"; */
contract Title is Auth, ERC721 {
// --- Data ---
uint public count;
string public uri;
constructor (string memory name, string memory symbol) ERC721(name, symbol) {
wards[msg.sender] = 1;
count = 1;
}
// --- Title ---
function issue (address usr) public auth returns (uint) {
return _issue(usr);
}
function _issue (address usr) internal returns (uint) {
_mint(usr, count);
count += 1; // can't overflow, not enough gas in the world to pay for 2**256 nfts.
return count-1;
}
function close (uint tkn) public auth {
_burn(tkn);
}
}
interface TitleLike_1 {
function issue(address) external returns (uint);
function close(uint) external;
function ownerOf (uint) external view returns (address);
}
contract TitleOwned {
TitleLike_1 title;
constructor (address title_) {
title = TitleLike_1(title_);
}
modifier owner (uint loan) { require(title.ownerOf(loan) == msg.sender); _; }
}
////// src/borrower/shelf.sol
/* pragma solidity >=0.6.12; */
/* import "tinlake-math/math.sol"; */
/* import "tinlake-auth/auth.sol"; */
/* import { TitleOwned, TitleLike } from "tinlake-title/title.sol"; */
interface NFTLike_2 {
function ownerOf(uint256 tokenId) external view returns (address owner);
function transferFrom(address from, address to, uint256 tokenId) external;
}
interface TokenLike_1 {
function totalSupply() external view returns(uint);
function balanceOf(address) external view returns (uint);
function transferFrom(address,address,uint) external returns (bool);
function transfer(address, uint) external returns (bool);
function approve(address, uint) external;
}
interface PileLike_3 {
function total() external view returns(uint);
function debt(uint) external returns (uint);
function accrue(uint) external;
function incDebt(uint, uint) external;
function decDebt(uint, uint) external;
}
interface NAVFeedLike_2 {
function borrow(uint loan, uint currencyAmount) external;
function repay(uint loan, uint currencyAmount) external;
}
interface ReserveLike_2 {
function balance() external;
}
interface SubscriberLike {
function borrowEvent(uint loan) external;
function unlockEvent(uint loan) external;
}
interface AssessorLike_1 {
function reBalance() external;
}
contract Shelf is Auth, TitleOwned, Math {
// --- Data ---
NAVFeedLike_2 public ceiling;
PileLike_3 public pile;
TokenLike_1 public currency;
ReserveLike_2 public reserve;
AssessorLike_1 public assessor;
SubscriberLike public subscriber;
uint public balance;
address public lender;
struct Loan {
address registry;
uint256 tokenId;
}
mapping (uint => uint) public balances;
mapping (uint => Loan) public shelf;
mapping (bytes32 => uint) public nftlookup;
// Events
event Close(uint indexed loan);
event Issue(address indexed registry_, uint indexed token_);
event Borrow(uint indexed loan, uint currencyAmount);
event Withdraw(uint indexed loan, uint currencyAmount, address usr);
event Repay(uint indexed loan, uint currencyAmount);
event Recover(uint indexed loan, address usr, uint currencyAmount);
event Lock(uint indexed loan);
event Unlock(uint indexed loan);
event Claim(uint indexed loan, address usr);
event Depend(bytes32 indexed contractName, address addr);
constructor(address currency_, address title_, address pile_, address ceiling_) TitleOwned(title_) {
currency = TokenLike_1(currency_);
pile = PileLike_3(pile_);
ceiling = NAVFeedLike_2(ceiling_);
wards[msg.sender] = 1;
emit Rely(msg.sender);
}
// sets the dependency to another contract
function depend(bytes32 contractName, address addr) external auth {
if (contractName == "lender") {
if (lender != address(0)) currency.approve(lender, uint(0));
currency.approve(addr, type(uint256).max);
lender = addr;
}
else if (contractName == "token") { currency = TokenLike_1(addr); }
else if (contractName == "title") { title = TitleLike_1(addr); }
else if (contractName == "pile") { pile = PileLike_3(addr); }
else if (contractName == "ceiling") { ceiling = NAVFeedLike_2(addr); }
else if (contractName == "reserve") { reserve = ReserveLike_2(addr); }
else if (contractName == "assessor") { assessor = AssessorLike_1(addr);}
else if (contractName == "subscriber") { subscriber = SubscriberLike(addr); }
else revert();
emit Depend(contractName, addr);
}
function token(uint loan) public view returns (address registry, uint nft) {
return (shelf[loan].registry, shelf[loan].tokenId);
}
// issues a new loan in Tinlake - it requires the ownership of an nft
// first step in the loan process - everyone could add an nft
function issue(address registry_, uint token_) external returns (uint) {
require(NFTLike_2(registry_).ownerOf(token_) == msg.sender, "nft-not-owned");
bytes32 nft = keccak256(abi.encodePacked(registry_, token_));
require(nftlookup[nft] == 0, "nft-in-use");
uint loan = title.issue(msg.sender);
nftlookup[nft] = loan;
shelf[loan].registry = registry_;
shelf[loan].tokenId = token_;
emit Issue(registry_, token_);
return loan;
}
function close(uint loan) external {
require(pile.debt(loan) == 0, "loan-has-outstanding-debt");
require(!nftLocked(loan), "nft-not-locked");
(address registry, uint tokenId) = token(loan);
require(title.ownerOf(loan) == msg.sender || NFTLike_2(registry).ownerOf(tokenId) == msg.sender, "not-loan-or-nft-owner");
title.close(loan);
bytes32 nft = keccak256(abi.encodePacked(shelf[loan].registry, shelf[loan].tokenId));
nftlookup[nft] = 0;
resetLoanBalance(loan);
emit Close(loan);
}
// used by the lender contracts to know if currency is needed or currency can be taken
function balanceRequest() external view returns (bool, uint) {
uint currencyBalance = currency.balanceOf(address(this));
if (balance > currencyBalance) {
return (true, safeSub(balance, currencyBalance));
} else {
return (false, safeSub(currencyBalance, balance));
}
}
// starts the borrow process of a loan
// informs the system of the requested currencyAmount
// interest accumulation starts with this method
// the method can only be called if the nft is locked
// a max ceiling needs to be defined by an oracle
function borrow(uint loan, uint currencyAmount) external owner(loan) {
require(nftLocked(loan), "nft-not-locked");
if(address(subscriber) != address(0)) {
subscriber.borrowEvent(loan);
}
pile.accrue(loan);
balances[loan] = safeAdd(balances[loan], currencyAmount);
balance = safeAdd(balance, currencyAmount);
// request currency from lender contracts
reserve.balance();
// increase NAV
ceiling.borrow(loan, currencyAmount);
pile.incDebt(loan, currencyAmount);
// reBalance lender interest bearing amount based on new NAV
assessor.reBalance();
emit Borrow(loan, currencyAmount);
}
// withdraw transfers the currency to the borrower account
function withdraw(uint loan, uint currencyAmount, address usr) external owner(loan) {
require(nftLocked(loan), "nft-not-locked");
require(currencyAmount <= balances[loan], "withdraw-amount-too-high");
balances[loan] = safeSub(balances[loan], currencyAmount);
balance = safeSub(balance, currencyAmount);
require(currency.transfer(usr, currencyAmount), "currency-transfer-failed");
emit Withdraw(loan, currencyAmount, usr);
}
// repays the entire or partial debt of a loan
function repay(uint loan, uint currencyAmount) external owner(loan) {
require(nftLocked(loan), "nft-not-locked");
require(balances[loan] == 0, "withdraw-required-before-repay");
_repay(loan, msg.sender, currencyAmount);
emit Repay(loan, currencyAmount);
}
// a collector can recover defaulted loans
// it is not required to recover the entire loan debt
function recover(uint loan, address usr, uint currencyAmount) external auth {
pile.accrue(loan);
uint loanDebt = pile.debt(loan);
require(currency.transferFrom(usr, address(this), currencyAmount), "currency-transfer-failed");
ceiling.repay(loan, loanDebt);
// sets loan debt to 0
pile.decDebt(loan, loanDebt);
resetLoanBalance(loan);
reserve.balance();
// reBalance lender interest bearing amount based on new NAV
assessor.reBalance();
emit Recover(loan, usr, currencyAmount);
}
function _repay(uint loan, address usr, uint currencyAmount) internal {
pile.accrue(loan);
uint loanDebt = pile.debt(loan);
// only repay max loan debt
if (currencyAmount > loanDebt) {
currencyAmount = loanDebt;
}
require(currency.transferFrom(usr, address(this), currencyAmount), "currency-transfer-failed");
ceiling.repay(loan, currencyAmount);
pile.decDebt(loan, currencyAmount);
reserve.balance();
// reBalance lender interest bearing amount based on new NAV
assessor.reBalance();
}
// locks an nft in the shelf
// requires an issued loan
function lock(uint loan) external owner(loan) {
if(address(subscriber) != address(0)) {
subscriber.unlockEvent(loan);
}
NFTLike_2(shelf[loan].registry).transferFrom(msg.sender, address(this), shelf[loan].tokenId);
emit Lock(loan);
}
// unlocks an nft in the shelf
// requires zero debt
function unlock(uint loan) external owner(loan) {
require(pile.debt(loan) == 0, "loan-has-outstanding-debt");
NFTLike_2(shelf[loan].registry).transferFrom(address(this), msg.sender, shelf[loan].tokenId);
emit Unlock(loan);
}
function nftLocked(uint loan) public view returns (bool) {
return NFTLike_2(shelf[loan].registry).ownerOf(shelf[loan].tokenId) == address(this);
}
// a loan can be claimed by a collector if the loan debt is above the loan threshold
// transfers the nft to the collector
function claim(uint loan, address usr) public auth {
NFTLike_2(shelf[loan].registry).transferFrom(address(this), usr, shelf[loan].tokenId);
emit Claim(loan, usr);
}
function resetLoanBalance(uint loan) internal {
uint loanBalance = balances[loan];
if (loanBalance > 0) {
balances[loan] = 0;
balance = safeSub(balance, loanBalance);
}
}
}
|
only repay max loan debt
|
function _repay(uint loan, address usr, uint currencyAmount) internal {
pile.accrue(loan);
uint loanDebt = pile.debt(loan);
if (currencyAmount > loanDebt) {
currencyAmount = loanDebt;
}
require(currency.transferFrom(usr, address(this), currencyAmount), "currency-transfer-failed");
ceiling.repay(loan, currencyAmount);
pile.decDebt(loan, currencyAmount);
reserve.balance();
}
| 10,218,225
|
./full_match/1/0x26Ee982dEE36Df3FA0D0db37798F8d0bD4c305Ed/sources/contracts/RatKingSociety.sol
|
Gets the array of addresses of the free content NFTs provided by RatKingSociety/
|
function getContentNFTList() public view returns (address[] memory) {
return listContentNFT;
}
| 4,929,606
|
// Based on the smart contract for CryptoPunks:
// https://github.com/larvalabs/cryptopunks/blob/master/contracts/CryptoPunksMarket.sol
// Given that the CryptoPunks smart contract has performed well so far,
// I attempted to make as few changes as possible.
// Security upgrades include:
// Locked pragma to Solidity 0.7.4 (and added all necessary syntax upgrades)
// Added circuit breaker (owner only privilege)
// Changed all if-then-throw statements to require statements
// Efficiency upgrades include:
// Variable packing (within reason)
// Reduced some variables to smaller size (e.g., uint --> uint16, string --> bytes8)
// Other changes include:
// Changed variable names to represent tulips
// @author Miguel Opeña
// SPDX-License-Identifier: MIT
pragma solidity 0.7.4;
contract NFTulipsMarket {
// Use this hash to verify the image file containing all the tulips
string public imageHash = "b929f0a772b476441f055c878ba2080ecb10dfd2f103fef876372946660c58fb";
// Use this hash to verify the generative algorithm to create previous image
string public codeHash = "39dce9989126cb2d126e125a7c17de01200fcb7ea8e37705985d84cb4257487c";
address admin;
bool private stopped = false;
bytes8 public name = "NFTulips";
uint16 public totalSupply = 10000;
bool public allTulipsAssigned = false;
uint16 public tulipsRemainingToAssign = 10000;
//mapping (address => uint) public addressToTulipIndex;
mapping (uint16 => address) public tulipIndexToAddress;
/* This creates an array with all balances */
mapping (address => uint) public balanceOf;
struct Offer {
bool isForSale;
uint16 tulipIndex;
address seller;
uint minValue; // in ether
address onlySellTo; // specify to sell only to a specific person
}
struct Bid {
bool hasBid;
uint16 tulipIndex;
address bidder;
uint value;
}
// A record of tulips that are offered for sale at a specific minimum value, and perhaps to a specific person
mapping (uint16 => Offer) public tulipsOfferedForSale;
// A record of the highest tulip bid
mapping (uint16 => Bid) public tulipBids;
mapping (address => uint) public pendingWithdrawals;
event Assign(address indexed to, uint16 tulipIndex);
event Transfer(address indexed from, address indexed to, uint value);
event TulipTransfer(address indexed from, address indexed to, uint16 tulipIndex);
event TulipOffered(uint16 indexed tulipIndex, uint minValue, address indexed toAddress);
event TulipBidEntered(uint16 indexed tulipIndex, uint value, address indexed fromAddress);
event TulipBidWithdrawn(uint16 indexed tulipIndex, uint value, address indexed fromAddress);
event TulipBought(uint16 indexed tulipIndex, uint value, address indexed fromAddress, address indexed toAddress);
event TulipNoLongerForSale(uint16 indexed tulipIndex);
// Admin-only privileges
modifier isAdmin() {
require(msg.sender == admin, "Admin only!");
_;
}
// Circuit breaker modifier
modifier stopInEmergency {
require(!stopped, "Emergency circuit breaker activated; contact admin!");
_;
}
// Initialize contract; assign all tulips to admin; offer for sale at 0.05 ETH apiece
constructor() {
admin = msg.sender;
}
// Circuit breaker activation
function toggleContractActive() isAdmin public {
stopped = !stopped;
}
// Set initial owner (to) of given tulip (tulipIndex)
function setInitialOwner(address to, uint16 tulipIndex) isAdmin public {
require(!allTulipsAssigned, "All tulips already assigned");
require(tulipIndex < totalSupply, "Invalid tulip index");
if (tulipIndexToAddress[tulipIndex] != to) {
if (tulipIndexToAddress[tulipIndex] != address(0)) {
balanceOf[tulipIndexToAddress[tulipIndex]]--;
} else {
tulipsRemainingToAssign--;
}
tulipIndexToAddress[tulipIndex] = to;
balanceOf[to]++;
emit Assign(to, tulipIndex);
}
}
// Set initial owner (addresses[i]) of each tulip (indices[i])
function setInitialOwners(address[] calldata addresses, uint16[] calldata indices) isAdmin public {
uint n = addresses.length;
for (uint16 i = 0; i < n; i++) {
setInitialOwner(addresses[i], indices[i]);
}
}
// Manually toggle when all initial owners assigned
function allInitialOwnersAssigned() isAdmin public {
allTulipsAssigned = true;
}
// Buyer (msg.sender) claims tulip (tulipIndex) for themselves, at zero cost
function getTulip(uint16 tulipIndex) stopInEmergency public {
require(!allTulipsAssigned, "All tulips already assigned");
require(tulipsRemainingToAssign > 0, "No remaining tulips to assign");
require(tulipIndexToAddress[tulipIndex] == address(0), "Tulip must be unclaimed");
require(tulipIndex < totalSupply, "Invalid tulip index");
tulipIndexToAddress[tulipIndex] = msg.sender;
balanceOf[msg.sender]++;
tulipsRemainingToAssign--;
emit Assign(msg.sender, tulipIndex);
}
// Tulip owner (msg.sender) transfers tulip (tulipIndex) to an address (to) for free
function transferTulip(address to, uint16 tulipIndex) stopInEmergency public {
require(allTulipsAssigned, "All tulips must be assigned");
require(tulipIndexToAddress[tulipIndex] == msg.sender, "Tulip owner only");
require(tulipIndex < totalSupply, "Invalid tulip index");
if (tulipsOfferedForSale[tulipIndex].isForSale) {
tulipNoLongerForSale(tulipIndex);
}
tulipIndexToAddress[tulipIndex] = to;
balanceOf[msg.sender]--;
balanceOf[to]++;
emit Transfer(msg.sender, to, 1);
emit TulipTransfer(msg.sender, to, tulipIndex);
// Check for the case where there is a bid from the new owner and refund it.
// Any other bid can stay in place.
// Bid memory bid = tulipBids[tulipIndex];
if (tulipBids[tulipIndex].bidder == to) {
// Kill bid and refund value
pendingWithdrawals[to] += tulipBids[tulipIndex].value;
tulipBids[tulipIndex] = Bid(false, tulipIndex, address(0), 0);
}
}
// Tulip owner (msg.sender) marks tulip (tulipIndex) as not-for-sale
function tulipNoLongerForSale(uint16 tulipIndex) stopInEmergency public {
require(allTulipsAssigned, "All tulips must be assigned");
require(tulipIndexToAddress[tulipIndex] == msg.sender, "Tulip owner only");
require(tulipIndex < totalSupply, "Invalid tulip index");
tulipsOfferedForSale[tulipIndex] = Offer(false, tulipIndex, msg.sender, 0, address(0));
emit TulipNoLongerForSale(tulipIndex);
}
// Tulip owner (msg.sender) marks tulip (tulipIndex) as for sale, at a minimum price (minSalePriceInWei)
function offerTulipForSale(uint16 tulipIndex, uint minSalePriceInWei) stopInEmergency public {
require(allTulipsAssigned, "All tulips must be assigned");
require(tulipIndexToAddress[tulipIndex] == msg.sender, "Tulip owner only");
require(tulipIndex < totalSupply, "Invalid tulip index");
tulipsOfferedForSale[tulipIndex] = Offer(true, tulipIndex, msg.sender, minSalePriceInWei, address(0));
emit TulipOffered(tulipIndex, minSalePriceInWei, address(0));
}
// Tulip owner (msg.sender) marks tulip (tulipIndex) as for sale, at a minimum price (minSalePriceInWei), to a specific address (toAddress)
function offerTulipForSaleToAddress(uint16 tulipIndex, uint minSalePriceInWei, address toAddress) stopInEmergency public {
require(allTulipsAssigned, "All tulips must be assigned");
require(tulipIndexToAddress[tulipIndex] == msg.sender, "Tulip owner only");
require(tulipIndex < totalSupply, "Invalid tulip index");
tulipsOfferedForSale[tulipIndex] = Offer(true, tulipIndex, msg.sender, minSalePriceInWei, toAddress);
emit TulipOffered(tulipIndex, minSalePriceInWei, toAddress);
}
// Buyer (msg.sender) buys tulip (tulipIndex) for themselves
function buyTulip(uint16 tulipIndex) stopInEmergency payable public {
require(allTulipsAssigned, "All tulips must be assigned");
require(tulipIndex < totalSupply, "Invalid tulip index");
// Offer memory offer = tulipsOfferedForSale[tulipIndex];
require(tulipsOfferedForSale[tulipIndex].isForSale, "Tulip must be for sale");
require(tulipsOfferedForSale[tulipIndex].onlySellTo == address(0) || tulipsOfferedForSale[tulipIndex].onlySellTo == msg.sender, "Invalid offer.onlySellTo address");
require(msg.value >= tulipsOfferedForSale[tulipIndex].minValue, "Insufficient ETH attached");
require(tulipsOfferedForSale[tulipIndex].seller == tulipIndexToAddress[tulipIndex], "Seller no longer owner");
address seller = tulipsOfferedForSale[tulipIndex].seller;
tulipIndexToAddress[tulipIndex] = msg.sender;
balanceOf[seller]--;
balanceOf[msg.sender]++;
emit Transfer(seller, msg.sender, 1);
tulipNoLongerForSale(tulipIndex);
pendingWithdrawals[seller] += msg.value;
emit TulipBought(tulipIndex, msg.value, seller, msg.sender);
// Check for the case where there is a bid from the new owner and refund it.
// Any other bid can stay in place.
// Bid memory bid = tulipBids[tulipIndex];
if (tulipBids[tulipIndex].bidder == msg.sender) {
// Kill bid and refund value
pendingWithdrawals[msg.sender] += tulipBids[tulipIndex].value;
tulipBids[tulipIndex] = Bid(false, tulipIndex, address(0), 0);
}
}
// Seller withdraws the funds under their address
function withdraw() public {
require(allTulipsAssigned, "All tulips must be assigned");
uint amount = pendingWithdrawals[msg.sender];
// Remember to zero the pending refund before sending to prevent re-entrancy attacks
pendingWithdrawals[msg.sender] = 0;
// Refund the purchase money
(bool success, ) = msg.sender.call{value: amount}("");
require(success, "Transfer failed");
}
// Bidder (msg.sender) enters bid for tulip (tulipIndex)
function enterBidForTulip(uint16 tulipIndex) stopInEmergency payable public {
require(allTulipsAssigned, "All tulips must be assigned");
require(tulipIndex < totalSupply, "Invalid tulip index");
require(tulipIndexToAddress[tulipIndex] != address(0), "Zero address cannot bid");
require(tulipIndexToAddress[tulipIndex] != msg.sender, "Owner cannot bid on own tulip");
require(msg.value != 0, "msg.value cannot be zero");
// Bid memory existing = tulipBids[tulipIndex];
require(msg.value > tulipBids[tulipIndex].value, "msg.value is too low");
if (tulipBids[tulipIndex].value > 0) {
// Refund the failing bid
pendingWithdrawals[tulipBids[tulipIndex].bidder] += tulipBids[tulipIndex].value;
}
tulipBids[tulipIndex] = Bid(true, tulipIndex, msg.sender, msg.value);
emit TulipBidEntered(tulipIndex, msg.value, msg.sender);
}
// Tulip owner (msg.sender) accepts bid (minPrice) for tulip (tulipIndex)
function acceptBidForTulip(uint16 tulipIndex, uint minPrice) stopInEmergency public {
require(allTulipsAssigned, "All tulips must be assigned");
require(tulipIndex < totalSupply, "Invalid tulip index");
require(tulipIndexToAddress[tulipIndex] == msg.sender, "Tulip owner only");
address seller = msg.sender;
// Bid memory bid = tulipBids[tulipIndex];
require(tulipBids[tulipIndex].value > 0, "Bid value cannot be zero");
require(tulipBids[tulipIndex].value >= minPrice, "Bid value is too low");
tulipIndexToAddress[tulipIndex] = tulipBids[tulipIndex].bidder;
balanceOf[seller]--;
balanceOf[tulipBids[tulipIndex].bidder]++;
emit Transfer(seller, tulipBids[tulipIndex].bidder, 1);
tulipsOfferedForSale[tulipIndex] = Offer(false, tulipIndex, tulipBids[tulipIndex].bidder, 0, address(0));
uint amount = tulipBids[tulipIndex].value;
tulipBids[tulipIndex] = Bid(false, tulipIndex, address(0), 0);
pendingWithdrawals[seller] += amount;
emit TulipBought(tulipIndex, tulipBids[tulipIndex].value, seller, tulipBids[tulipIndex].bidder);
}
// Bidder (msg.sender) withdraws a bid they previously placed
function withdrawBidForTulip(uint16 tulipIndex) public {
require(allTulipsAssigned, "All tulips must be assigned");
require(tulipIndex < totalSupply, "Invalid tulip index");
require(tulipIndexToAddress[tulipIndex] != address(0), "Zero address cannot bid");
require(tulipIndexToAddress[tulipIndex] != msg.sender, "Owner cannot bid on own tulip");
// Bid memory bid = tulipBids[tulipIndex];
require(tulipBids[tulipIndex].bidder == msg.sender, "Only bidder can withdraw their bid");
emit TulipBidWithdrawn(tulipIndex, tulipBids[tulipIndex].value, msg.sender);
uint amount = tulipBids[tulipIndex].value;
tulipBids[tulipIndex] = Bid(false, tulipIndex, address(0), 0);
// Refund the bid money
(bool success, ) = msg.sender.call{value: amount}("");
require(success, "Transfer failed");
}
}
|
Seller withdraws the funds under their address Remember to zero the pending refund before sending to prevent re-entrancy attacks Refund the purchase money
|
function withdraw() public {
require(allTulipsAssigned, "All tulips must be assigned");
uint amount = pendingWithdrawals[msg.sender];
pendingWithdrawals[msg.sender] = 0;
require(success, "Transfer failed");
}
| 7,316,665
|
// Sources flattened with hardhat v2.8.0 https://hardhat.org
// File @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol@v4.4.1
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol@v4.4.1
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol@v4.4.1
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol@v4.4.1
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol@v4.4.1
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @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;
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");
(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");
(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");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal 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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol@v4.4.1
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// File @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol@v4.4.1
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol@v4.4.1
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol@v4.4.1
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol@v4.4.1
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[44] private __gap;
}
// File @openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol@v4.4.1
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// File @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol@v4.4.1
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol@v4.4.1
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable {
function __ERC721Burnable_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Burnable_init_unchained();
}
function __ERC721Burnable_init_unchained() internal onlyInitializing {
}
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/proxy/beacon/IBeaconUpgradeable.sol@v4.4.1
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// File @openzeppelin/contracts-upgradeable/utils/StorageSlotUpgradeable.sol@v4.4.1
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// File @openzeppelin/contracts-upgradeable/proxy/ERC1967/ERC1967UpgradeUpgradeable.sol@v4.4.1
// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal onlyInitializing {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @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) private returns (bytes memory) {
require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol@v4.4.1
// OpenZeppelin Contracts v4.4.1 (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal onlyInitializing {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol@v4.4.1
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File contracts/jbac.sol
pragma solidity ^0.8.2;
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
contract JailedBabyApeClubV2 is Initializable, ERC721Upgradeable, PausableUpgradeable, OwnableUpgradeable, ERC721BurnableUpgradeable, UUPSUpgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
address proxyRegistryAddress;
uint256 basePrice;
uint256 totalSupply;
CountersUpgradeable.Counter private _tokenIdCounter;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function initialize() initializer public {
__ERC721_init("Jailed Baby Ape Club", "JBAC");
__Pausable_init();
__Ownable_init();
__ERC721Burnable_init();
__UUPSUpgradeable_init();
address _proxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1;
proxyRegistryAddress = _proxyRegistryAddress;
basePrice = 30000000000000000;
totalSupply = 8989;
_tokenIdCounter.increment();
}
function batchMint(uint256 count) public payable {
require(msg.value >= basePrice * count, 'INCREASE PAYMENT TO MINT');
for(uint256 i=0; i< count; i++){
uint256 tokenId = _tokenIdCounter.current();
require(tokenId <= totalSupply);
_tokenIdCounter.increment();
_safeMint(msg.sender, tokenId);
}
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
function currentToken() public view returns (uint256) {
uint256 currentNFT = _tokenIdCounter.current();
return currentNFT;
}
function _baseURI() internal pure override returns (string memory) {
return "https://api.gnmedia.studio/v1/jbac/metadata/";
}
function pause() public onlyOwner {
_pause();
}
function unpause() public onlyOwner {
_unpause();
}
function safeMint(address to) public payable {
require(msg.value >= basePrice, 'INCREASE PAYMENT TO MINT');
uint256 tokenId = _tokenIdCounter.current();
require(tokenId <= totalSupply);
_tokenIdCounter.increment();
_safeMint(to, tokenId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
whenNotPaused
override
{
super._beforeTokenTransfer(from, to, tokenId);
}
function _authorizeUpgrade(address newImplementation)
internal
onlyOwner
override
{}
function withdrawAll() public {
uint256 amount = address(this).balance;
require(payable(owner()).send(amount));
}
}
|
This variable should never be directly accessed by users of the library: interactions must be restricted to the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add this feature: see https:github.com/ethereum/solidity/issues/4637
|
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
pragma solidity ^0.8.0;
struct Counter {
}
| 14,734,904
|
/**
*Submitted for verification at Etherscan.io on 2021-03-13
*/
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
pragma solidity ^0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.4.24;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol
pragma solidity ^0.4.24;
/**
* @title DetailedERC20 token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
// File: contracts/interfaces/IAMB.sol
pragma solidity 0.4.24;
interface IAMB {
function messageSender() external view returns (address);
function maxGasPerTx() external view returns (uint256);
function transactionHash() external view returns (bytes32);
function messageId() external view returns (bytes32);
function messageSourceChainId() external view returns (bytes32);
function messageCallStatus(bytes32 _messageId) external view returns (bool);
function failedMessageDataHash(bytes32 _messageId) external view returns (bytes32);
function failedMessageReceiver(bytes32 _messageId) external view returns (address);
function failedMessageSender(bytes32 _messageId) external view returns (address);
function requireToPassMessage(address _contract, bytes _data, uint256 _gas) external returns (bytes32);
function requireToConfirmMessage(address _contract, bytes _data, uint256 _gas) external returns (bytes32);
function sourceChainId() external view returns (uint256);
function destinationChainId() external view returns (uint256);
}
// File: contracts/interfaces/ERC677.sol
pragma solidity 0.4.24;
contract ERC677 is ERC20 {
event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
function transferAndCall(address, uint256, bytes) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) public returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool);
}
contract LegacyERC20 {
function transfer(address _spender, uint256 _value) public; // returns (bool);
function transferFrom(address _owner, address _spender, uint256 _value) public; // returns (bool);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: contracts/upgradeability/EternalStorage.sol
pragma solidity 0.4.24;
/**
* @title EternalStorage
* @dev This contract holds all the necessary state variables to carry out the storage of any contract.
*/
contract EternalStorage {
mapping(bytes32 => uint256) internal uintStorage;
mapping(bytes32 => string) internal stringStorage;
mapping(bytes32 => address) internal addressStorage;
mapping(bytes32 => bytes) internal bytesStorage;
mapping(bytes32 => bool) internal boolStorage;
mapping(bytes32 => int256) internal intStorage;
}
// File: contracts/interfaces/IUpgradeabilityOwnerStorage.sol
pragma solidity 0.4.24;
interface IUpgradeabilityOwnerStorage {
function upgradeabilityOwner() external view returns (address);
}
// File: contracts/upgradeable_contracts/Ownable.sol
pragma solidity 0.4.24;
/**
* @title Ownable
* @dev This contract has an owner address providing basic authorization control
*/
contract Ownable is EternalStorage {
bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202; // upgradeabilityOwner()
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event OwnershipTransferred(address previousOwner, address newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner());
/* solcov ignore next */
_;
}
/**
* @dev Throws if called by any account other than contract itself or owner.
*/
modifier onlyRelevantSender() {
// proxy owner if used through proxy, address(0) otherwise
require(
!address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER)) || // covers usage without calling through storage proxy
msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner() || // covers usage through regular proxy calls
msg.sender == address(this) // covers calls through upgradeAndCall proxy method
);
/* solcov ignore next */
_;
}
bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; // keccak256(abi.encodePacked("owner"))
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function owner() public view returns (address) {
return addressStorage[OWNER];
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner the address to transfer ownership to.
*/
function transferOwnership(address newOwner) external onlyOwner {
_setOwner(newOwner);
}
/**
* @dev Sets a new owner address
*/
function _setOwner(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(owner(), newOwner);
addressStorage[OWNER] = newOwner;
}
}
// File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/BasicMultiTokenBridge.sol
pragma solidity 0.4.24;
contract BasicMultiTokenBridge is EternalStorage, Ownable {
using SafeMath for uint256;
// token == 0x00..00 represents default limits (assuming decimals == 18) for all newly created tokens
event DailyLimitChanged(address indexed token, uint256 newLimit);
event ExecutionDailyLimitChanged(address indexed token, uint256 newLimit);
/**
* @dev Checks if specified token was already bridged at least once.
* @param _token address of the token contract.
* @return true, if token address is address(0) or token was already bridged.
*/
function isTokenRegistered(address _token) public view returns (bool) {
return minPerTx(_token) > 0;
}
/**
* @dev Retrieves the total spent amount for particular token during specific day.
* @param _token address of the token contract.
* @param _day day number for which spent amount if requested.
* @return amount of tokens sent through the bridge to the other side.
*/
function totalSpentPerDay(address _token, uint256 _day) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _token, _day))];
}
/**
* @dev Retrieves the total executed amount for particular token during specific day.
* @param _token address of the token contract.
* @param _day day number for which spent amount if requested.
* @return amount of tokens received from the bridge from the other side.
*/
function totalExecutedPerDay(address _token, uint256 _day) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))];
}
/**
* @dev Retrieves current daily limit for a particular token contract.
* @param _token address of the token contract.
* @return daily limit on tokens that can be sent through the bridge per day.
*/
function dailyLimit(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))];
}
/**
* @dev Retrieves current execution daily limit for a particular token contract.
* @param _token address of the token contract.
* @return daily limit on tokens that can be received from the bridge on the other side per day.
*/
function executionDailyLimit(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))];
}
/**
* @dev Retrieves current maximum amount of tokens per one transfer for a particular token contract.
* @param _token address of the token contract.
* @return maximum amount on tokens that can be sent through the bridge in one transfer.
*/
function maxPerTx(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))];
}
/**
* @dev Retrieves current maximum execution amount of tokens per one transfer for a particular token contract.
* @param _token address of the token contract.
* @return maximum amount on tokens that can received from the bridge on the other side in one transaction.
*/
function executionMaxPerTx(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))];
}
/**
* @dev Retrieves current minimum amount of tokens per one transfer for a particular token contract.
* @param _token address of the token contract.
* @return minimum amount on tokens that can be sent through the bridge in one transfer.
*/
function minPerTx(address _token) public view returns (uint256) {
uint256 limit = uintStorage[keccak256(abi.encodePacked("minPerTx", _token))];
if (_token == address(0)) {
return limit;
}
return limit > 0 ? 1 : 0;
}
/**
* @dev Checks that bridged amount of tokens conforms to the configured limits.
* @param _token address of the token contract.
* @param _amount amount of bridge tokens.
* @return true, if specified amount can be bridged.
*/
function withinLimit(address _token, uint256 _amount) public view returns (bool) {
uint256 nextLimit = totalSpentPerDay(_token, getCurrentDay()).add(_amount);
return
dailyLimit(address(0)) > 0 &&
dailyLimit(_token) >= nextLimit &&
_amount <= maxPerTx(_token) &&
_amount >= minPerTx(_token);
}
/**
* @dev Checks that bridged amount of tokens conforms to the configured execution limits.
* @param _token address of the token contract.
* @param _amount amount of bridge tokens.
* @return true, if specified amount can be processed and executed.
*/
function withinExecutionLimit(address _token, uint256 _amount) public view returns (bool) {
uint256 nextLimit = totalExecutedPerDay(_token, getCurrentDay()).add(_amount);
return
executionDailyLimit(address(0)) > 0 &&
executionDailyLimit(_token) >= nextLimit &&
_amount <= executionMaxPerTx(_token);
}
/**
* @dev Returns current day number.
* @return day number.
*/
function getCurrentDay() public view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return now / 1 days;
}
/**
* @dev Updates daily limit for the particular token. Only owner can call this method.
* @param _token address of the token contract, or address(0) for configuring the efault limit.
* @param _dailyLimit daily allowed amount of bridged tokens, should be greater than maxPerTx.
* 0 value is also allowed, will stop the bridge operations in outgoing direction.
*/
function setDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner {
require(isTokenRegistered(_token));
require(_dailyLimit > maxPerTx(_token) || _dailyLimit == 0);
uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _dailyLimit;
emit DailyLimitChanged(_token, _dailyLimit);
}
/**
* @dev Updates execution daily limit for the particular token. Only owner can call this method.
* @param _token address of the token contract, or address(0) for configuring the default limit.
* @param _dailyLimit daily allowed amount of executed tokens, should be greater than executionMaxPerTx.
* 0 value is also allowed, will stop the bridge operations in incoming direction.
*/
function setExecutionDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner {
require(isTokenRegistered(_token));
require(_dailyLimit > executionMaxPerTx(_token) || _dailyLimit == 0);
uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _dailyLimit;
emit ExecutionDailyLimitChanged(_token, _dailyLimit);
}
/**
* @dev Updates execution maximum per transaction for the particular token. Only owner can call this method.
* @param _token address of the token contract, or address(0) for configuring the default limit.
* @param _maxPerTx maximum amount of executed tokens per one transaction, should be less than executionDailyLimit.
* 0 value is also allowed, will stop the bridge operations in incoming direction.
*/
function setExecutionMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner {
require(isTokenRegistered(_token));
require(_maxPerTx == 0 || (_maxPerTx > 0 && _maxPerTx < executionDailyLimit(_token)));
uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _maxPerTx;
}
/**
* @dev Updates maximum per transaction for the particular token. Only owner can call this method.
* @param _token address of the token contract, or address(0) for configuring the default limit.
* @param _maxPerTx maximum amount of tokens per one transaction, should be less than dailyLimit, greater than minPerTx.
* 0 value is also allowed, will stop the bridge operations in outgoing direction.
*/
function setMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner {
require(isTokenRegistered(_token));
require(_maxPerTx == 0 || (_maxPerTx > minPerTx(_token) && _maxPerTx < dailyLimit(_token)));
uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _maxPerTx;
}
/**
* @dev Updates minumum per transaction for the particular token. Only owner can call this method.
* @param _token address of the token contract, or address(0) for configuring the default limit.
* @param _minPerTx minumum amount of tokens per one transaction, should be less than maxPerTx and dailyLimit.
*/
function setMinPerTx(address _token, uint256 _minPerTx) external onlyOwner {
require(isTokenRegistered(_token));
require(_minPerTx > 0 && _minPerTx < dailyLimit(_token) && _minPerTx < maxPerTx(_token));
uintStorage[keccak256(abi.encodePacked("minPerTx", _token))] = _minPerTx;
}
/**
* @dev Retrieves maximum available bridge amount per one transaction taking into account maxPerTx() and dailyLimit() parameters.
* @param _token address of the token contract, or address(0) for the default limit.
* @return minimum of maxPerTx parameter and remaining daily quota.
*/
function maxAvailablePerTx(address _token) public view returns (uint256) {
uint256 _maxPerTx = maxPerTx(_token);
uint256 _dailyLimit = dailyLimit(_token);
uint256 _spent = totalSpentPerDay(_token, getCurrentDay());
uint256 _remainingOutOfDaily = _dailyLimit > _spent ? _dailyLimit - _spent : 0;
return _maxPerTx < _remainingOutOfDaily ? _maxPerTx : _remainingOutOfDaily;
}
/**
* @dev Internal function for adding spent amount for some token.
* @param _token address of the token contract.
* @param _day day number, when tokens are processed.
* @param _value amount of bridge tokens.
*/
function addTotalSpentPerDay(address _token, uint256 _day, uint256 _value) internal {
uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _token, _day))] = totalSpentPerDay(_token, _day).add(
_value
);
}
/**
* @dev Internal function for adding execcuted amount for some token.
* @param _token address of the token contract.
* @param _day day number, when tokens are processed.
* @param _value amount of bridge tokens.
*/
function addTotalExecutedPerDay(address _token, uint256 _day, uint256 _value) internal {
uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))] = totalExecutedPerDay(
_token,
_day
)
.add(_value);
}
/**
* @dev Internal function for initializing limits for some token.
* @param _token address of the token contract.
* @param _limits [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ].
*/
function _setLimits(address _token, uint256[3] _limits) internal {
require(
_limits[2] > 0 && // minPerTx > 0
_limits[1] > _limits[2] && // maxPerTx > minPerTx
_limits[0] > _limits[1] // dailyLimit > maxPerTx
);
uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _limits[0];
uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _limits[1];
uintStorage[keccak256(abi.encodePacked("minPerTx", _token))] = _limits[2];
emit DailyLimitChanged(_token, _limits[0]);
}
/**
* @dev Internal function for initializing execution limits for some token.
* @param _token address of the token contract.
* @param _limits [ 0 = executionDailyLimit, 1 = executionMaxPerTx ].
*/
function _setExecutionLimits(address _token, uint256[2] _limits) internal {
require(_limits[1] < _limits[0]); // foreignMaxPerTx < foreignDailyLimit
uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _limits[0];
uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _limits[1];
emit ExecutionDailyLimitChanged(_token, _limits[0]);
}
/**
* @dev Internal function for initializing limits for some token relative to its decimals parameter.
* @param _token address of the token contract.
* @param _decimals token decimals parameter.
*/
function _initializeTokenBridgeLimits(address _token, uint256 _decimals) internal {
uint256 factor;
if (_decimals < 18) {
factor = 10**(18 - _decimals);
uint256 _minPerTx = minPerTx(address(0)).div(factor);
uint256 _maxPerTx = maxPerTx(address(0)).div(factor);
uint256 _dailyLimit = dailyLimit(address(0)).div(factor);
uint256 _executionMaxPerTx = executionMaxPerTx(address(0)).div(factor);
uint256 _executionDailyLimit = executionDailyLimit(address(0)).div(factor);
// such situation can happen when calculated limits relative to the token decimals are too low
// e.g. minPerTx(address(0)) == 10 ** 14, _decimals == 3. _minPerTx happens to be 0, which is not allowed.
// in this case, limits are raised to the default values
if (_minPerTx == 0) {
// Numbers 1, 100, 10000 are chosen in a semi-random way,
// so that any token with small decimals can still be bridged in some amounts.
// It is possible to override limits for the particular token later if needed.
_minPerTx = 1;
if (_maxPerTx <= _minPerTx) {
_maxPerTx = 100;
_executionMaxPerTx = 100;
if (_dailyLimit <= _maxPerTx || _executionDailyLimit <= _executionMaxPerTx) {
_dailyLimit = 10000;
_executionDailyLimit = 10000;
}
}
}
_setLimits(_token, [_dailyLimit, _maxPerTx, _minPerTx]);
_setExecutionLimits(_token, [_executionDailyLimit, _executionMaxPerTx]);
} else {
factor = 10**(_decimals - 18);
_setLimits(
_token,
[dailyLimit(address(0)).mul(factor), maxPerTx(address(0)).mul(factor), minPerTx(address(0)).mul(factor)]
);
_setExecutionLimits(
_token,
[executionDailyLimit(address(0)).mul(factor), executionMaxPerTx(address(0)).mul(factor)]
);
}
}
}
// File: contracts/libraries/Bytes.sol
pragma solidity 0.4.24;
/**
* @title Bytes
* @dev Helper methods to transform bytes to other solidity types.
*/
library Bytes {
/**
* @dev Converts bytes array to bytes32.
* Truncates bytes array if its size is more than 32 bytes.
* NOTE: This function does not perform any checks on the received parameter.
* Make sure that the _bytes argument has a correct length, not less than 32 bytes.
* A case when _bytes has length less than 32 will lead to the undefined behaviour,
* since assembly will read data from memory that is not related to the _bytes argument.
* @param _bytes to be converted to bytes32 type
* @return bytes32 type of the firsts 32 bytes array in parameter.
*/
function bytesToBytes32(bytes _bytes) internal pure returns (bytes32 result) {
assembly {
result := mload(add(_bytes, 32))
}
}
/**
* @dev Truncate bytes array if its size is more than 20 bytes.
* NOTE: Similar to the bytesToBytes32 function, make sure that _bytes is not shorter than 20 bytes.
* @param _bytes to be converted to address type
* @return address included in the firsts 20 bytes of the bytes array in parameter.
*/
function bytesToAddress(bytes _bytes) internal pure returns (address addr) {
assembly {
addr := mload(add(_bytes, 20))
}
}
}
// File: openzeppelin-solidity/contracts/AddressUtils.sol
pragma solidity ^0.4.24;
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
// File: contracts/upgradeable_contracts/BasicAMBMediator.sol
pragma solidity 0.4.24;
/**
* @title BasicAMBMediator
* @dev Basic storage and methods needed by mediators to interact with AMB bridge.
*/
contract BasicAMBMediator is Ownable {
bytes32 internal constant BRIDGE_CONTRACT = 0x811bbb11e8899da471f0e69a3ed55090fc90215227fc5fb1cb0d6e962ea7b74f; // keccak256(abi.encodePacked("bridgeContract"))
bytes32 internal constant MEDIATOR_CONTRACT = 0x98aa806e31e94a687a31c65769cb99670064dd7f5a87526da075c5fb4eab9880; // keccak256(abi.encodePacked("mediatorContract"))
bytes32 internal constant REQUEST_GAS_LIMIT = 0x2dfd6c9f781bb6bbb5369c114e949b69ebb440ef3d4dd6b2836225eb1dc3a2be; // keccak256(abi.encodePacked("requestGasLimit"))
/**
* @dev Throws if caller on the other side is not an associated mediator.
*/
modifier onlyMediator {
require(msg.sender == address(bridgeContract()));
require(messageSender() == mediatorContractOnOtherSide());
_;
}
/**
* @dev Sets the AMB bridge contract address. Only the owner can call this method.
* @param _bridgeContract the address of the bridge contract.
*/
function setBridgeContract(address _bridgeContract) external onlyOwner {
_setBridgeContract(_bridgeContract);
}
/**
* @dev Sets the mediator contract address from the other network. Only the owner can call this method.
* @param _mediatorContract the address of the mediator contract.
*/
function setMediatorContractOnOtherSide(address _mediatorContract) external onlyOwner {
_setMediatorContractOnOtherSide(_mediatorContract);
}
/**
* @dev Sets the gas limit to be used in the message execution by the AMB bridge on the other network.
* This value can't exceed the parameter maxGasPerTx defined on the AMB bridge.
* Only the owner can call this method.
* @param _requestGasLimit the gas limit for the message execution.
*/
function setRequestGasLimit(uint256 _requestGasLimit) external onlyOwner {
_setRequestGasLimit(_requestGasLimit);
}
/**
* @dev Get the AMB interface for the bridge contract address
* @return AMB interface for the bridge contract address
*/
function bridgeContract() public view returns (IAMB) {
return IAMB(addressStorage[BRIDGE_CONTRACT]);
}
/**
* @dev Tells the mediator contract address from the other network.
* @return the address of the mediator contract.
*/
function mediatorContractOnOtherSide() public view returns (address) {
return addressStorage[MEDIATOR_CONTRACT];
}
/**
* @dev Tells the gas limit to be used in the message execution by the AMB bridge on the other network.
* @return the gas limit for the message execution.
*/
function requestGasLimit() public view returns (uint256) {
return uintStorage[REQUEST_GAS_LIMIT];
}
/**
* @dev Stores a valid AMB bridge contract address.
* @param _bridgeContract the address of the bridge contract.
*/
function _setBridgeContract(address _bridgeContract) internal {
require(AddressUtils.isContract(_bridgeContract));
addressStorage[BRIDGE_CONTRACT] = _bridgeContract;
}
/**
* @dev Stores the mediator contract address from the other network.
* @param _mediatorContract the address of the mediator contract.
*/
function _setMediatorContractOnOtherSide(address _mediatorContract) internal {
addressStorage[MEDIATOR_CONTRACT] = _mediatorContract;
}
/**
* @dev Stores the gas limit to be used in the message execution by the AMB bridge on the other network.
* @param _requestGasLimit the gas limit for the message execution.
*/
function _setRequestGasLimit(uint256 _requestGasLimit) internal {
require(_requestGasLimit <= maxGasPerTx());
uintStorage[REQUEST_GAS_LIMIT] = _requestGasLimit;
}
/**
* @dev Tells the address that generated the message on the other network that is currently being executed by
* the AMB bridge.
* @return the address of the message sender.
*/
function messageSender() internal view returns (address) {
return bridgeContract().messageSender();
}
/**
* @dev Tells the id of the message originated on the other network.
* @return the id of the message originated on the other network.
*/
function messageId() internal view returns (bytes32) {
return bridgeContract().messageId();
}
/**
* @dev Tells the maximum gas limit that a message can use on its execution by the AMB bridge on the other network.
* @return the maximum gas limit value.
*/
function maxGasPerTx() internal view returns (uint256) {
return bridgeContract().maxGasPerTx();
}
}
// File: contracts/upgradeable_contracts/ChooseReceiverHelper.sol
pragma solidity 0.4.24;
contract ChooseReceiverHelper {
/**
* @dev Helper function for alternative receiver feature. Chooses the actual receiver out of sender and passed data.
* @param _from address of tokens sender.
* @param _data passed data in the transfer message.
* @return address of the receiver on the other side.
*/
function chooseReceiver(address _from, bytes _data) internal view returns (address recipient) {
recipient = _from;
if (_data.length > 0) {
require(_data.length == 20);
recipient = Bytes.bytesToAddress(_data);
require(recipient != address(0));
require(recipient != bridgeContractOnOtherSide());
}
}
/* solcov ignore next */
function bridgeContractOnOtherSide() internal view returns (address);
}
// File: contracts/upgradeable_contracts/TransferInfoStorage.sol
pragma solidity 0.4.24;
contract TransferInfoStorage is EternalStorage {
/**
* @dev Stores the value of a message sent to the AMB bridge.
* @param _messageId of the message sent to the bridge.
* @param _value amount of tokens bridged.
*/
function setMessageValue(bytes32 _messageId, uint256 _value) internal {
uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))] = _value;
}
/**
* @dev Tells the amount of tokens of a message sent to the AMB bridge.
* @return value representing amount of tokens.
*/
function messageValue(bytes32 _messageId) internal view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))];
}
/**
* @dev Stores the receiver of a message sent to the AMB bridge.
* @param _messageId of the message sent to the bridge.
* @param _recipient receiver of the tokens bridged.
*/
function setMessageRecipient(bytes32 _messageId, address _recipient) internal {
addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))] = _recipient;
}
/**
* @dev Tells the receiver of a message sent to the AMB bridge.
* @return address of the receiver.
*/
function messageRecipient(bytes32 _messageId) internal view returns (address) {
return addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))];
}
/**
* @dev Sets that the message sent to the AMB bridge has been fixed.
* @param _messageId of the message sent to the bridge.
*/
function setMessageFixed(bytes32 _messageId) internal {
boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))] = true;
}
/**
* @dev Tells if a message sent to the AMB bridge has been fixed.
* @return bool indicating the status of the message.
*/
function messageFixed(bytes32 _messageId) public view returns (bool) {
return boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))];
}
}
// File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/MultiTokenBridgeMediator.sol
pragma solidity 0.4.24;
/**
* @title MultiTokenBridgeMediator
* @dev Common mediator functionality to handle operations related to multi-token bridge messages sent to AMB bridge.
*/
contract MultiTokenBridgeMediator is
BasicAMBMediator,
BasicMultiTokenBridge,
TransferInfoStorage,
ChooseReceiverHelper
{
event FailedMessageFixed(bytes32 indexed messageId, address token, address recipient, uint256 value);
event TokensBridgingInitiated(
address indexed token,
address indexed sender,
uint256 value,
bytes32 indexed messageId
);
event TokensBridged(address indexed token, address indexed recipient, uint256 value, bytes32 indexed messageId);
/**
* @dev Stores the bridged token of a message sent to the AMB bridge.
* @param _messageId of the message sent to the bridge.
* @param _token bridged token address.
*/
function setMessageToken(bytes32 _messageId, address _token) internal {
addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))] = _token;
}
/**
* @dev Tells the bridged token address of a message sent to the AMB bridge.
* @return address of a token contract.
*/
function messageToken(bytes32 _messageId) internal view returns (address) {
return addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))];
}
/**
* @dev Handles the bridged tokens. Checks that the value is inside the execution limits and invokes the method
* to execute the Mint or Unlock accordingly.
* @param _token bridged ERC20/ERC677 token
* @param _recipient address that will receive the tokens
* @param _value amount of tokens to be received
*/
function _handleBridgedTokens(ERC677 _token, address _recipient, uint256 _value) internal {
if (withinExecutionLimit(_token, _value)) {
addTotalExecutedPerDay(_token, getCurrentDay(), _value);
executeActionOnBridgedTokens(_token, _recipient, _value);
} else {
executeActionOnBridgedTokensOutOfLimit(_token, _recipient, _value);
}
}
/**
* @dev Method to be called when a bridged message execution failed. It will generate a new message requesting to
* fix/roll back the transferred assets on the other network.
* @param _messageId id of the message which execution failed.
*/
function requestFailedMessageFix(bytes32 _messageId) external {
require(!bridgeContract().messageCallStatus(_messageId));
require(bridgeContract().failedMessageReceiver(_messageId) == address(this));
require(bridgeContract().failedMessageSender(_messageId) == mediatorContractOnOtherSide());
bytes4 methodSelector = this.fixFailedMessage.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, _messageId);
bridgeContract().requireToPassMessage(mediatorContractOnOtherSide(), data, requestGasLimit());
}
/**
* @dev Handles the request to fix transferred assets which bridged message execution failed on the other network.
* It uses the information stored by passMessage method when the assets were initially transferred
* @param _messageId id of the message which execution failed on the other network.
*/
function fixFailedMessage(bytes32 _messageId) public onlyMediator {
require(!messageFixed(_messageId));
address token = messageToken(_messageId);
address recipient = messageRecipient(_messageId);
uint256 value = messageValue(_messageId);
setMessageFixed(_messageId);
executeActionOnFixedTokens(token, recipient, value);
emit FailedMessageFixed(_messageId, token, recipient, value);
}
/**
* @dev Execute the action to be performed when the bridge tokens are out of execution limits.
*/
function executeActionOnBridgedTokensOutOfLimit(address, address, uint256) internal {
revert();
}
/* solcov ignore next */
function executeActionOnBridgedTokens(address _token, address _recipient, uint256 _value) internal;
/* solcov ignore next */
function executeActionOnFixedTokens(address _token, address _recipient, uint256 _value) internal;
}
// File: contracts/upgradeable_contracts/Initializable.sol
pragma solidity 0.4.24;
contract Initializable is EternalStorage {
bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba; // keccak256(abi.encodePacked("isInitialized"))
function setInitialize() internal {
boolStorage[INITIALIZED] = true;
}
function isInitialized() public view returns (bool) {
return boolStorage[INITIALIZED];
}
}
// File: contracts/upgradeable_contracts/ReentrancyGuard.sol
pragma solidity 0.4.24;
contract ReentrancyGuard {
function lock() internal returns (bool res) {
assembly {
// Even though this is not the same as boolStorage[keccak256(abi.encodePacked("lock"))],
// since solidity mapping introduces another level of addressing, such slot change is safe
// for temporary variables which are cleared at the end of the call execution.
res := sload(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92) // keccak256(abi.encodePacked("lock"))
}
}
function setLock(bool _lock) internal {
assembly {
// Even though this is not the same as boolStorage[keccak256(abi.encodePacked("lock"))],
// since solidity mapping introduces another level of addressing, such slot change is safe
// for temporary variables which are cleared at the end of the call execution.
sstore(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92, _lock) // keccak256(abi.encodePacked("lock"))
}
}
}
// File: contracts/upgradeable_contracts/Upgradeable.sol
pragma solidity 0.4.24;
contract Upgradeable {
// Avoid using onlyUpgradeabilityOwner name to prevent issues with implementation from proxy contract
modifier onlyIfUpgradeabilityOwner() {
require(msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner());
/* solcov ignore next */
_;
}
}
// File: contracts/upgradeable_contracts/Sacrifice.sol
pragma solidity 0.4.24;
contract Sacrifice {
constructor(address _recipient) public payable {
selfdestruct(_recipient);
}
}
// File: contracts/libraries/Address.sol
pragma solidity 0.4.24;
/**
* @title Address
* @dev Helper methods for Address type.
*/
library Address {
/**
* @dev Try to send native tokens to the address. If it fails, it will force the transfer by creating a selfdestruct contract
* @param _receiver address that will receive the native tokens
* @param _value the amount of native tokens to send
*/
function safeSendValue(address _receiver, uint256 _value) internal {
if (!_receiver.send(_value)) {
(new Sacrifice).value(_value)(_receiver);
}
}
}
// File: contracts/libraries/SafeERC20.sol
pragma solidity 0.4.24;
/**
* @title SafeERC20
* @dev Helper methods for safe token transfers.
* Functions perform additional checks to be sure that token transfer really happened.
*/
library SafeERC20 {
using SafeMath for uint256;
/**
* @dev Same as ERC20.transfer(address,uint256) but with extra consistency checks.
* @param _token address of the token contract
* @param _to address of the receiver
* @param _value amount of tokens to send
*/
function safeTransfer(address _token, address _to, uint256 _value) internal {
LegacyERC20(_token).transfer(_to, _value);
assembly {
if returndatasize {
returndatacopy(0, 0, 32)
if iszero(mload(0)) {
revert(0, 0)
}
}
}
}
/**
* @dev Same as ERC20.transferFrom(address,address,uint256) but with extra consistency checks.
* @param _token address of the token contract
* @param _from address of the sender
* @param _value amount of tokens to send
*/
function safeTransferFrom(address _token, address _from, uint256 _value) internal {
LegacyERC20(_token).transferFrom(_from, address(this), _value);
assembly {
if returndatasize {
returndatacopy(0, 0, 32)
if iszero(mload(0)) {
revert(0, 0)
}
}
}
}
}
// File: contracts/upgradeable_contracts/Claimable.sol
pragma solidity 0.4.24;
/**
* @title Claimable
* @dev Implementation of the claiming utils that can be useful for withdrawing accidentally sent tokens that are not used in bridge operations.
*/
contract Claimable {
using SafeERC20 for address;
/**
* Throws if a given address is equal to address(0)
*/
modifier validAddress(address _to) {
require(_to != address(0));
/* solcov ignore next */
_;
}
/**
* @dev Withdraws the erc20 tokens or native coins from this contract.
* Caller should additionally check that the claimed token is not a part of bridge operations (i.e. that token != erc20token()).
* @param _token address of the claimed token or address(0) for native coins.
* @param _to address of the tokens/coins receiver.
*/
function claimValues(address _token, address _to) internal validAddress(_to) {
if (_token == address(0)) {
claimNativeCoins(_to);
} else {
claimErc20Tokens(_token, _to);
}
}
/**
* @dev Internal function for withdrawing all native coins from the contract.
* @param _to address of the coins receiver.
*/
function claimNativeCoins(address _to) internal {
uint256 value = address(this).balance;
Address.safeSendValue(_to, value);
}
/**
* @dev Internal function for withdrawing all tokens of ssome particular ERC20 contract from this contract.
* @param _token address of the claimed ERC20 token.
* @param _to address of the tokens receiver.
*/
function claimErc20Tokens(address _token, address _to) internal {
ERC20Basic token = ERC20Basic(_token);
uint256 balance = token.balanceOf(this);
_token.safeTransfer(_to, balance);
}
}
// File: contracts/upgradeable_contracts/VersionableBridge.sol
pragma solidity 0.4.24;
contract VersionableBridge {
function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) {
return (5, 2, 0);
}
/* solcov ignore next */
function getBridgeMode() external pure returns (bytes4);
}
// File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/BasicMultiAMBErc20ToErc677.sol
pragma solidity 0.4.24;
/**
* @title BasicMultiAMBErc20ToErc677
* @dev Common functionality for multi-erc20-to-erc677 mediator intended to work on top of AMB bridge.
*/
contract BasicMultiAMBErc20ToErc677 is
Initializable,
ReentrancyGuard,
Upgradeable,
Claimable,
VersionableBridge,
MultiTokenBridgeMediator
{
/**
* @dev Tells the address of the mediator contract on the other side, used by chooseReceiver method
* to avoid sending the native tokens to that address.
* @return address of the mediator contract con the other side
*/
function bridgeContractOnOtherSide() internal view returns (address) {
return mediatorContractOnOtherSide();
}
/**
* @dev Initiate the bridge operation for some amount of tokens from msg.sender.
* The user should first call Approve method of the ERC677 token.
* @param token bridged token contract address.
* @param _receiver address that will receive the native tokens on the other network.
* @param _value amount of tokens to be transferred to the other network.
*/
function relayTokens(ERC677 token, address _receiver, uint256 _value) external {
_relayTokens(token, _receiver, _value);
}
/**
* @dev Initiate the bridge operation for some amount of tokens from msg.sender to msg.sender on the other side.
* The user should first call Approve method of the ERC677 token.
* @param token bridged token contract address.
* @param _value amount of tokens to be transferred to the other network.
*/
function relayTokens(ERC677 token, uint256 _value) external {
_relayTokens(token, msg.sender, _value);
}
/**
* @dev Tells the bridge interface version that this contract supports.
* @return major value of the version
* @return minor value of the version
* @return patch value of the version
*/
function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) {
return (1, 4, 0);
}
/**
* @dev Tells the bridge mode that this contract supports.
* @return _data 4 bytes representing the bridge mode
*/
function getBridgeMode() external pure returns (bytes4 _data) {
return 0xb1516c26; // bytes4(keccak256(abi.encodePacked("multi-erc-to-erc-amb")))
}
/**
* @dev Claims stucked tokens. Only unsupported tokens can be claimed.
* When dealing with already supported tokens, fixMediatorBalance can be used instead.
* @param _token address of claimed token, address(0) for native
* @param _to address of tokens receiver
*/
function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner {
// Only unregistered tokens and native coins are allowed to be claimed with the use of this function
require(_token == address(0) || !isTokenRegistered(_token));
claimValues(_token, _to);
}
/* solcov ignore next */
function onTokenTransfer(address _from, uint256 _value, bytes _data) public returns (bool);
/* solcov ignore next */
function _relayTokens(ERC677 token, address _receiver, uint256 _value) internal;
/* solcov ignore next */
function bridgeSpecificActionsOnTokenTransfer(ERC677 _token, address _from, address _receiver, uint256 _value)
internal;
}
// File: contracts/upgradeability/Proxy.sol
pragma solidity 0.4.24;
/**
* @title Proxy
* @dev Gives the possibility to delegate any call to a foreign implementation.
*/
contract Proxy {
/**
* @dev Tells the address of the implementation where every call will be delegated.
* @return address of the implementation to which it will be delegated
*/
/* solcov ignore next */
function implementation() public view returns (address);
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
function() public payable {
// solhint-disable-previous-line no-complex-fallback
address _impl = implementation();
require(_impl != address(0));
assembly {
/*
0x40 is the "free memory slot", meaning a pointer to next slot of empty memory. mload(0x40)
loads the data in the free memory slot, so `ptr` is a pointer to the next slot of empty
memory. It's needed because we're going to write the return data of delegatecall to the
free memory slot.
*/
let ptr := mload(0x40)
/*
`calldatacopy` is copy calldatasize bytes from calldata
First argument is the destination to which data is copied(ptr)
Second argument specifies the start position of the copied data.
Since calldata is sort of its own unique location in memory,
0 doesn't refer to 0 in memory or 0 in storage - it just refers to the zeroth byte of calldata.
That's always going to be the zeroth byte of the function selector.
Third argument, calldatasize, specifies how much data will be copied.
calldata is naturally calldatasize bytes long (same thing as msg.data.length)
*/
calldatacopy(ptr, 0, calldatasize)
/*
delegatecall params explained:
gas: the amount of gas to provide for the call. `gas` is an Opcode that gives
us the amount of gas still available to execution
_impl: address of the contract to delegate to
ptr: to pass copied data
calldatasize: loads the size of `bytes memory data`, same as msg.data.length
0, 0: These are for the `out` and `outsize` params. Because the output could be dynamic,
these are set to 0, 0 so the output data will not be written to memory. The output
data will be read using `returndatasize` and `returdatacopy` instead.
result: This will be 0 if the call fails and 1 if it succeeds
*/
let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0)
/*
*/
/*
ptr current points to the value stored at 0x40,
because we assigned it like ptr := mload(0x40).
Because we use 0x40 as a free memory pointer,
we want to make sure that the next time we want to allocate memory,
we aren't overwriting anything important.
So, by adding ptr and returndatasize,
we get a memory location beyond the end of the data we will be copying to ptr.
We place this in at 0x40, and any reads from 0x40 will now read from free memory
*/
mstore(0x40, add(ptr, returndatasize))
/*
`returndatacopy` is an Opcode that copies the last return data to a slot. `ptr` is the
slot it will copy to, 0 means copy from the beginning of the return data, and size is
the amount of data to copy.
`returndatasize` is an Opcode that gives us the size of the last return data. In this case, that is the size of the data returned from delegatecall
*/
returndatacopy(ptr, 0, returndatasize)
/*
if `result` is 0, revert.
if `result` is 1, return `size` amount of data from `ptr`. This is the data that was
copied to `ptr` from the delegatecall return data
*/
switch result
case 0 {
revert(ptr, returndatasize)
}
default {
return(ptr, returndatasize)
}
}
}
}
// File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/TokenProxy.sol
pragma solidity 0.4.24;
interface IPermittableTokenVersion {
function version() external pure returns (string);
}
/**
* @title TokenProxy
* @dev Helps to reduces the size of the deployed bytecode for automatically created tokens, by using a proxy contract.
*/
contract TokenProxy is Proxy {
// storage layout is copied from PermittableToken.sol
string internal name;
string internal symbol;
uint8 internal decimals;
mapping(address => uint256) internal balances;
uint256 internal totalSupply;
mapping(address => mapping(address => uint256)) internal allowed;
address internal owner;
bool internal mintingFinished;
address internal bridgeContractAddr;
// string public constant version = "1";
bytes32 internal DOMAIN_SEPARATOR;
// bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb;
mapping(address => uint256) internal nonces;
mapping(address => mapping(address => uint256)) internal expirations;
/**
* @dev Creates a non-upgradeable token proxy for PermitableToken.sol, initializes its eternalStorage.
* @param _tokenImage address of the token image used for mirroring all functions.
* @param _name token name.
* @param _symbol token symbol.
* @param _decimals token decimals.
* @param _chainId chain id for current network.
*/
constructor(address _tokenImage, string memory _name, string memory _symbol, uint8 _decimals, uint256 _chainId)
public
{
string memory version = IPermittableTokenVersion(_tokenImage).version();
assembly {
// EIP 1967
// bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)
sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _tokenImage)
}
name = _name;
symbol = _symbol;
decimals = _decimals;
owner = msg.sender; // msg.sender == HomeMultiAMBErc20ToErc677 mediator
bridgeContractAddr = msg.sender;
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(_name)),
keccak256(bytes(version)),
_chainId,
address(this)
)
);
}
/**
* @dev Retrieves the implementation contract address, mirrored token image.
* @return token image address.
*/
function implementation() public view returns (address impl) {
assembly {
impl := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc)
}
}
}
// File: contracts/upgradeable_contracts/BaseRewardAddressList.sol
pragma solidity 0.4.24;
/**
* @title BaseRewardAddressList
* @dev Implements the logic to store, add and remove reward account addresses. Works as a linked list.
*/
contract BaseRewardAddressList is EternalStorage {
using SafeMath for uint256;
address public constant F_ADDR = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF;
uint256 internal constant MAX_REWARD_ADDRESSES = 50;
bytes32 internal constant REWARD_ADDRESS_COUNT = 0xabc77c82721ced73eef2645facebe8c30249e6ac372cce6eb9d1fed31bd6648f; // keccak256(abi.encodePacked("rewardAddressCount"))
event RewardAddressAdded(address indexed addr);
event RewardAddressRemoved(address indexed addr);
/**
* @dev Retrieves all registered reward accounts.
* @return address list of the registered reward receivers.
*/
function rewardAddressList() external view returns (address[]) {
address[] memory list = new address[](rewardAddressCount());
uint256 counter = 0;
address nextAddr = getNextRewardAddress(F_ADDR);
while (nextAddr != F_ADDR) {
require(nextAddr != address(0));
list[counter] = nextAddr;
nextAddr = getNextRewardAddress(nextAddr);
counter++;
}
return list;
}
/**
* @dev Retrieves amount of registered reward accounts.
* @return length of reward addresses list.
*/
function rewardAddressCount() public view returns (uint256) {
return uintStorage[REWARD_ADDRESS_COUNT];
}
/**
* @dev Checks if specified address is included into the registered rewards receivers list.
* @param _addr address to verify.
* @return true, if specified address is associated with one of the registered reward accounts.
*/
function isRewardAddress(address _addr) public view returns (bool) {
return _addr != F_ADDR && getNextRewardAddress(_addr) != address(0);
}
/**
* @dev Retrieves next reward address in the linked list, or F_ADDR if given address is the last one.
* @param _address address of some reward account.
* @return address of the next reward receiver.
*/
function getNextRewardAddress(address _address) public view returns (address) {
return addressStorage[keccak256(abi.encodePacked("rewardAddressList", _address))];
}
/**
* @dev Internal function for adding a new reward address to the linked list.
* @param _addr new reward account.
*/
function _addRewardAddress(address _addr) internal {
require(_addr != address(0) && _addr != F_ADDR);
require(!isRewardAddress(_addr));
address nextAddr = getNextRewardAddress(F_ADDR);
require(nextAddr != address(0));
_setNextRewardAddress(_addr, nextAddr);
_setNextRewardAddress(F_ADDR, _addr);
_setRewardAddressCount(rewardAddressCount().add(1));
}
/**
* @dev Internal function for removing existing reward address from the linked list.
* @param _addr old reward account which should be removed.
*/
function _removeRewardAddress(address _addr) internal {
require(isRewardAddress(_addr));
address nextAddr = getNextRewardAddress(_addr);
address index = F_ADDR;
address next = getNextRewardAddress(index);
while (next != _addr) {
require(next != address(0));
index = next;
next = getNextRewardAddress(index);
require(next != F_ADDR);
}
_setNextRewardAddress(index, nextAddr);
delete addressStorage[keccak256(abi.encodePacked("rewardAddressList", _addr))];
_setRewardAddressCount(rewardAddressCount().sub(1));
}
/**
* @dev Internal function for initializing linked list with the array of the initial reward addresses.
* @param _rewardAddresses initial reward addresses list, should be non-empty.
*/
function _setRewardAddressList(address[] _rewardAddresses) internal {
require(_rewardAddresses.length > 0);
_setNextRewardAddress(F_ADDR, _rewardAddresses[0]);
for (uint256 i = 0; i < _rewardAddresses.length; i++) {
require(_rewardAddresses[i] != address(0) && _rewardAddresses[i] != F_ADDR);
require(!isRewardAddress(_rewardAddresses[i]));
if (i == _rewardAddresses.length - 1) {
_setNextRewardAddress(_rewardAddresses[i], F_ADDR);
} else {
_setNextRewardAddress(_rewardAddresses[i], _rewardAddresses[i + 1]);
}
emit RewardAddressAdded(_rewardAddresses[i]);
}
_setRewardAddressCount(_rewardAddresses.length);
}
/**
* @dev Internal function for updating the length of the reward accounts list.
* @param _rewardAddressCount new linked list length.
*/
function _setRewardAddressCount(uint256 _rewardAddressCount) internal {
require(_rewardAddressCount <= MAX_REWARD_ADDRESSES);
uintStorage[REWARD_ADDRESS_COUNT] = _rewardAddressCount;
}
/**
* @dev Internal function for updating the pointer to the next reward receiver.
* @param _prevAddr address of some reward receiver.
* @param _addr address of the next receiver to which _prevAddr should point to.
*/
function _setNextRewardAddress(address _prevAddr, address _addr) internal {
addressStorage[keccak256(abi.encodePacked("rewardAddressList", _prevAddr))] = _addr;
}
}
// File: contracts/interfaces/IBurnableMintableERC677Token.sol
pragma solidity 0.4.24;
contract IBurnableMintableERC677Token is ERC677 {
function mint(address _to, uint256 _amount) public returns (bool);
function burn(uint256 _value) public;
function claimTokens(address _token, address _to) external;
}
// File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/HomeFeeManagerMultiAMBErc20ToErc677.sol
pragma solidity 0.4.24;
/**
* @title HomeFeeManagerMultiAMBErc20ToErc677
* @dev Implements the logic to distribute fees from the multi erc20 to erc677 mediator contract operations.
* The fees are distributed in the form of native tokens to the list of reward accounts.
*/
contract HomeFeeManagerMultiAMBErc20ToErc677 is BaseRewardAddressList, Ownable, BasicMultiTokenBridge {
using SafeMath for uint256;
event FeeUpdated(bytes32 feeType, address indexed token, uint256 fee);
event FeeDistributed(uint256 fee, address indexed token, bytes32 indexed messageId);
// This is not a real fee value but a relative value used to calculate the fee percentage
uint256 internal constant MAX_FEE = 1 ether;
bytes32 public constant HOME_TO_FOREIGN_FEE = 0x741ede137d0537e88e0ea0ff25b1f22d837903dbbee8980b4a06e8523247ee26; // keccak256(abi.encodePacked("homeToForeignFee"))
bytes32 public constant FOREIGN_TO_HOME_FEE = 0x03be2b2875cb41e0e77355e802a16769bb8dfcf825061cde185c73bf94f12625; // keccak256(abi.encodePacked("foreignToHomeFee"))
/**
* @dev Throws if given fee percentage is >= 100%.
*/
modifier validFee(uint256 _fee) {
require(_fee < MAX_FEE);
/* solcov ignore next */
_;
}
/**
* @dev Throws if given fee type is unknown.
*/
modifier validFeeType(bytes32 _feeType) {
require(_feeType == HOME_TO_FOREIGN_FEE || _feeType == FOREIGN_TO_HOME_FEE);
/* solcov ignore next */
_;
}
/**
* @dev Adds a new reward address to the list, which will receive fees collected from the bridge operations.
* Only the owner can call this method.
* @param _addr new reward account.
*/
function addRewardAddress(address _addr) external onlyOwner {
_addRewardAddress(_addr);
}
/**
* @dev Removes a reward address from the rewards list.
* Only the owner can call this method.
* @param _addr old reward account, that should be removed.
*/
function removeRewardAddress(address _addr) external onlyOwner {
_removeRewardAddress(_addr);
}
/**
* @dev Updates the value for the particular fee type.
* Only the owner can call this method.
* @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE].
* @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens.
* @param _fee new fee value, in percentage (1 ether == 10**18 == 100%).
*/
function setFee(bytes32 _feeType, address _token, uint256 _fee) external onlyOwner {
_setFee(_feeType, _token, _fee);
}
/**
* @dev Retrieves the value for the particular fee type.
* @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE].
* @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens.
* @return fee value associated with the requested fee type.
*/
function getFee(bytes32 _feeType, address _token) public view validFeeType(_feeType) returns (uint256) {
return uintStorage[keccak256(abi.encodePacked(_feeType, _token))];
}
/**
* @dev Calculates the amount of fee to pay for the value of the particular fee type.
* @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE].
* @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens.
* @param _value bridged value, for which fee should be evaluated.
* @return amount of fee to be subtracted from the transferred value.
*/
function calculateFee(bytes32 _feeType, address _token, uint256 _value) public view returns (uint256) {
uint256 _fee = getFee(_feeType, _token);
return _value.mul(_fee).div(MAX_FEE);
}
/**
* @dev Internal function for updating the fee value for the given fee type.
* @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE].
* @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens.
* @param _fee new fee value, in percentage (1 ether == 10**18 == 100%).
*/
function _setFee(bytes32 _feeType, address _token, uint256 _fee) internal validFeeType(_feeType) validFee(_fee) {
require(isTokenRegistered(_token));
uintStorage[keccak256(abi.encodePacked(_feeType, _token))] = _fee;
emit FeeUpdated(_feeType, _token, _fee);
}
/**
* @dev Calculates a random number based on the block number.
* @param _count the max value for the random number.
* @return a number between 0 and _count.
*/
function random(uint256 _count) internal view returns (uint256) {
return uint256(blockhash(block.number.sub(1))) % _count;
}
/**
* @dev Calculates and distributes the amount of fee proportionally between registered reward addresses.
* @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE].
* @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens.
* @param _value bridged value, for which fee should be evaluated.
* @return total amount of fee subtracted from the transferred value and distributed between the reward accounts.
*/
function _distributeFee(bytes32 _feeType, address _token, uint256 _value) internal returns (uint256) {
uint256 numOfAccounts = rewardAddressCount();
uint256 _fee = calculateFee(_feeType, _token, _value);
if (numOfAccounts == 0 || _fee == 0) {
return 0;
}
uint256 feePerAccount = _fee.div(numOfAccounts);
uint256 randomAccountIndex;
uint256 diff = _fee.sub(feePerAccount.mul(numOfAccounts));
if (diff > 0) {
randomAccountIndex = random(numOfAccounts);
}
address nextAddr = getNextRewardAddress(F_ADDR);
require(nextAddr != F_ADDR && nextAddr != address(0));
uint256 i = 0;
while (nextAddr != F_ADDR) {
uint256 feeToDistribute = feePerAccount;
if (diff > 0 && randomAccountIndex == i) {
feeToDistribute = feeToDistribute.add(diff);
}
if (_feeType == HOME_TO_FOREIGN_FEE) {
ERC677(_token).transfer(nextAddr, feeToDistribute);
} else {
IBurnableMintableERC677Token(_token).mint(nextAddr, feeToDistribute);
}
nextAddr = getNextRewardAddress(nextAddr);
require(nextAddr != address(0));
i = i + 1;
}
return _fee;
}
}
// File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/MultiTokenForwardingRules.sol
pragma solidity 0.4.24;
/**
* @title MultiTokenForwardingRules
* @dev Multi token mediator functionality for managing destination AMB lanes permissions.
*/
contract MultiTokenForwardingRules is Ownable {
address internal constant ANY_ADDRESS = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF;
event ForwardingRuleUpdated(address token, address sender, address receiver, int256 lane);
/**
* @dev Tells the destination lane for a particular bridge operation by checking several wildcard forwarding rules.
* @param _token address of the token contract on the foreign side of the bridge.
* @param _sender address of the tokens sender on the home side of the bridge.
* @param _receiver address of the tokens receiver on the foreign side of the bridge.
* @return destination lane identifier, where the message should be forwarded to.
* 1 - oracle-driven-lane should be used.
* 0 - default behaviour should be applied.
* -1 - manual lane should be used.
*/
function destinationLane(address _token, address _sender, address _receiver) public view returns (int256) {
int256 defaultLane = forwardingRule(_token, ANY_ADDRESS, ANY_ADDRESS); // specific token for all senders and receivers
int256 lane;
if (defaultLane < 0) {
lane = forwardingRule(_token, _sender, ANY_ADDRESS); // specific token for specific sender
if (lane != 0) return lane;
lane = forwardingRule(_token, ANY_ADDRESS, _receiver); // specific token for specific receiver
if (lane != 0) return lane;
return defaultLane;
}
lane = forwardingRule(ANY_ADDRESS, _sender, ANY_ADDRESS); // all tokens for specific sender
if (lane != 0) return lane;
return forwardingRule(ANY_ADDRESS, ANY_ADDRESS, _receiver); // all tokens for specific receiver
}
/**
* Updates the forwarding rule for bridging specific token.
* Only owner can call this method.
* @param _token address of the token contract on the foreign side.
* @param _enable true, if bridge operations for a given token should be forwarded to the manual lane.
*/
function setTokenForwardingRule(address _token, bool _enable) external {
require(_token != ANY_ADDRESS);
_setForwardingRule(_token, ANY_ADDRESS, ANY_ADDRESS, _enable ? int256(-1) : int256(0));
}
/**
* Allows a particular address to send bridge requests to the oracle-driven lane for a particular token.
* Only owner can call this method.
* @param _token address of the token contract on the foreign side.
* @param _sender address of the tokens sender on the home side of the bridge.
* @param _enable true, if bridge operations for a given token and sender should be forwarded to the oracle-driven lane.
*/
function setSenderExceptionForTokenForwardingRule(address _token, address _sender, bool _enable) external {
require(_token != ANY_ADDRESS);
require(_sender != ANY_ADDRESS);
_setForwardingRule(_token, _sender, ANY_ADDRESS, _enable ? int256(1) : int256(0));
}
/**
* Allows a particular address to receive bridged tokens from the oracle-driven lane for a particular token.
* Only owner can call this method.
* @param _token address of the token contract on the foreign side.
* @param _receiver address of the tokens receiver on the foreign side of the bridge.
* @param _enable true, if bridge operations for a given token and receiver should be forwarded to the oracle-driven lane.
*/
function setReceiverExceptionForTokenForwardingRule(address _token, address _receiver, bool _enable) external {
require(_token != ANY_ADDRESS);
require(_receiver != ANY_ADDRESS);
_setForwardingRule(_token, ANY_ADDRESS, _receiver, _enable ? int256(1) : int256(0));
}
/**
* Updates the forwarding rule for the specific sender.
* Only owner can call this method.
* @param _sender address of the tokens sender on the home side.
* @param _enable true, if all bridge operations from a given sender should be forwarded to the manual lane.
*/
function setSenderForwardingRule(address _sender, bool _enable) external {
require(_sender != ANY_ADDRESS);
_setForwardingRule(ANY_ADDRESS, _sender, ANY_ADDRESS, _enable ? int256(-1) : int256(0));
}
/**
* Updates the forwarding rule for the specific receiver.
* Only owner can call this method.
* @param _receiver address of the tokens receiver on the foreign side.
* @param _enable true, if all bridge operations to a given receiver should be forwarded to the manual lane.
*/
function setReceiverForwardingRule(address _receiver, bool _enable) external {
require(_receiver != ANY_ADDRESS);
_setForwardingRule(ANY_ADDRESS, ANY_ADDRESS, _receiver, _enable ? int256(-1) : int256(0));
}
/**
* @dev Tells forwarding rule set up for a particular bridge operation.
* @param _token address of the token contract on the foreign side of the bridge.
* @param _sender address of the tokens sender on the home side of the bridge.
* @param _receiver address of the tokens receiver on the foreign side of the bridge.
* @return preferred destination lane for the particular bridge operation.
*/
function forwardingRule(address _token, address _sender, address _receiver) public view returns (int256) {
return intStorage[keccak256(abi.encodePacked("forwardTo", _token, _sender, _receiver))];
}
/**
* @dev Internal function for updating the preferred destination lane for the specific wildcard pattern.
* Only owner can call this method.
* Examples:
* _setForwardingRule(tokenA, ANY_ADDRESS, ANY_ADDRESS, -1) - forward all operations on tokenA to the manual lane
* _setForwardingRule(tokenA, Alice, ANY_ADDRESS, 1) - allow Alice to use the oracle-driven lane for bridging tokenA
* _setForwardingRule(tokenA, ANY_ADDRESS, Bob, 1) - forward all tokenA bridge operations, where Bob is the receiver, to the oracle-driven lane
* _setForwardingRule(ANY_ADDRESS, Mallory, ANY_ADDRESS, -1) - forward all bridge operations from Mallory to the manual lane
* @param _token address of the token contract on the foreign side of the bridge.
* @param _sender address of the tokens sender on the home side of the bridge.
* @param _receiver address of the tokens receiver on the foreign side of the bridge.
* @param _lane preferred destination lane for the particular sender.
* 1 - forward to the oracle-driven lane.
* 0 - behaviour is unset, proceed by checking other less-specific rules.
* -1 - manual lane should be used.
*/
function _setForwardingRule(address _token, address _sender, address _receiver, int256 _lane) internal onlyOwner {
intStorage[keccak256(abi.encodePacked("forwardTo", _token, _sender, _receiver))] = _lane;
emit ForwardingRuleUpdated(_token, _sender, _receiver, _lane);
}
}
// File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/HomeMultiAMBErc20ToErc677.sol
pragma solidity 0.4.24;
/**
* @title HomeMultiAMBErc20ToErc677
* @dev Home side implementation for multi-erc20-to-erc677 mediator intended to work on top of AMB bridge.
* It is designed to be used as an implementation contract of EternalStorageProxy contract.
*/
contract HomeMultiAMBErc20ToErc677 is
BasicMultiAMBErc20ToErc677,
HomeFeeManagerMultiAMBErc20ToErc677,
MultiTokenForwardingRules
{
bytes32 internal constant TOKEN_IMAGE_CONTRACT = 0x20b8ca26cc94f39fab299954184cf3a9bd04f69543e4f454fab299f015b8130f; // keccak256(abi.encodePacked("tokenImageContract"))
event NewTokenRegistered(address indexed foreignToken, address indexed homeToken);
/**
* @dev Stores the initial parameters of the mediator.
* @param _bridgeContract the address of the AMB bridge contract.
* @param _mediatorContract the address of the mediator contract on the other network.
* @param _dailyLimitMaxPerTxMinPerTxArray array with limit values for the assets to be bridged to the other network.
* [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ]
* @param _executionDailyLimitExecutionMaxPerTxArray array with limit values for the assets bridged from the other network.
* [ 0 = executionDailyLimit, 1 = executionMaxPerTx ]
* @param _requestGasLimit the gas limit for the message execution.
* @param _owner address of the owner of the mediator contract.
* @param _tokenImage address of the PermittableToken contract that will be used for deploying of new tokens.
* @param _rewardAddresses list of reward addresses, between whom fees will be distributed.
* @param _fees array with initial fees for both bridge directions.
* [ 0 = homeToForeignFee, 1 = foreignToHomeFee ]
*/
function initialize(
address _bridgeContract,
address _mediatorContract,
uint256[3] _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ]
uint256[2] _executionDailyLimitExecutionMaxPerTxArray, // [ 0 = _executionDailyLimit, 1 = _executionMaxPerTx ]
uint256 _requestGasLimit,
address _owner,
address _tokenImage,
address[] _rewardAddresses,
uint256[2] _fees // [ 0 = homeToForeignFee, 1 = foreignToHomeFee ]
) external onlyRelevantSender returns (bool) {
require(!isInitialized());
_setBridgeContract(_bridgeContract);
_setMediatorContractOnOtherSide(_mediatorContract);
_setLimits(address(0), _dailyLimitMaxPerTxMinPerTxArray);
_setExecutionLimits(address(0), _executionDailyLimitExecutionMaxPerTxArray);
_setRequestGasLimit(_requestGasLimit);
_setOwner(_owner);
_setTokenImage(_tokenImage);
if (_rewardAddresses.length > 0) {
_setRewardAddressList(_rewardAddresses);
}
_setFee(HOME_TO_FOREIGN_FEE, address(0), _fees[0]);
_setFee(FOREIGN_TO_HOME_FEE, address(0), _fees[1]);
setInitialize();
return isInitialized();
}
/**
* @dev Updates an address of the token image contract used for proxifying newly created tokens.
* @param _tokenImage address of PermittableToken contract.
*/
function setTokenImage(address _tokenImage) external onlyOwner {
_setTokenImage(_tokenImage);
}
/**
* @dev Retrieves address of the token image contract.
* @return address of block reward contract.
*/
function tokenImage() public view returns (address) {
return addressStorage[TOKEN_IMAGE_CONTRACT];
}
/**
* @dev Handles the bridged tokens for the first time, includes deployment of new TokenProxy contract.
* Checks that the value is inside the execution limits and invokes the method
* to execute the Mint or Unlock accordingly.
* @param _token address of the bridged ERC20/ERC677 token on the foreign side.
* @param _name name of the bridged token, "x" will be appended, if empty, symbol will be used instead.
* @param _symbol symbol of the bridged token, "x" will be appended, if empty, name will be used instead.
* @param _decimals decimals of the bridge foreign token.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
*/
function deployAndHandleBridgedTokens(
address _token,
string _name,
string _symbol,
uint8 _decimals,
address _recipient,
uint256 _value
) external onlyMediator {
string memory name = _name;
string memory symbol = _symbol;
require(bytes(name).length > 0 || bytes(symbol).length > 0);
if (bytes(name).length == 0) {
name = symbol;
} else if (bytes(symbol).length == 0) {
symbol = name;
}
name = string(abi.encodePacked(name, " on xDai"));
address homeToken = new TokenProxy(tokenImage(), name, symbol, _decimals, bridgeContract().sourceChainId());
_setTokenAddressPair(_token, homeToken);
_initializeTokenBridgeLimits(homeToken, _decimals);
_setFee(HOME_TO_FOREIGN_FEE, homeToken, getFee(HOME_TO_FOREIGN_FEE, address(0)));
_setFee(FOREIGN_TO_HOME_FEE, homeToken, getFee(FOREIGN_TO_HOME_FEE, address(0)));
_handleBridgedTokens(ERC677(homeToken), _recipient, _value);
emit NewTokenRegistered(_token, homeToken);
}
/**
* @dev Handles the bridged tokens. Checks that the value is inside the execution limits and invokes the method
* to execute the Mint or Unlock accordingly.
* @param _token bridged ERC20 token.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
*/
function handleBridgedTokens(ERC677 _token, address _recipient, uint256 _value) external onlyMediator {
ERC677 homeToken = ERC677(homeTokenAddress(_token));
require(isTokenRegistered(homeToken));
_handleBridgedTokens(homeToken, _recipient, _value);
}
/**
* @dev ERC677 transfer callback function.
* @param _from address of tokens sender.
* @param _value amount of transferred tokens.
* @param _data additional transfer data, can be used for passing alternative receiver address.
*/
function onTokenTransfer(address _from, uint256 _value, bytes _data) public returns (bool) {
// if onTokenTransfer is called as a part of call to _relayTokens, this callback does nothing
if (!lock()) {
ERC677 token = ERC677(msg.sender);
// if msg.sender if not a valid token contract, this check will fail, since limits are zeros
// so the following check is not needed
// require(isTokenRegistered(token));
require(withinLimit(token, _value));
addTotalSpentPerDay(token, getCurrentDay(), _value);
bridgeSpecificActionsOnTokenTransfer(token, _from, chooseReceiver(_from, _data), _value);
}
return true;
}
/**
* @dev Validates that the token amount is inside the limits, calls transferFrom to transfer the tokens to the contract
* and invokes the method to burn/lock the tokens and unlock/mint the tokens on the other network.
* The user should first call Approve method of the ERC677 token.
* @param token bridge token contract address.
* @param _receiver address that will receive the native tokens on the other network.
* @param _value amount of tokens to be transferred to the other network.
*/
function _relayTokens(ERC677 token, address _receiver, uint256 _value) internal {
// This lock is to prevent calling passMessage twice if a ERC677 token is used.
// When transferFrom is called, after the transfer, the ERC677 token will call onTokenTransfer from this contract
// which will call passMessage.
require(!lock());
address to = address(this);
// if msg.sender if not a valid token contract, this check will fail, since limits are zeros
// so the following check is not needed
// require(isTokenRegistered(token));
require(withinLimit(token, _value));
addTotalSpentPerDay(token, getCurrentDay(), _value);
setLock(true);
token.transferFrom(msg.sender, to, _value);
setLock(false);
bridgeSpecificActionsOnTokenTransfer(token, msg.sender, _receiver, _value);
}
/**
* @dev Executes action on the request to deposit tokens relayed from the other network
* @param _recipient address of tokens receiver
* @param _value amount of bridged tokens
*/
function executeActionOnBridgedTokens(address _token, address _recipient, uint256 _value) internal {
bytes32 _messageId = messageId();
uint256 valueToMint = _value;
uint256 fee = _distributeFee(FOREIGN_TO_HOME_FEE, _token, valueToMint);
if (fee > 0) {
emit FeeDistributed(fee, _token, _messageId);
valueToMint = valueToMint.sub(fee);
}
IBurnableMintableERC677Token(_token).mint(_recipient, valueToMint);
emit TokensBridged(_token, _recipient, valueToMint, _messageId);
}
/**
* @dev Mints back the amount of tokens that were bridged to the other network but failed.
* @param _token address that bridged token contract.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
*/
function executeActionOnFixedTokens(address _token, address _recipient, uint256 _value) internal {
IBurnableMintableERC677Token(_token).mint(_recipient, _value);
}
/**
* @dev Retrieves address of the home bridged token contract associated with a specific foreign token contract.
* @param _foreignToken address of the created home token contract.
* @return address of the home token contract.
*/
function homeTokenAddress(address _foreignToken) public view returns (address) {
return addressStorage[keccak256(abi.encodePacked("homeTokenAddress", _foreignToken))];
}
/**
* @dev Retrieves address of the foreign bridged token contract associated with a specific home token contract.
* @param _homeToken address of the created home token contract.
* @return address of the foreign token contract.
*/
function foreignTokenAddress(address _homeToken) public view returns (address) {
return addressStorage[keccak256(abi.encodePacked("foreignTokenAddress", _homeToken))];
}
/**
* @dev Internal function for updating an address of the token image contract.
* @param _foreignToken address of bridged foreign token contract.
* @param _foreignToken address of created home token contract.
*/
function _setTokenAddressPair(address _foreignToken, address _homeToken) internal {
addressStorage[keccak256(abi.encodePacked("homeTokenAddress", _foreignToken))] = _homeToken;
addressStorage[keccak256(abi.encodePacked("foreignTokenAddress", _homeToken))] = _foreignToken;
}
/**
* @dev Internal function for updating an address of the token image contract.
* @param _tokenImage address of deployed PermittableToken contract.
*/
function _setTokenImage(address _tokenImage) internal {
require(AddressUtils.isContract(_tokenImage));
addressStorage[TOKEN_IMAGE_CONTRACT] = _tokenImage;
}
/**
* @dev Executes action on withdrawal of bridged tokens
* @param _token address of token contract
* @param _from address of tokens sender
* @param _receiver address of tokens receiver on the other side
* @param _value requested amount of bridged tokens
*/
function bridgeSpecificActionsOnTokenTransfer(ERC677 _token, address _from, address _receiver, uint256 _value)
internal
{
uint256 valueToBridge = _value;
uint256 fee = 0;
// Next line disables fee collection in case sender is one of the reward addresses.
// It is needed to allow a 100% withdrawal of tokens from the home side.
// If fees are not disabled for reward receivers, small fraction of tokens will always
// be redistributed between the same set of reward addresses, which is not the desired behaviour.
if (!isRewardAddress(_from)) {
fee = _distributeFee(HOME_TO_FOREIGN_FEE, _token, valueToBridge);
valueToBridge = valueToBridge.sub(fee);
}
IBurnableMintableERC677Token(_token).burn(valueToBridge);
bytes32 _messageId = passMessage(_token, _from, _receiver, valueToBridge);
if (fee > 0) {
emit FeeDistributed(fee, _token, _messageId);
}
}
/**
* @dev Call AMB bridge to require the invocation of handleBridgedTokens method of the mediator on the other network.
* Store information related to the bridged tokens in case the message execution fails on the other network
* and the action needs to be fixed/rolled back.
* @param _token bridged ERC20 token
* @param _from address of sender, if bridge operation fails, tokens will be returned to this address
* @param _receiver address of receiver on the other side, will eventually receive bridged tokens
* @param _value bridged amount of tokens
* @return id of the created and passed message
*/
function passMessage(ERC677 _token, address _from, address _receiver, uint256 _value) internal returns (bytes32) {
bytes4 methodSelector = this.handleBridgedTokens.selector;
address foreignToken = foreignTokenAddress(_token);
bytes memory data = abi.encodeWithSelector(methodSelector, foreignToken, _receiver, _value);
address executor = mediatorContractOnOtherSide();
uint256 gasLimit = requestGasLimit();
IAMB bridge = bridgeContract();
// Address of the foreign token is used here for determining lane permissions.
// Such decision makes it possible to set rules for tokens that are not bridged yet.
bytes32 _messageId = destinationLane(foreignToken, _from, _receiver) >= 0
? bridge.requireToPassMessage(executor, data, gasLimit)
: bridge.requireToConfirmMessage(executor, data, gasLimit);
setMessageToken(_messageId, _token);
setMessageValue(_messageId, _value);
setMessageRecipient(_messageId, _from);
emit TokensBridgingInitiated(_token, _from, _value, _messageId);
return _messageId;
}
}
// File: contracts/libraries/TokenReader.sol
pragma solidity 0.4.24;
/**
* @title TokenReader
* @dev Helper methods for reading name/symbol/decimals parameters from ERC20 token contracts.
*/
library TokenReader {
/**
* @dev Reads the name property of the provided token.
* Either name() or NAME() method is used.
* Both, string and bytes32 types are supported.
* @param _token address of the token contract.
* @return token name as a string or an empty string if none of the methods succeeded.
*/
function readName(address _token) internal view returns (string) {
uint256 ptr;
uint256 size;
assembly {
ptr := mload(0x40)
mstore(ptr, 0x06fdde0300000000000000000000000000000000000000000000000000000000) // name()
if iszero(staticcall(gas, _token, ptr, 4, ptr, 32)) {
mstore(ptr, 0xa3f4df7e00000000000000000000000000000000000000000000000000000000) // NAME()
staticcall(gas, _token, ptr, 4, ptr, 32)
pop
}
mstore(0x40, add(ptr, returndatasize))
switch gt(returndatasize, 32)
case 1 {
returndatacopy(mload(0x40), 32, 32) // string length
size := mload(mload(0x40))
}
default {
size := returndatasize // 32 or 0
}
}
string memory res = new string(size);
assembly {
if gt(returndatasize, 32) {
// load as string
returndatacopy(add(res, 32), 64, size)
jump(exit)
}
/* solhint-disable */
if gt(returndatasize, 0) {
let i := 0
ptr := mload(ptr) // load bytes32 value
mstore(add(res, 32), ptr) // save value in result string
for { } gt(ptr, 0) { i := add(i, 1) } { // until string is empty
ptr := shl(8, ptr) // shift left by one symbol
}
mstore(res, i) // save result string length
}
exit:
/* solhint-enable */
}
return res;
}
/**
* @dev Reads the symbol property of the provided token.
* Either symbol() or SYMBOL() method is used.
* Both, string and bytes32 types are supported.
* @param _token address of the token contract.
* @return token symbol as a string or an empty string if none of the methods succeeded.
*/
function readSymbol(address _token) internal view returns (string) {
uint256 ptr;
uint256 size;
assembly {
ptr := mload(0x40)
mstore(ptr, 0x95d89b4100000000000000000000000000000000000000000000000000000000) // symbol()
if iszero(staticcall(gas, _token, ptr, 4, ptr, 32)) {
mstore(ptr, 0xf76f8d7800000000000000000000000000000000000000000000000000000000) // SYMBOL()
staticcall(gas, _token, ptr, 4, ptr, 32)
pop
}
mstore(0x40, add(ptr, returndatasize))
switch gt(returndatasize, 32)
case 1 {
returndatacopy(mload(0x40), 32, 32) // string length
size := mload(mload(0x40))
}
default {
size := returndatasize // 32 or 0
}
}
string memory res = new string(size);
assembly {
if gt(returndatasize, 32) {
// load as string
returndatacopy(add(res, 32), 64, size)
jump(exit)
}
/* solhint-disable */
if gt(returndatasize, 0) {
let i := 0
ptr := mload(ptr) // load bytes32 value
mstore(add(res, 32), ptr) // save value in result string
for { } gt(ptr, 0) { i := add(i, 1) } { // until string is empty
ptr := shl(8, ptr) // shift left by one symbol
}
mstore(res, i) // save result string length
}
exit:
/* solhint-enable */
}
return res;
}
/**
* @dev Reads the decimals property of the provided token.
* Either decimals() or DECIMALS() method is used.
* @param _token address of the token contract.
* @return token decimals or 0 if none of the methods succeeded.
*/
function readDecimals(address _token) internal view returns (uint256) {
uint256 decimals;
assembly {
let ptr := mload(0x40)
mstore(0x40, add(ptr, 32))
mstore(ptr, 0x313ce56700000000000000000000000000000000000000000000000000000000) // decimals()
if iszero(staticcall(gas, _token, ptr, 4, ptr, 32)) {
mstore(ptr, 0x2e0f262500000000000000000000000000000000000000000000000000000000) // DECIMALS()
if iszero(staticcall(gas, _token, ptr, 4, ptr, 32)) {
mstore(ptr, 0)
}
}
decimals := mload(ptr)
}
return decimals;
}
}
// File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/ForeignMultiAMBErc20ToErc677.sol
pragma solidity 0.4.24;
/**
* @title ForeignMultiAMBErc20ToErc677
* @dev Foreign side implementation for multi-erc20-to-erc677 mediator intended to work on top of AMB bridge.
* It is designed to be used as an implementation contract of EternalStorageProxy contract.
*/
contract ForeignMultiAMBErc20ToErc677 is BasicMultiAMBErc20ToErc677 {
using SafeERC20 for address;
using SafeERC20 for ERC677;
/**
* @dev Stores the initial parameters of the mediator.
* @param _bridgeContract the address of the AMB bridge contract.
* @param _mediatorContract the address of the mediator contract on the other network.
* @param _dailyLimitMaxPerTxMinPerTxArray array with limit values for the assets to be bridged to the other network.
* [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ]
* @param _executionDailyLimitExecutionMaxPerTxArray array with limit values for the assets bridged from the other network.
* [ 0 = executionDailyLimit, 1 = executionMaxPerTx ]
* @param _requestGasLimit the gas limit for the message execution.
* @param _owner address of the owner of the mediator contract.
*/
function initialize(
address _bridgeContract,
address _mediatorContract,
uint256[3] _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ]
uint256[2] _executionDailyLimitExecutionMaxPerTxArray, // [ 0 = _executionDailyLimit, 1 = _executionMaxPerTx ]
uint256 _requestGasLimit,
address _owner
) external onlyRelevantSender returns (bool) {
require(!isInitialized());
_setBridgeContract(_bridgeContract);
_setMediatorContractOnOtherSide(_mediatorContract);
_setLimits(address(0), _dailyLimitMaxPerTxMinPerTxArray);
_setExecutionLimits(address(0), _executionDailyLimitExecutionMaxPerTxArray);
_setRequestGasLimit(_requestGasLimit);
_setOwner(_owner);
setInitialize();
return isInitialized();
}
/**
* @dev Executes action on the request to withdraw tokens relayed from the other network
* @param _token address of the token contract
* @param _recipient address of tokens receiver
* @param _value amount of bridged tokens
*/
function executeActionOnBridgedTokens(address _token, address _recipient, uint256 _value) internal {
bytes32 _messageId = messageId();
_releaseTokens(_token, _recipient, _value);
emit TokensBridged(_token, _recipient, _value, _messageId);
}
/**
* @dev ERC677 transfer callback function.
* @param _from address of tokens sender.
* @param _value amount of transferred tokens.
* @param _data additional transfer data, can be used for passing alternative receiver address.
*/
function onTokenTransfer(address _from, uint256 _value, bytes _data) public returns (bool) {
if (!lock()) {
ERC677 token = ERC677(msg.sender);
bridgeSpecificActionsOnTokenTransfer(token, _from, chooseReceiver(_from, _data), _value);
}
return true;
}
/**
* @dev Handles the bridged tokens. Checks that the value is inside the execution limits and invokes the method
* to execute the Mint or Unlock accordingly.
* @param _token bridged ERC20 token.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
*/
function handleBridgedTokens(ERC677 _token, address _recipient, uint256 _value) external onlyMediator {
require(isTokenRegistered(_token));
_handleBridgedTokens(_token, _recipient, _value);
}
/**
* @dev Validates that the token amount is inside the limits, calls transferFrom to transfer the tokens to the contract
* and invokes the method to burn/lock the tokens and unlock/mint the tokens on the other network.
* The user should first call Approve method of the ERC677 token.
* @param token bridge token contract address.
* @param _receiver address that will receive the native tokens on the other network.
* @param _value amount of tokens to be transferred to the other network.
*/
function _relayTokens(ERC677 token, address _receiver, uint256 _value) internal {
// This lock is to prevent calling passMessage twice if a ERC677 token is used.
// When transferFrom is called, after the transfer, the ERC677 token will call onTokenTransfer from this contract
// which will call passMessage.
require(!lock());
uint256 balanceBefore = token.balanceOf(address(this));
setLock(true);
token.safeTransferFrom(msg.sender, _value);
setLock(false);
uint256 balanceDiff = token.balanceOf(address(this)).sub(balanceBefore);
require(balanceDiff <= _value);
bridgeSpecificActionsOnTokenTransfer(token, msg.sender, _receiver, balanceDiff);
}
/**
* @dev Executes action on deposit of bridged tokens
* @param _token address of the token contract
* @param _from address of tokens sender
* @param _receiver address of tokens receiver on the other side
* @param _value requested amount of bridged tokens
*/
function bridgeSpecificActionsOnTokenTransfer(ERC677 _token, address _from, address _receiver, uint256 _value)
internal
{
bool isKnownToken = isTokenRegistered(_token);
if (!isKnownToken) {
string memory name = TokenReader.readName(_token);
string memory symbol = TokenReader.readSymbol(_token);
uint8 decimals = uint8(TokenReader.readDecimals(_token));
require(bytes(name).length > 0 || bytes(symbol).length > 0);
_initializeTokenBridgeLimits(_token, decimals);
}
require(withinLimit(_token, _value));
addTotalSpentPerDay(_token, getCurrentDay(), _value);
bytes memory data;
if (isKnownToken) {
data = abi.encodeWithSelector(this.handleBridgedTokens.selector, _token, _receiver, _value);
} else {
data = abi.encodeWithSelector(
HomeMultiAMBErc20ToErc677(this).deployAndHandleBridgedTokens.selector,
_token,
name,
symbol,
decimals,
_receiver,
_value
);
}
_setMediatorBalance(_token, mediatorBalance(_token).add(_value));
bytes32 _messageId = bridgeContract().requireToPassMessage(
mediatorContractOnOtherSide(),
data,
requestGasLimit()
);
setMessageToken(_messageId, _token);
setMessageValue(_messageId, _value);
setMessageRecipient(_messageId, _from);
if (!isKnownToken) {
_setTokenRegistrationMessageId(_token, _messageId);
}
emit TokensBridgingInitiated(_token, _from, _value, _messageId);
}
/**
* @dev Handles the request to fix transferred assets which bridged message execution failed on the other network.
* It uses the information stored by passMessage method when the assets were initially transferred
* @param _messageId id of the message which execution failed on the other network.
*/
function fixFailedMessage(bytes32 _messageId) public {
super.fixFailedMessage(_messageId);
address token = messageToken(_messageId);
if (_messageId == tokenRegistrationMessageId(token)) {
delete uintStorage[keccak256(abi.encodePacked("dailyLimit", token))];
delete uintStorage[keccak256(abi.encodePacked("maxPerTx", token))];
delete uintStorage[keccak256(abi.encodePacked("minPerTx", token))];
delete uintStorage[keccak256(abi.encodePacked("executionDailyLimit", token))];
delete uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", token))];
_setTokenRegistrationMessageId(token, bytes32(0));
}
}
/**
* @dev Unlock back the amount of tokens that were bridged to the other network but failed.
* @param _token address that bridged token contract.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
*/
function executeActionOnFixedTokens(address _token, address _recipient, uint256 _value) internal {
_releaseTokens(_token, _recipient, _value);
}
/**
* @dev Allows to send to the other network the amount of locked tokens that can be forced into the contract
* without the invocation of the required methods. (e. g. regular transfer without a call to onTokenTransfer)
* @param _token address of the token contract.
* @param _receiver the address that will receive the tokens on the other network.
*/
function fixMediatorBalance(address _token, address _receiver)
external
onlyIfUpgradeabilityOwner
validAddress(_receiver)
{
require(isTokenRegistered(_token));
uint256 balance = ERC677(_token).balanceOf(address(this));
uint256 expectedBalance = mediatorBalance(_token);
require(balance > expectedBalance);
uint256 diff = balance - expectedBalance;
uint256 available = maxAvailablePerTx(_token);
require(available > 0);
if (diff > available) {
diff = available;
}
addTotalSpentPerDay(_token, getCurrentDay(), diff);
_setMediatorBalance(_token, expectedBalance.add(diff));
bytes memory data = abi.encodeWithSelector(this.handleBridgedTokens.selector, _token, _receiver, diff);
bytes32 _messageId = bridgeContract().requireToPassMessage(
mediatorContractOnOtherSide(),
data,
requestGasLimit()
);
setMessageToken(_messageId, _token);
setMessageValue(_messageId, diff);
setMessageRecipient(_messageId, _receiver);
}
/**
* @dev Tells the expected token balance of the contract.
* @param _token address of token contract.
* @return the current tracked token balance of the contract.
*/
function mediatorBalance(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("mediatorBalance", _token))];
}
/**
* @dev Returns message id where specified token was first seen and deploy on the other side was requested.
* @param _token address of token contract.
* @return message id of the send message.
*/
function tokenRegistrationMessageId(address _token) public view returns (bytes32) {
return bytes32(uintStorage[keccak256(abi.encodePacked("tokenRegistrationMessageId", _token))]);
}
/**
* @dev Updates expected token balance of the contract.
* @param _token address of token contract.
* @param _balance the new token balance of the contract.
*/
function _setMediatorBalance(address _token, uint256 _balance) internal {
uintStorage[keccak256(abi.encodePacked("mediatorBalance", _token))] = _balance;
}
/**
* @dev Updates message id where specified token was first seen and deploy on the other side was requested.
* @param _token address of token contract.
* @param _messageId message id of the send message.
*/
function _setTokenRegistrationMessageId(address _token, bytes32 _messageId) internal {
uintStorage[keccak256(abi.encodePacked("tokenRegistrationMessageId", _token))] = uint256(_messageId);
}
/**
* Internal function for unlocking some amount of tokens.
* In case of bridging STAKE token, the insufficient amount of tokens can be additionally minted.
*/
function _releaseTokens(address _token, address _recipient, uint256 _value) internal {
// It is necessary to use mediatorBalance(STAKE) instead of STAKE.balanceOf(this) to disallow user
// withdraw mistakenly locked funds (via regular transfer()) instead of minting new tokens.
// It should be possible to process mistakenly locked funds by calling fixMediatorBalance.
uint256 balance = mediatorBalance(_token);
// STAKE total supply on xDai can be higher than the native STAKE supply on Mainnet
// Omnibridge is allowed to mint extra native STAKE tokens.
if (_token == address(0x0Ae055097C6d159879521C384F1D2123D1f195e6) && balance < _value) {
// if all locked tokens were already withdrawn, mint new tokens directly to receiver
// mediatorBalance(STAKE) remains 0 in this case.
if (balance == 0) {
IBurnableMintableERC677Token(_token).mint(_recipient, _value);
return;
}
// otherwise, mint insufficient tokens to the contract
IBurnableMintableERC677Token(_token).mint(address(this), _value - balance);
balance = _value;
}
_token.safeTransfer(_recipient, _value);
_setMediatorBalance(_token, balance.sub(_value));
}
}
|
Unlock back the amount of tokens that were bridged to the other network but failed. _token address that bridged token contract. _recipient address that will receive the tokens. _value amount of tokens to be received./
|
function executeActionOnFixedTokens(address _token, address _recipient, uint256 _value) internal {
_releaseTokens(_token, _recipient, _value);
}
| 6,740,581
|
./full_match/11155111/0xf05d07d9A1cfDb65ebCbeB2771A62321C4cB87D1/sources/src/Governance/Treasury.sol
|
執行交易開啟分潤合約賠錢賣,暫不做事開啟分潤合約認賠不做事
|
function executeTransaction(uint256 _txIndex)
external
onlyOwner
txExists(_txIndex)
txNotExecuted(_txIndex){
Transaction storage transaction = transactions[_txIndex];
require(transaction.confirmedNum >= txRequireConfirmedNum, "can not execute tx.");
transaction.executed = true;
if (transaction.txType == TransactionType.BUY){
address targetToken = transaction.path[transaction.path.length-1];
investingETHValue[targetToken] += transaction.value;
investments.push(targetToken);
investingTokenAmount[targetToken] = uniswapV2Invest.getTokenBalance(targetToken);
address targetToken = transaction.path[0];
IERC20(targetToken).approve(address(uniswapV2Invest), investingTokenAmount[targetToken]);
uniswapV2Invest.swapExactTokensForETH(transaction.amount, 0, transaction.path);
uint256 standardETH = (investingETHValue[targetToken] * transaction.amount) / investingTokenAmount[targetToken];
if (receivedETH > standardETH){
uint256 revenue = receivedETH - standardETH;
uint256 snapshotId = trendToken.snapshot();
rewardsContract.push(address(revenueRewardsSharedByTokens));
}
if (uniswapV2Invest.getTokenBalance(targetToken) == 0){
investingTokenAmount[targetToken] =0;
investingETHValue[targetToken] =0;
removeInvestment(targetToken);
}
trendToken.approve(address(uniswapV2Invest), transaction.amount);
liquidityETHAmount += amountETH;
liquidityTokensAmount += amountToken;
liquidity += liquidityToken;
uniswapPair.approve(address(uniswapV2Invest), transaction.amount);
liquidity -= transaction.amount;
liquidityETHAmount -= amountETH;
liquidityTokensAmount -= amountToken;
if (amountETH > originETH){
uint256 revenue = amountETH - originETH;
uint256 snapshotId = trendToken.snapshot();
rewardsContract.push(address(revenueRewardsSharedByTokens));
}
uniswapPair = IUniswapPair(uniswapV2Invest.createPool());
}
emit ExecuteTransaction(msg.sender, transaction.txType, transaction.path, transaction.value, transaction.data, transaction.executed, transaction.confirmedNum);
}
| 3,794,336
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) {
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
// success determines whether the staticcall succeeded and result determines
// whether the contract at account indicates support of _interfaceId
(bool success, bool result) = _callERC165SupportsInterface(account, interfaceId);
return (success && result);
}
/**
* @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return success true if the STATICCALL succeeded, false otherwise
* @return result true if the STATICCALL succeeded and the contract at account
* indicates support of the interface with identifier interfaceId, false otherwise
*/
function _callERC165SupportsInterface(address account, bytes4 interfaceId)
private
view
returns (bool, bool)
{
bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId);
(bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams);
if (result.length < 32) return (false, false);
return (success, abi.decode(result, (bool)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, 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;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @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}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
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'
// solhint-disable-next-line max-line-length
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).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_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
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
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);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./IVaultHandler.sol";
import "./Orchestrator.sol";
/**
* @title ERC-20 TCAP Vault
* @author Cryptex.finance
* @notice Contract in charge of handling the TCAP Vault and stake using a Collateral ERC20
*/
contract ERC20VaultHandler is IVaultHandler {
/**
* @notice Constructor
* @param _orchestrator address
* @param _divisor uint256
* @param _ratio uint256
* @param _burnFee uint256
* @param _liquidationPenalty uint256
* @param _tcapOracle address
* @param _tcapAddress address
* @param _collateralAddress address
* @param _collateralOracle address
* @param _ethOracle address
* @param _rewardHandler address
* @param _treasury address
*/
constructor(
Orchestrator _orchestrator,
uint256 _divisor,
uint256 _ratio,
uint256 _burnFee,
uint256 _liquidationPenalty,
address _tcapOracle,
TCAP _tcapAddress,
address _collateralAddress,
address _collateralOracle,
address _ethOracle,
address _rewardHandler,
address _treasury
)
IVaultHandler(
_orchestrator,
_divisor,
_ratio,
_burnFee,
_liquidationPenalty,
_tcapOracle,
_tcapAddress,
_collateralAddress,
_collateralOracle,
_ethOracle,
_rewardHandler,
_treasury
)
{}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/introspection/IERC165.sol";
import "./TCAP.sol";
import "./Orchestrator.sol";
import "./oracles/ChainlinkOracle.sol";
interface IRewardHandler {
function stake(address _staker, uint256 amount) external;
function withdraw(address _staker, uint256 amount) external;
function getRewardFromVault(address _staker) external;
}
/**
* @title TCAP Vault Handler Abstract Contract
* @author Cryptex.Finance
* @notice Contract in charge of handling the TCAP Token and stake
*/
abstract contract IVaultHandler is
Ownable,
AccessControl,
ReentrancyGuard,
Pausable,
IERC165
{
/// @notice Open Zeppelin libraries
using SafeMath for uint256;
using SafeCast for int256;
using Counters for Counters.Counter;
using SafeERC20 for IERC20;
/**
* @notice Vault object created to manage the mint and burns of TCAP tokens
* @param Id, unique identifier of the vault
* @param Collateral, current collateral on vault
* @param Debt, current amount of TCAP tokens minted
* @param Owner, owner of the vault
*/
struct Vault {
uint256 Id;
uint256 Collateral;
uint256 Debt;
address Owner;
}
/// @notice Vault Id counter
Counters.Counter public counter;
/// @notice TCAP Token Address
TCAP public immutable TCAPToken;
/// @notice Total Market Cap/USD Oracle Address
ChainlinkOracle public immutable tcapOracle;
/// @notice Collateral Token Address
IERC20 public immutable collateralContract;
/// @notice Collateral/USD Oracle Address
ChainlinkOracle public immutable collateralPriceOracle;
/// @notice ETH/USD Oracle Address
ChainlinkOracle public immutable ETHPriceOracle;
/// @notice Value used as divisor with the total market cap, just like the S&P 500 or any major financial index would to define the final tcap token price
uint256 public divisor;
/// @notice Minimun ratio required to prevent liquidation of vault
uint256 public ratio;
/// @notice Fee percentage of the total amount to burn charged on ETH when burning TCAP Tokens
uint256 public burnFee;
/// @notice Penalty charged to vault owner when a vault is liquidated, this value goes to the liquidator
uint256 public liquidationPenalty;
/// @notice Address of the contract that gives rewards to minters of TCAP, rewards are only given if address is set in constructor
IRewardHandler public immutable rewardHandler;
/// @notice Address of the treasury contract (usually the timelock) where the funds generated by the protocol are sent
address public treasury;
/// @notice Owner address to Vault Id
mapping(address => uint256) public userToVault;
/// @notice Id To Vault
mapping(uint256 => Vault) public vaults;
/// @notice value used to multiply chainlink oracle for handling decimals
uint256 public constant oracleDigits = 10000000000;
/// @notice Minimum value that the ratio can be set to
uint256 public constant MIN_RATIO = 150;
/// @notice Maximum value that the burn fee can be set to
uint256 public constant MAX_FEE = 10;
/**
* @dev the computed interface ID according to ERC-165. The interface ID is a XOR of interface method selectors.
* setRatio.selector ^
* setBurnFee.selector ^
* setLiquidationPenalty.selector ^
* pause.selector ^
* unpause.selector => 0x9e75ab0c
*/
bytes4 private constant _INTERFACE_ID_IVAULT = 0x9e75ab0c;
/// @dev bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/// @notice An event emitted when the ratio is updated
event NewRatio(address indexed _owner, uint256 _ratio);
/// @notice An event emitted when the burn fee is updated
event NewBurnFee(address indexed _owner, uint256 _burnFee);
/// @notice An event emitted when the liquidation penalty is updated
event NewLiquidationPenalty(
address indexed _owner,
uint256 _liquidationPenalty
);
/// @notice An event emitted when the treasury contract is updated
event NewTreasury(address indexed _owner, address _tresury);
/// @notice An event emitted when a vault is created
event VaultCreated(address indexed _owner, uint256 indexed _id);
/// @notice An event emitted when collateral is added to a vault
event CollateralAdded(
address indexed _owner,
uint256 indexed _id,
uint256 _amount
);
/// @notice An event emitted when collateral is removed from a vault
event CollateralRemoved(
address indexed _owner,
uint256 indexed _id,
uint256 _amount
);
/// @notice An event emitted when tokens are minted
event TokensMinted(
address indexed _owner,
uint256 indexed _id,
uint256 _amount
);
/// @notice An event emitted when tokens are burned
event TokensBurned(
address indexed _owner,
uint256 indexed _id,
uint256 _amount
);
/// @notice An event emitted when a vault is liquidated
event VaultLiquidated(
uint256 indexed _vaultId,
address indexed _liquidator,
uint256 _liquidationCollateral,
uint256 _reward
);
/// @notice An event emitted when a erc20 token is recovered
event Recovered(address _token, uint256 _amount);
/**
* @notice Constructor
* @param _orchestrator address
* @param _divisor uint256
* @param _ratio uint256
* @param _burnFee uint256
* @param _liquidationPenalty uint256
* @param _tcapOracle address
* @param _tcapAddress address
* @param _collateralAddress address
* @param _collateralOracle address
* @param _ethOracle address
* @param _rewardHandler address
* @param _treasury address
*/
constructor(
Orchestrator _orchestrator,
uint256 _divisor,
uint256 _ratio,
uint256 _burnFee,
uint256 _liquidationPenalty,
address _tcapOracle,
TCAP _tcapAddress,
address _collateralAddress,
address _collateralOracle,
address _ethOracle,
address _rewardHandler,
address _treasury
) {
require(
_liquidationPenalty.add(100) < _ratio,
"VaultHandler::constructor: liquidation penalty too high"
);
require(
_ratio >= MIN_RATIO,
"VaultHandler::constructor: ratio lower than MIN_RATIO"
);
require(
_burnFee <= MAX_FEE,
"VaultHandler::constructor: burn fee higher than MAX_FEE"
);
divisor = _divisor;
ratio = _ratio;
burnFee = _burnFee;
liquidationPenalty = _liquidationPenalty;
tcapOracle = ChainlinkOracle(_tcapOracle);
collateralContract = IERC20(_collateralAddress);
collateralPriceOracle = ChainlinkOracle(_collateralOracle);
ETHPriceOracle = ChainlinkOracle(_ethOracle);
TCAPToken = _tcapAddress;
rewardHandler = IRewardHandler(_rewardHandler);
treasury = _treasury;
/// @dev counter starts in 1 as 0 is reserved for empty objects
counter.increment();
/// @dev transfer ownership to orchestrator
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
transferOwnership(address(_orchestrator));
}
/// @notice Reverts if the user hasn't created a vault.
modifier vaultExists() {
require(
userToVault[msg.sender] != 0,
"VaultHandler::vaultExists: no vault created"
);
_;
}
/// @notice Reverts if value is 0.
modifier notZero(uint256 _value) {
require(_value != 0, "VaultHandler::notZero: value can't be 0");
_;
}
/**
* @notice Sets the collateral ratio needed to mint tokens
* @param _ratio uint
* @dev Only owner can call it
*/
function setRatio(uint256 _ratio) external virtual onlyOwner {
require(
_ratio >= MIN_RATIO,
"VaultHandler::setRatio: ratio lower than MIN_RATIO"
);
ratio = _ratio;
emit NewRatio(msg.sender, _ratio);
}
/**
* @notice Sets the burn fee percentage an user pays when burning tcap tokens
* @param _burnFee uint
* @dev Only owner can call it
*/
function setBurnFee(uint256 _burnFee) external virtual onlyOwner {
require(
_burnFee <= MAX_FEE,
"VaultHandler::setBurnFee: burn fee higher than MAX_FEE"
);
burnFee = _burnFee;
emit NewBurnFee(msg.sender, _burnFee);
}
/**
* @notice Sets the liquidation penalty % charged on liquidation
* @param _liquidationPenalty uint
* @dev Only owner can call it
* @dev recommended value is between 1-15% and can't be above 100%
*/
function setLiquidationPenalty(uint256 _liquidationPenalty)
external
virtual
onlyOwner
{
require(
_liquidationPenalty.add(100) < ratio,
"VaultHandler::setLiquidationPenalty: liquidation penalty too high"
);
liquidationPenalty = _liquidationPenalty;
emit NewLiquidationPenalty(msg.sender, _liquidationPenalty);
}
/**
* @notice Sets the treasury contract address where fees are transfered to
* @param _treasury address
* @dev Only owner can call it
*/
function setTreasury(address _treasury) external virtual onlyOwner {
require(
_treasury != address(0),
"VaultHandler::setTreasury: not a valid treasury"
);
treasury = _treasury;
emit NewTreasury(msg.sender, _treasury);
}
/**
* @notice Allows an user to create an unique Vault
* @dev Only one vault per address can be created
*/
function createVault() external virtual whenNotPaused {
require(
userToVault[msg.sender] == 0,
"VaultHandler::createVault: vault already created"
);
uint256 id = counter.current();
userToVault[msg.sender] = id;
Vault memory vault = Vault(id, 0, 0, msg.sender);
vaults[id] = vault;
counter.increment();
emit VaultCreated(msg.sender, id);
}
/**
* @notice Allows users to add collateral to their vaults
* @param _amount of collateral to be added
* @dev _amount should be higher than 0
* @dev ERC20 token must be approved first
*/
function addCollateral(uint256 _amount)
external
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
require(
collateralContract.transferFrom(msg.sender, address(this), _amount),
"VaultHandler::addCollateral: ERC20 transfer did not succeed"
);
Vault storage vault = vaults[userToVault[msg.sender]];
vault.Collateral = vault.Collateral.add(_amount);
emit CollateralAdded(msg.sender, vault.Id, _amount);
}
/**
* @notice Allows users to remove collateral currently not being used to generate TCAP tokens from their vaults
* @param _amount of collateral to remove
* @dev reverts if the resulting ratio is less than the minimun ratio
* @dev _amount should be higher than 0
* @dev transfers the collateral back to the user
*/
function removeCollateral(uint256 _amount)
external
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
Vault storage vault = vaults[userToVault[msg.sender]];
uint256 currentRatio = getVaultRatio(vault.Id);
require(
vault.Collateral >= _amount,
"VaultHandler::removeCollateral: retrieve amount higher than collateral"
);
vault.Collateral = vault.Collateral.sub(_amount);
if (currentRatio != 0) {
require(
getVaultRatio(vault.Id) >= ratio,
"VaultHandler::removeCollateral: collateral below min required ratio"
);
}
require(
collateralContract.transfer(msg.sender, _amount),
"VaultHandler::removeCollateral: ERC20 transfer did not succeed"
);
emit CollateralRemoved(msg.sender, vault.Id, _amount);
}
/**
* @notice Uses collateral to generate debt on TCAP Tokens which are minted and assigend to caller
* @param _amount of tokens to mint
* @dev _amount should be higher than 0
* @dev requires to have a vault ratio above the minimum ratio
* @dev if reward handler is set stake to earn rewards
*/
function mint(uint256 _amount)
external
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
Vault storage vault = vaults[userToVault[msg.sender]];
uint256 collateral = requiredCollateral(_amount);
require(
vault.Collateral >= collateral,
"VaultHandler::mint: not enough collateral"
);
vault.Debt = vault.Debt.add(_amount);
require(
getVaultRatio(vault.Id) >= ratio,
"VaultHandler::mint: collateral below min required ratio"
);
if (address(rewardHandler) != address(0)) {
rewardHandler.stake(msg.sender, _amount);
}
TCAPToken.mint(msg.sender, _amount);
emit TokensMinted(msg.sender, vault.Id, _amount);
}
/**
* @notice Pays the debt of TCAP tokens resulting them on burn, this releases collateral up to minimun vault ratio
* @param _amount of tokens to burn
* @dev _amount should be higher than 0
* @dev A fee of exactly burnFee must be sent as value on ETH
* @dev The fee goes to the treasury contract
* @dev if reward handler is set exit rewards
*/
function burn(uint256 _amount)
external
payable
virtual
nonReentrant
vaultExists
whenNotPaused
notZero(_amount)
{
uint256 fee = getFee(_amount);
require(
msg.value >= fee,
"VaultHandler::burn: burn fee less than required"
);
Vault memory vault = vaults[userToVault[msg.sender]];
_burn(vault.Id, _amount);
if (address(rewardHandler) != address(0)) {
rewardHandler.withdraw(msg.sender, _amount);
rewardHandler.getRewardFromVault(msg.sender);
}
safeTransferETH(treasury, fee);
//send back ETH above fee
safeTransferETH(msg.sender, msg.value.sub(fee));
emit TokensBurned(msg.sender, vault.Id, _amount);
}
/**
* @notice Allow users to burn TCAP tokens to liquidate vaults with vault collateral ratio under the minium ratio, the liquidator receives the staked collateral of the liquidated vault at a premium
* @param _vaultId to liquidate
* @param _maxTCAP max amount of TCAP the liquidator is willing to pay to liquidate vault
* @dev Resulting ratio must be above or equal minimun ratio
* @dev A fee of exactly burnFee must be sent as value on ETH
* @dev The fee goes to the treasury contract
*/
function liquidateVault(uint256 _vaultId, uint256 _maxTCAP)
external
payable
nonReentrant
whenNotPaused
{
Vault storage vault = vaults[_vaultId];
require(vault.Id != 0, "VaultHandler::liquidateVault: no vault created");
uint256 vaultRatio = getVaultRatio(vault.Id);
require(
vaultRatio < ratio,
"VaultHandler::liquidateVault: vault is not liquidable"
);
uint256 requiredTCAP = requiredLiquidationTCAP(vault.Id);
require(
_maxTCAP >= requiredTCAP,
"VaultHandler::liquidateVault: liquidation amount different than required"
);
uint256 fee = getFee(requiredTCAP);
require(
msg.value >= fee,
"VaultHandler::liquidateVault: burn fee less than required"
);
uint256 reward = liquidationReward(vault.Id);
_burn(vault.Id, requiredTCAP);
//Removes the collateral that is rewarded to liquidator
vault.Collateral = vault.Collateral.sub(reward);
// Triggers update of CTX Rewards
if (address(rewardHandler) != address(0)) {
rewardHandler.withdraw(vault.Owner, requiredTCAP);
}
require(
collateralContract.transfer(msg.sender, reward),
"VaultHandler::liquidateVault: ERC20 transfer did not succeed"
);
safeTransferETH(treasury, fee);
//send back ETH above fee
safeTransferETH(msg.sender, msg.value.sub(fee));
emit VaultLiquidated(vault.Id, msg.sender, requiredTCAP, reward);
}
/**
* @notice Allows the owner to Pause the Contract
*/
function pause() external onlyOwner {
_pause();
}
/**
* @notice Allows the owner to Unpause the Contract
*/
function unpause() external onlyOwner {
_unpause();
}
/**
* @notice Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders
* @param _tokenAddress address
* @param _tokenAmount uint
* @dev Only owner can call it
*/
function recoverERC20(address _tokenAddress, uint256 _tokenAmount)
external
onlyOwner
{
// Cannot recover the collateral token
require(
_tokenAddress != address(collateralContract),
"Cannot withdraw the collateral tokens"
);
IERC20(_tokenAddress).safeTransfer(owner(), _tokenAmount);
emit Recovered(_tokenAddress, _tokenAmount);
}
/**
* @notice Allows the safe transfer of ETH
* @param _to account to transfer ETH
* @param _value amount of ETH
*/
function safeTransferETH(address _to, uint256 _value) internal {
(bool success, ) = _to.call{value: _value}(new bytes(0));
require(success, "ETHVaultHandler::safeTransferETH: ETH transfer failed");
}
/**
* @notice ERC165 Standard for support of interfaces
* @param _interfaceId bytes of interface
* @return bool
*/
function supportsInterface(bytes4 _interfaceId)
external
pure
override
returns (bool)
{
return (_interfaceId == _INTERFACE_ID_IVAULT ||
_interfaceId == _INTERFACE_ID_ERC165);
}
/**
* @notice Returns the Vault information of specified identifier
* @param _id of vault
* @return Id, Collateral, Owner, Debt
*/
function getVault(uint256 _id)
external
view
virtual
returns (
uint256,
uint256,
address,
uint256
)
{
Vault memory vault = vaults[_id];
return (vault.Id, vault.Collateral, vault.Owner, vault.Debt);
}
/**
* @notice Returns the price of the chainlink oracle multiplied by the digits to get 18 decimals format
* @param _oracle to be the price called
* @return price
*/
function getOraclePrice(ChainlinkOracle _oracle)
public
view
virtual
returns (uint256 price)
{
price = _oracle.getLatestAnswer().toUint256().mul(oracleDigits);
}
/**
* @notice Returns the price of the TCAP token
* @return price of the TCAP Token
* @dev TCAP token is 18 decimals
* @dev oracle totalMarketPrice must be in wei format
* @dev P = T / d
* P = TCAP Token Price
* T = Total Crypto Market Cap
* d = Divisor
*/
function TCAPPrice() public view virtual returns (uint256 price) {
uint256 totalMarketPrice = getOraclePrice(tcapOracle);
price = totalMarketPrice.div(divisor);
}
/**
* @notice Returns the minimal required collateral to mint TCAP token
* @param _amount uint amount to mint
* @return collateral of the TCAP Token
* @dev TCAP token is 18 decimals
* @dev C = ((P * A * r) / 100) / cp
* C = Required Collateral
* P = TCAP Token Price
* A = Amount to Mint
* cp = Collateral Price
* r = Minimun Ratio for Liquidation
* Is only divided by 100 as eth price comes in wei to cancel the additional 0s
*/
function requiredCollateral(uint256 _amount)
public
view
virtual
returns (uint256 collateral)
{
uint256 tcapPrice = TCAPPrice();
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
collateral = ((tcapPrice.mul(_amount).mul(ratio)).div(100)).div(
collateralPrice
);
}
/**
* @notice Returns the minimal required TCAP to liquidate a Vault
* @param _vaultId of the vault to liquidate
* @return amount required of the TCAP Token
* @dev LT = ((((D * r) / 100) - cTcap) * 100) / (r - (p + 100))
* cTcap = ((C * cp) / P)
* LT = Required TCAP
* D = Vault Debt
* C = Required Collateral
* P = TCAP Token Price
* cp = Collateral Price
* r = Min Vault Ratio
* p = Liquidation Penalty
*/
function requiredLiquidationTCAP(uint256 _vaultId)
public
view
virtual
returns (uint256 amount)
{
Vault memory vault = vaults[_vaultId];
uint256 tcapPrice = TCAPPrice();
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
uint256 collateralTcap =
(vault.Collateral.mul(collateralPrice)).div(tcapPrice);
uint256 reqDividend =
(((vault.Debt.mul(ratio)).div(100)).sub(collateralTcap)).mul(100);
uint256 reqDivisor = ratio.sub(liquidationPenalty.add(100));
amount = reqDividend.div(reqDivisor);
}
/**
* @notice Returns the Reward for liquidating a vault
* @param _vaultId of the vault to liquidate
* @return rewardCollateral for liquidating Vault
* @dev the returned value is returned as collateral currency
* @dev R = (LT * (p + 100)) / 100
* R = Liquidation Reward
* LT = Required Liquidation TCAP
* p = liquidation penalty
*/
function liquidationReward(uint256 _vaultId)
public
view
virtual
returns (uint256 rewardCollateral)
{
uint256 req = requiredLiquidationTCAP(_vaultId);
uint256 tcapPrice = TCAPPrice();
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
uint256 reward = (req.mul(liquidationPenalty.add(100)));
rewardCollateral = (reward.mul(tcapPrice)).div(collateralPrice.mul(100));
}
/**
* @notice Returns the Collateral Ratio of the Vault
* @param _vaultId id of vault
* @return currentRatio
* @dev vr = (cp * (C * 100)) / D * P
* vr = Vault Ratio
* C = Vault Collateral
* cp = Collateral Price
* D = Vault Debt
* P = TCAP Token Price
*/
function getVaultRatio(uint256 _vaultId)
public
view
virtual
returns (uint256 currentRatio)
{
Vault memory vault = vaults[_vaultId];
if (vault.Id == 0 || vault.Debt == 0) {
currentRatio = 0;
} else {
uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
currentRatio = (
(collateralPrice.mul(vault.Collateral.mul(100))).div(
vault.Debt.mul(TCAPPrice())
)
);
}
}
/**
* @notice Returns the required fee of ETH to burn the TCAP tokens
* @param _amount to burn
* @return fee
* @dev The returned value is returned in wei
* @dev f = (((P * A * b)/ 100))/ EP
* f = Burn Fee Value
* P = TCAP Token Price
* A = Amount to Burn
* b = Burn Fee %
* EP = ETH Price
*/
function getFee(uint256 _amount) public view virtual returns (uint256 fee) {
uint256 ethPrice = getOraclePrice(ETHPriceOracle);
fee = (TCAPPrice().mul(_amount).mul(burnFee)).div(100).div(ethPrice);
}
/**
* @notice Burns an amount of TCAP Tokens
* @param _vaultId vault id
* @param _amount to burn
*/
function _burn(uint256 _vaultId, uint256 _amount) internal {
Vault storage vault = vaults[_vaultId];
require(
vault.Debt >= _amount,
"VaultHandler::burn: amount greater than debt"
);
vault.Debt = vault.Debt.sub(_amount);
TCAPToken.burn(msg.sender, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/introspection/ERC165Checker.sol";
import "./IVaultHandler.sol";
import "./TCAP.sol";
import "./oracles/ChainlinkOracle.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title TCAP Orchestrator
* @author Cryptex.finance
* @notice Orchestrator contract in charge of managing the settings of the vaults, rewards and TCAP token. It acts as the owner of these contracts.
*/
contract Orchestrator is Ownable {
/// @dev Enum which saves the available functions to emergency call.
enum Functions {BURNFEE, LIQUIDATION, PAUSE}
/// @notice Address that can set to 0 the fees or pause the vaults in an emergency event
address public guardian;
/** @dev Interface constants*/
bytes4 private constant _INTERFACE_ID_IVAULT = 0x9e75ab0c;
bytes4 private constant _INTERFACE_ID_TCAP = 0xbd115939;
bytes4 private constant _INTERFACE_ID_CHAINLINK_ORACLE = 0x85be402b;
/// @dev tracks which vault was emergency called
mapping(IVaultHandler => mapping(Functions => bool)) private emergencyCalled;
/// @notice An event emitted when the guardian is updated
event GuardianSet(address indexed _owner, address guardian);
/// @notice An event emitted when a transaction is executed
event TransactionExecuted(
address indexed target,
uint256 value,
string signature,
bytes data
);
/**
* @notice Constructor
* @param _guardian The guardian address
*/
constructor(address _guardian) {
require(
_guardian != address(0),
"Orchestrator::constructor: guardian can't be zero"
);
guardian = _guardian;
}
/// @notice Throws if called by any account other than the guardian
modifier onlyGuardian() {
require(
msg.sender == guardian,
"Orchestrator::onlyGuardian: caller is not the guardian"
);
_;
}
/**
* @notice Throws if vault is not valid.
* @param _vault address
*/
modifier validVault(IVaultHandler _vault) {
require(
ERC165Checker.supportsInterface(address(_vault), _INTERFACE_ID_IVAULT),
"Orchestrator::validVault: not a valid vault"
);
_;
}
/**
* @notice Throws if TCAP Token is not valid
* @param _tcap address
*/
modifier validTCAP(TCAP _tcap) {
require(
ERC165Checker.supportsInterface(address(_tcap), _INTERFACE_ID_TCAP),
"Orchestrator::validTCAP: not a valid TCAP ERC20"
);
_;
}
/**
* @notice Throws if Chainlink Oracle is not valid
* @param _oracle address
*/
modifier validChainlinkOracle(address _oracle) {
require(
ERC165Checker.supportsInterface(
address(_oracle),
_INTERFACE_ID_CHAINLINK_ORACLE
),
"Orchestrator::validChainlinkOrchestrator: not a valid Chainlink Oracle"
);
_;
}
/**
* @notice Sets the guardian of the orchestrator
* @param _guardian address of the guardian
* @dev Only owner can call it
*/
function setGuardian(address _guardian) external onlyOwner {
require(
_guardian != address(0),
"Orchestrator::setGuardian: guardian can't be zero"
);
guardian = _guardian;
emit GuardianSet(msg.sender, _guardian);
}
/**
* @notice Sets the ratio of a vault
* @param _vault address
* @param _ratio value
* @dev Only owner can call it
*/
function setRatio(IVaultHandler _vault, uint256 _ratio)
external
onlyOwner
validVault(_vault)
{
_vault.setRatio(_ratio);
}
/**
* @notice Sets the burn fee of a vault
* @param _vault address
* @param _burnFee value
* @dev Only owner can call it
*/
function setBurnFee(IVaultHandler _vault, uint256 _burnFee)
external
onlyOwner
validVault(_vault)
{
_vault.setBurnFee(_burnFee);
}
/**
* @notice Sets the burn fee to 0, only used on a black swan event
* @param _vault address
* @dev Only guardian can call it
* @dev Validates if _vault is valid
*/
function setEmergencyBurnFee(IVaultHandler _vault)
external
onlyGuardian
validVault(_vault)
{
require(
emergencyCalled[_vault][Functions.BURNFEE] != true,
"Orchestrator::setEmergencyBurnFee: emergency call already used"
);
emergencyCalled[_vault][Functions.BURNFEE] = true;
_vault.setBurnFee(0);
}
/**
* @notice Sets the liquidation penalty of a vault
* @param _vault address
* @param _liquidationPenalty value
* @dev Only owner can call it
*/
function setLiquidationPenalty(
IVaultHandler _vault,
uint256 _liquidationPenalty
) external onlyOwner validVault(_vault) {
_vault.setLiquidationPenalty(_liquidationPenalty);
}
/**
* @notice Sets the liquidation penalty of a vault to 0, only used on a black swan event
* @param _vault address
* @dev Only guardian can call it
* @dev Validates if _vault is valid
*/
function setEmergencyLiquidationPenalty(IVaultHandler _vault)
external
onlyGuardian
validVault(_vault)
{
require(
emergencyCalled[_vault][Functions.LIQUIDATION] != true,
"Orchestrator::setEmergencyLiquidationPenalty: emergency call already used"
);
emergencyCalled[_vault][Functions.LIQUIDATION] = true;
_vault.setLiquidationPenalty(0);
}
/**
* @notice Pauses the Vault
* @param _vault address
* @dev Only guardian can call it
* @dev Validates if _vault is valid
*/
function pauseVault(IVaultHandler _vault)
external
onlyGuardian
validVault(_vault)
{
require(
emergencyCalled[_vault][Functions.PAUSE] != true,
"Orchestrator::pauseVault: emergency call already used"
);
emergencyCalled[_vault][Functions.PAUSE] = true;
_vault.pause();
}
/**
* @notice Unpauses the Vault
* @param _vault address
* @dev Only guardian can call it
* @dev Validates if _vault is valid
*/
function unpauseVault(IVaultHandler _vault)
external
onlyGuardian
validVault(_vault)
{
_vault.unpause();
}
/**
* @notice Enables or disables the TCAP Cap
* @param _tcap address
* @param _enable bool
* @dev Only owner can call it
* @dev Validates if _tcap is valid
*/
function enableTCAPCap(TCAP _tcap, bool _enable)
external
onlyOwner
validTCAP(_tcap)
{
_tcap.enableCap(_enable);
}
/**
* @notice Sets the TCAP maximum minting value
* @param _tcap address
* @param _cap uint value
* @dev Only owner can call it
* @dev Validates if _tcap is valid
*/
function setTCAPCap(TCAP _tcap, uint256 _cap)
external
onlyOwner
validTCAP(_tcap)
{
_tcap.setCap(_cap);
}
/**
* @notice Adds Vault to TCAP ERC20
* @param _tcap address
* @param _vault address
* @dev Only owner can call it
* @dev Validates if _tcap is valid
* @dev Validates if _vault is valid
*/
function addTCAPVault(TCAP _tcap, IVaultHandler _vault)
external
onlyOwner
validTCAP(_tcap)
validVault(_vault)
{
_tcap.addVaultHandler(address(_vault));
}
/**
* @notice Removes Vault to TCAP ERC20
* @param _tcap address
* @param _vault address
* @dev Only owner can call it
* @dev Validates if _tcap is valid
* @dev Validates if _vault is valid
*/
function removeTCAPVault(TCAP _tcap, IVaultHandler _vault)
external
onlyOwner
validTCAP(_tcap)
validVault(_vault)
{
_tcap.removeVaultHandler(address(_vault));
}
/**
* @notice Allows the owner to execute custom transactions
* @param target address
* @param value uint256
* @param signature string
* @param data bytes
* @dev Only owner can call it
*/
function executeTransaction(
address target,
uint256 value,
string memory signature,
bytes memory data
) external payable onlyOwner returns (bytes memory) {
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
require(
target != address(0),
"Orchestrator::executeTransaction: target can't be zero"
);
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) =
target.call{value: value}(callData);
require(
success,
"Orchestrator::executeTransaction: Transaction execution reverted."
);
emit TransactionExecuted(target, value, signature, data);
(target, value, signature, data);
return returnData;
}
/**
* @notice Retrieves the eth stuck on the orchestrator
* @param _to address
* @dev Only owner can call it
*/
function retrieveETH(address _to) external onlyOwner {
require(
_to != address(0),
"Orchestrator::retrieveETH: address can't be zero"
);
uint256 amount = address(this).balance;
payable(_to).transfer(amount);
}
/// @notice Allows the contract to receive ETH
receive() external payable {}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/introspection/IERC165.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./Orchestrator.sol";
/**
* @title Total Market Cap Token
* @author Cryptex.finance
* @notice ERC20 token on the Ethereum Blockchain that provides total exposure to the cryptocurrency sector.
*/
contract TCAP is ERC20, Ownable, IERC165 {
/// @notice Open Zeppelin libraries
using SafeMath for uint256;
/// @notice if enabled TCAP can't be minted if the total supply is above or equal the cap value
bool public capEnabled = false;
/// @notice Maximum value the total supply of TCAP
uint256 public cap;
/**
* @notice Address to Vault Handler
* @dev Only vault handlers can mint and burn TCAP
*/
mapping(address => bool) public vaultHandlers;
/**
* @dev the computed interface ID according to ERC-165. The interface ID is a XOR of interface method selectors.
* mint.selector ^
* burn.selector ^
* setCap.selector ^
* enableCap.selector ^
* transfer.selector ^
* transferFrom.selector ^
* addVaultHandler.selector ^
* removeVaultHandler.selector ^
* approve.selector => 0xbd115939
*/
bytes4 private constant _INTERFACE_ID_TCAP = 0xbd115939;
/// @dev bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/// @notice An event emitted when a vault handler is added
event VaultHandlerAdded(
address indexed _owner,
address indexed _tokenHandler
);
/// @notice An event emitted when a vault handler is removed
event VaultHandlerRemoved(
address indexed _owner,
address indexed _tokenHandler
);
/// @notice An event emitted when the cap value is updated
event NewCap(address indexed _owner, uint256 _amount);
/// @notice An event emitted when the cap is enabled or disabled
event NewCapEnabled(address indexed _owner, bool _enable);
/**
* @notice Constructor
* @param _name uint256
* @param _symbol uint256
* @param _cap uint256
* @param _orchestrator address
*/
constructor(
string memory _name,
string memory _symbol,
uint256 _cap,
Orchestrator _orchestrator
) ERC20(_name, _symbol) {
cap = _cap;
/// @dev transfer ownership to orchestrator
transferOwnership(address(_orchestrator));
}
/// @notice Reverts if called by any account that is not a vault.
modifier onlyVault() {
require(
vaultHandlers[msg.sender],
"TCAP::onlyVault: caller is not a vault"
);
_;
}
/**
* @notice Adds a new address as a vault
* @param _vaultHandler address of a contract with permissions to mint and burn tokens
* @dev Only owner can call it
*/
function addVaultHandler(address _vaultHandler) external onlyOwner {
vaultHandlers[_vaultHandler] = true;
emit VaultHandlerAdded(msg.sender, _vaultHandler);
}
/**
* @notice Removes an address as a vault
* @param _vaultHandler address of the contract to be removed as vault
* @dev Only owner can call it
*/
function removeVaultHandler(address _vaultHandler) external onlyOwner {
vaultHandlers[_vaultHandler] = false;
emit VaultHandlerRemoved(msg.sender, _vaultHandler);
}
/**
* @notice Mints TCAP Tokens
* @param _account address of the receiver of tokens
* @param _amount uint of tokens to mint
* @dev Only vault can call it
*/
function mint(address _account, uint256 _amount) external onlyVault {
_mint(_account, _amount);
}
/**
* @notice Burns TCAP Tokens
* @param _account address of the account which is burning tokens.
* @param _amount uint of tokens to burn
* @dev Only vault can call it
*/
function burn(address _account, uint256 _amount) external onlyVault {
_burn(_account, _amount);
}
/**
* @notice Sets maximum value the total supply of TCAP can have
* @param _cap value
* @dev When capEnabled is true, mint is not allowed to issue tokens that would increase the total supply above or equal the specified capacity.
* @dev Only owner can call it
*/
function setCap(uint256 _cap) external onlyOwner {
cap = _cap;
emit NewCap(msg.sender, _cap);
}
/**
* @notice Enables or Disables the Total Supply Cap.
* @param _enable value
* @dev When capEnabled is true, minting will not be allowed above the max capacity. It can exist a supply above the cap, but it prevents minting above the cap.
* @dev Only owner can call it
*/
function enableCap(bool _enable) external onlyOwner {
capEnabled = _enable;
emit NewCapEnabled(msg.sender, _enable);
}
/**
* @notice ERC165 Standard for support of interfaces
* @param _interfaceId bytes of interface
* @return bool
*/
function supportsInterface(bytes4 _interfaceId)
external
pure
override
returns (bool)
{
return (_interfaceId == _INTERFACE_ID_TCAP ||
_interfaceId == _INTERFACE_ID_ERC165);
}
/**
* @notice executes before each token transfer or mint
* @param _from address
* @param _to address
* @param _amount value to transfer
* @dev See {ERC20-_beforeTokenTransfer}.
* @dev minted tokens must not cause the total supply to go over the cap.
* @dev Reverts if the to address is equal to token address
*/
function _beforeTokenTransfer(
address _from,
address _to,
uint256 _amount
) internal virtual override {
super._beforeTokenTransfer(_from, _to, _amount);
require(
_to != address(this),
"TCAP::transfer: can't transfer to TCAP contract"
);
if (_from == address(0) && capEnabled) {
// When minting tokens
require(
totalSupply().add(_amount) <= cap,
"TCAP::Transfer: TCAP cap exceeded"
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/introspection/IERC165.sol";
/**
* @title Chainlink Oracle
* @author Cryptex.finance
* @notice Contract in charge or reading the information from a Chainlink Oracle. TCAP contracts read the price directly from this contract. More information can be found on Chainlink Documentation
*/
contract ChainlinkOracle is Ownable, IERC165 {
AggregatorV3Interface internal aggregatorContract;
/*
* setReferenceContract.selector ^
* getLatestAnswer.selector ^
* getLatestTimestamp.selector ^
* getPreviousAnswer.selector ^
* getPreviousTimestamp.selector => 0x85be402b
*/
bytes4 private constant _INTERFACE_ID_CHAINLINK_ORACLE = 0x85be402b;
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @notice Called once the contract is deployed.
* Set the Chainlink Oracle as an aggregator.
*/
constructor(address _aggregator, address _timelock) {
require(_aggregator != address(0) && _timelock != address(0), "address can't be 0");
aggregatorContract = AggregatorV3Interface(_aggregator);
transferOwnership(_timelock);
}
/**
* @notice Changes the reference contract.
* @dev Only owner can call it.
*/
function setReferenceContract(address _aggregator) public onlyOwner() {
aggregatorContract = AggregatorV3Interface(_aggregator);
}
/**
* @notice Returns the latest answer from the reference contract.
* @return price
*/
function getLatestAnswer() public view returns (int256) {
(
uint80 roundID,
int256 price,
,
uint256 timeStamp,
uint80 answeredInRound
) = aggregatorContract.latestRoundData();
require(
timeStamp != 0,
"ChainlinkOracle::getLatestAnswer: round is not complete"
);
require(
answeredInRound >= roundID,
"ChainlinkOracle::getLatestAnswer: stale data"
);
return price;
}
/**
* @notice Returns the latest round from the reference contract.
*/
function getLatestRound()
public
view
returns (
uint80,
int256,
uint256,
uint256,
uint80
)
{
(
uint80 roundID,
int256 price,
uint256 startedAt,
uint256 timeStamp,
uint80 answeredInRound
) = aggregatorContract.latestRoundData();
return (roundID, price, startedAt, timeStamp, answeredInRound);
}
/**
* @notice Returns a given round from the reference contract.
* @param _id of round
*/
function getRound(uint80 _id)
public
view
returns (
uint80,
int256,
uint256,
uint256,
uint80
)
{
(
uint80 roundID,
int256 price,
uint256 startedAt,
uint256 timeStamp,
uint80 answeredInRound
) = aggregatorContract.getRoundData(_id);
return (roundID, price, startedAt, timeStamp, answeredInRound);
}
/**
* @notice Returns the last time the Oracle was updated.
*/
function getLatestTimestamp() public view returns (uint256) {
(, , , uint256 timeStamp, ) = aggregatorContract.latestRoundData();
return timeStamp;
}
/**
* @notice Returns a previous answer updated on the Oracle.
* @param _id of round
* @return price
*/
function getPreviousAnswer(uint80 _id) public view returns (int256) {
(uint80 roundID, int256 price, , , ) = aggregatorContract.getRoundData(_id);
require(
_id <= roundID,
"ChainlinkOracle::getPreviousAnswer: not enough history"
);
return price;
}
/**
* @notice Returns a previous time the Oracle was updated.
* @param _id of round
* @return timeStamp
*/
function getPreviousTimestamp(uint80 _id) public view returns (uint256) {
(uint80 roundID, , , uint256 timeStamp, ) =
aggregatorContract.getRoundData(_id);
require(
_id <= roundID,
"ChainlinkOracle::getPreviousTimestamp: not enough history"
);
return timeStamp;
}
/**
* @notice ERC165 Standard for support of interfaces.
*/
function supportsInterface(bytes4 interfaceId)
external
pure
override
returns (bool)
{
return (interfaceId == _INTERFACE_ID_CHAINLINK_ORACLE ||
interfaceId == _INTERFACE_ID_ERC165);
}
}
|
ERC165 Standard for support of interfaces _interfaceId bytes of interface return bool/
|
function supportsInterface(bytes4 _interfaceId)
external
pure
override
returns (bool)
{
return (_interfaceId == _INTERFACE_ID_TCAP ||
_interfaceId == _INTERFACE_ID_ERC165);
}
| 172,420
|
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.7.5;
pragma experimental ABIEncoderV2;
/* Interface Imports */
import { iL1NFTBridge } from "./interfaces/iL1NFTBridge.sol";
import { iL2NFTBridge } from "./interfaces/iL2NFTBridge.sol";
import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import { IERC721Metadata } from "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
/* Library Imports */
import { CrossDomainEnabled } from "@eth-optimism/contracts/contracts/libraries/bridge/CrossDomainEnabled.sol";
import { Lib_PredeployAddresses } from "@eth-optimism/contracts/contracts/libraries/constants/Lib_PredeployAddresses.sol";
import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { ERC721Holder } from "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import { ERC165Checker } from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
/* Contract Imports */
import { IL1StandardERC721 } from "../standards/IL1StandardERC721.sol";
import { iSupportBridgeExtraData } from "./interfaces/iSupportBridgeExtraData.sol";
/* External Imports */
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
/**
* @title L1NFTBridge
* @dev The L1 NFT Bridge is a contract which stores deposited L1 ERC721
* tokens that are in use on L2. It synchronizes a corresponding L2 Bridge, informing it of deposits
* and listening to it for newly finalized withdrawals.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract L1NFTBridge is iL1NFTBridge, CrossDomainEnabled, ERC721Holder, ReentrancyGuardUpgradeable, PausableUpgradeable {
using SafeMath for uint;
/********************************
* External Contract References *
********************************/
address public owner;
address public l2NFTBridge;
// Default gas value which can be overridden if more complex logic runs on L2.
uint32 public depositL2Gas;
enum Network { L1, L2 }
// Info of each NFT
struct PairNFTInfo {
address l1Contract;
address l2Contract;
Network baseNetwork; // L1 or L2
}
// Maps L1 token to tokenId to L2 token contract deposited for the native L1 NFT
mapping(address => mapping (uint256 => address)) public deposits;
// Maps L1 NFT address to NFTInfo
mapping(address => PairNFTInfo) public pairNFTInfo;
/***************
* Constructor *
***************/
// This contract lives behind a proxy, so the constructor parameters will go unused.
constructor()
CrossDomainEnabled(address(0))
{}
/**********************
* Function Modifiers *
**********************/
modifier onlyOwner() {
require(msg.sender == owner, 'Caller is not the owner');
_;
}
modifier onlyInitialized() {
require(address(messenger) != address(0), "Contract has not yet been initialized");
_;
}
/******************
* Initialization *
******************/
/**
* @dev transfer ownership
*
* @param _newOwner new owner of this contract
*/
function transferOwnership(
address _newOwner
)
public
onlyOwner()
onlyInitialized()
{
owner = _newOwner;
}
/**
* @dev Configure gas.
*
* @param _depositL2Gas default finalized deposit L2 Gas
*/
function configureGas(
uint32 _depositL2Gas
)
public
onlyOwner()
onlyInitialized()
{
depositL2Gas = _depositL2Gas;
}
/**
* @param _l1messenger L1 Messenger address being used for cross-chain communications.
* @param _l2NFTBridge L2 NFT bridge address.
*/
function initialize(
address _l1messenger,
address _l2NFTBridge
)
public
initializer()
{
require(_l1messenger != address(0) && _l2NFTBridge != address(0), "zero address not allowed");
messenger = _l1messenger;
l2NFTBridge = _l2NFTBridge;
owner = msg.sender;
configureGas(1400000);
__Context_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
}
/***
* @dev Add the new NFT pair to the pool
* DO NOT add the same NFT token more than once.
*
* @param _l1Contract L1 NFT contract address
* @param _l2Contract L2 NFT contract address
* @param _baseNetwork Network where the NFT contract was created
*
*/
function registerNFTPair(
address _l1Contract,
address _l2Contract,
string memory _baseNetwork
)
public
onlyOwner()
{
//create2 would prevent this check
//require(_l1Contract != _l2Contract, "Contracts should not be the same");
bytes4 erc721 = 0x80ac58cd;
require(ERC165Checker.supportsInterface(_l1Contract, erc721), "L1 NFT is not ERC721 compatible");
bytes32 bn = keccak256(abi.encodePacked(_baseNetwork));
bytes32 l1 = keccak256(abi.encodePacked("L1"));
bytes32 l2 = keccak256(abi.encodePacked("L2"));
// l2 NFT address equal to zero, then pair is not registered yet.
// use with caution, can register only once
PairNFTInfo storage pairNFT = pairNFTInfo[_l1Contract];
require(pairNFT.l2Contract == address(0), "L2 NFT address already registered");
// _baseNetwork can only be L1 or L2
require(bn == l1 || bn == l2, "Invalid Network");
Network baseNetwork;
if (bn == l1) {
baseNetwork = Network.L1;
}
else {
require(ERC165Checker.supportsInterface(_l1Contract, 0xec88b5ce), "L1 contract is not bridgable");
baseNetwork = Network.L2;
}
pairNFTInfo[_l1Contract] =
PairNFTInfo({
l1Contract: _l1Contract,
l2Contract: _l2Contract,
baseNetwork: baseNetwork
});
}
/**************
* Depositing *
**************/
// /**
// * @inheritdoc iL1NFTBridge
// */
function depositNFT(
address _l1Contract,
uint256 _tokenId,
uint32 _l2Gas
)
external
virtual
override
nonReentrant()
whenNotPaused()
{
_initiateNFTDeposit(_l1Contract, msg.sender, msg.sender, _tokenId, _l2Gas, "");
}
// /**
// * @inheritdoc iL1NFTBridge
// */
function depositNFTTo(
address _l1Contract,
address _to,
uint256 _tokenId,
uint32 _l2Gas
)
external
virtual
override
nonReentrant()
whenNotPaused()
{
_initiateNFTDeposit(_l1Contract, msg.sender, _to, _tokenId, _l2Gas, "");
}
// /**
// * @inheritdoc iL1NFTBridge
// */
function depositNFTWithExtraData(
address _l1Contract,
uint256 _tokenId,
uint32 _l2Gas
)
external
virtual
override
nonReentrant()
whenNotPaused()
{
bytes memory extraData;
// if token has base on this layer
if (pairNFTInfo[_l1Contract].baseNetwork == Network.L1) {
// check the existence of bridgeExtraData(uint256) on l1Contract
if (ERC165Checker.supportsInterface(_l1Contract, 0x9b9284f9)) {
extraData = iSupportBridgeExtraData(_l1Contract).bridgeExtraData(_tokenId);
} else {
// otherwise send tokenURI return (encoded in bytes)
// allow to fail if the call fails
extraData = abi.encode(IERC721Metadata(_l1Contract).tokenURI(_tokenId));
}
}
// size limits unchecked
_initiateNFTDeposit(_l1Contract, msg.sender, msg.sender, _tokenId, _l2Gas, extraData);
}
// /**
// * @inheritdoc iL1NFTBridge
// */
function depositNFTWithExtraDataTo(
address _l1Contract,
address _to,
uint256 _tokenId,
uint32 _l2Gas
)
external
virtual
override
nonReentrant()
whenNotPaused()
{
bytes memory extraData;
// if token has base on this layer
if (pairNFTInfo[_l1Contract].baseNetwork == Network.L1) {
// check the existence of bridgeExtraData(uint256) on l1Contract
if (ERC165Checker.supportsInterface(_l1Contract, 0x9b9284f9)) {
extraData = iSupportBridgeExtraData(_l1Contract).bridgeExtraData(_tokenId);
} else {
// otherwise send tokenURI return (encoded in bytes)
// allow to fail if the call fails
extraData = abi.encode(IERC721Metadata(_l1Contract).tokenURI(_tokenId));
}
}
// size limits unchecked
_initiateNFTDeposit(_l1Contract, msg.sender, _to, _tokenId, _l2Gas, extraData);
}
/**
* @dev Performs the logic for deposits by informing the L2 Deposited Token
* contract of the deposit and calling a handler to lock the L1 token. (e.g. transferFrom)
*
* @param _l1Contract Address of the L1 NFT contract we are depositing
* @param _from Account to pull the deposit from on L1
* @param _to Account to give the deposit to on L2
* @param _tokenId NFT token Id to deposit.
* @param _l2Gas Gas limit required to complete the deposit on L2.
* @param _data Data/metadata to forward to L2. This data is either extraBridgeData,
* or encoded tokenURI, in this order of priority if user choses to send, is empty otherwise
*/
function _initiateNFTDeposit(
address _l1Contract,
address _from,
address _to,
uint256 _tokenId,
uint32 _l2Gas,
bytes memory _data
)
internal
{
PairNFTInfo storage pairNFT = pairNFTInfo[_l1Contract];
require(pairNFT.l2Contract != address(0), "Can't Find L2 NFT Contract");
if (pairNFT.baseNetwork == Network.L1) {
// This check could be bypassed by a malicious contract via initcode,
// but it takes care of the user error we want to avoid.
require(!Address.isContract(msg.sender), "Account not EOA");
// When a deposit is initiated on L1, the L1 Bridge transfers the funds to itself for future
// withdrawals. safeTransferFrom also checks if the contract has code, so this will fail if
// _from is an EOA or address(0).
IERC721(_l1Contract).safeTransferFrom(
_from,
address(this),
_tokenId
);
// Construct calldata for _l2Contract.finalizeDeposit(_to, _amount)
bytes memory message = abi.encodeWithSelector(
iL2NFTBridge.finalizeDeposit.selector,
_l1Contract,
pairNFT.l2Contract,
_from,
_to,
_tokenId,
_data
);
// Send calldata into L2
sendCrossDomainMessage(
l2NFTBridge,
_l2Gas,
message
);
deposits[_l1Contract][_tokenId] = pairNFT.l2Contract;
} else {
address l2Contract = IL1StandardERC721(_l1Contract).l2Contract();
require(pairNFT.l2Contract == l2Contract, "L2 NFT Contract Address Error");
// When a withdrawal is initiated, we burn the withdrawer's funds to prevent subsequent L2
// usage
address NFTOwner = IL1StandardERC721(_l1Contract).ownerOf(_tokenId);
require(
msg.sender == NFTOwner || IL1StandardERC721(_l1Contract).getApproved(_tokenId) == msg.sender ||
IL1StandardERC721(_l1Contract).isApprovedForAll(NFTOwner, msg.sender)
);
IL1StandardERC721(_l1Contract).burn(_tokenId);
// Construct calldata for l2NFTBridge.finalizeDeposit(_to, _amount)
bytes memory message;
message = abi.encodeWithSelector(
iL2NFTBridge.finalizeDeposit.selector,
_l1Contract,
l2Contract,
_from,
_to,
_tokenId,
_data
);
// Send calldata into L2
sendCrossDomainMessage(
l2NFTBridge,
_l2Gas,
message
);
}
emit NFTDepositInitiated(_l1Contract, pairNFT.l2Contract, _from, _to, _tokenId, _data);
}
// /**
// * @inheritdoc iL1NFTBridge
// */
function finalizeNFTWithdrawal(
address _l1Contract,
address _l2Contract,
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
)
external
override
onlyFromCrossDomainAccount(l2NFTBridge)
{
PairNFTInfo storage pairNFT = pairNFTInfo[_l1Contract];
if (pairNFT.baseNetwork == Network.L1) {
// needs to verify comes from correct l2Contract
require(deposits[_l1Contract][_tokenId] == _l2Contract, "Incorrect Burn");
// When a withdrawal is finalized on L1, the L1 Bridge transfers the funds to the withdrawer
IERC721(_l1Contract).safeTransferFrom(address(this), _to, _tokenId);
emit NFTWithdrawalFinalized(_l1Contract, _l2Contract, _from, _to, _tokenId, _data);
} else {
// Check the target token is compliant and
// verify the deposited token on L2 matches the L1 deposited token representation here
if (
// check with interface of IL1StandardERC721
ERC165Checker.supportsInterface(_l1Contract, 0xec88b5ce) &&
_l2Contract == IL1StandardERC721(_l1Contract).l2Contract()
) {
// When a deposit is finalized, we credit the account on L2 with the same amount of
// tokens.
IL1StandardERC721(_l1Contract).mint(_to, _tokenId, _data);
emit NFTWithdrawalFinalized(_l1Contract, _l2Contract, _from, _to, _tokenId, _data);
} else {
bytes memory message = abi.encodeWithSelector(
iL2NFTBridge.finalizeDeposit.selector,
_l1Contract,
_l2Contract,
_to, // switched the _to and _from here to bounce back the deposit to the sender
_from,
_tokenId,
_data
);
// Send message up to L1 bridge
sendCrossDomainMessage(
l2NFTBridge,
depositL2Gas,
message
);
emit NFTWithdrawalFailed(_l1Contract, _l2Contract, _from, _to, _tokenId, _data);
}
}
}
/******************
* Pause *
******************/
/**
* Pause contract
*/
function pause() external onlyOwner() {
_pause();
}
/**
* UnPause contract
*/
function unpause() external onlyOwner() {
_unpause();
}
}
|
Performs the logic for deposits by informing the L2 Deposited Token contract of the deposit and calling a handler to lock the L1 token. (e.g. transferFrom) _l1Contract Address of the L1 NFT contract we are depositing _from Account to pull the deposit from on L1 _to Account to give the deposit to on L2 _tokenId NFT token Id to deposit. _l2Gas Gas limit required to complete the deposit on L2. _data Data/metadata to forward to L2. This data is either extraBridgeData, or encoded tokenURI, in this order of priority if user choses to send, is empty otherwise/ This check could be bypassed by a malicious contract via initcode, but it takes care of the user error we want to avoid. When a deposit is initiated on L1, the L1 Bridge transfers the funds to itself for future withdrawals. safeTransferFrom also checks if the contract has code, so this will fail if _from is an EOA or address(0). Construct calldata for _l2Contract.finalizeDeposit(_to, _amount) Send calldata into L2 When a withdrawal is initiated, we burn the withdrawer's funds to prevent subsequent L2 usage Construct calldata for l2NFTBridge.finalizeDeposit(_to, _amount) Send calldata into L2
|
function _initiateNFTDeposit(
address _l1Contract,
address _from,
address _to,
uint256 _tokenId,
uint32 _l2Gas,
bytes memory _data
)
internal
{
PairNFTInfo storage pairNFT = pairNFTInfo[_l1Contract];
require(pairNFT.l2Contract != address(0), "Can't Find L2 NFT Contract");
if (pairNFT.baseNetwork == Network.L1) {
require(!Address.isContract(msg.sender), "Account not EOA");
IERC721(_l1Contract).safeTransferFrom(
_from,
address(this),
_tokenId
);
bytes memory message = abi.encodeWithSelector(
iL2NFTBridge.finalizeDeposit.selector,
_l1Contract,
pairNFT.l2Contract,
_from,
_to,
_tokenId,
_data
);
sendCrossDomainMessage(
l2NFTBridge,
_l2Gas,
message
);
deposits[_l1Contract][_tokenId] = pairNFT.l2Contract;
address l2Contract = IL1StandardERC721(_l1Contract).l2Contract();
require(pairNFT.l2Contract == l2Contract, "L2 NFT Contract Address Error");
address NFTOwner = IL1StandardERC721(_l1Contract).ownerOf(_tokenId);
require(
msg.sender == NFTOwner || IL1StandardERC721(_l1Contract).getApproved(_tokenId) == msg.sender ||
IL1StandardERC721(_l1Contract).isApprovedForAll(NFTOwner, msg.sender)
);
IL1StandardERC721(_l1Contract).burn(_tokenId);
bytes memory message;
message = abi.encodeWithSelector(
iL2NFTBridge.finalizeDeposit.selector,
_l1Contract,
l2Contract,
_from,
_to,
_tokenId,
_data
);
sendCrossDomainMessage(
l2NFTBridge,
_l2Gas,
message
);
}
emit NFTDepositInitiated(_l1Contract, pairNFT.l2Contract, _from, _to, _tokenId, _data);
}
| 13,054,819
|
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
import "OpenZeppelin/openzeppelin-contracts@4.1.0/contracts/access/Ownable.sol";
import "../interfaces/IERC2981.sol";
import "./Token.sol";
/**
* @title NFT Marketplace with ERC-2981 support
* @notice Defines a marketplace to bid on and sell NFTs.
* Sends royalties to rightsholder on each sale if applicable.
*/
contract Marketplace {
struct SellOffer {
address seller;
uint256 minPrice;
}
struct BuyOffer {
address buyer;
uint256 price;
uint256 createTime;
}
bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
// Store the address of the contract of the NFT to trade. Can be changed in
// constructor or with a call to setTokenContractAddress.
address public _tokenContractAddress = address(0);
// Store all active sell offers and maps them to their respective token ids
mapping(uint256 => SellOffer) public activeSellOffers;
// Store all active buy offers and maps them to their respective token ids
mapping(uint256 => BuyOffer) public activeBuyOffers;
// Token contract
Token token;
// Escrow for buy offers
mapping(address => mapping(uint256 => uint256)) public buyOffersEscrow;
// Events
event NewSellOffer(uint256 tokenId, address seller, uint256 value);
event NewBuyOffer(uint256 tokenId, address buyer, uint256 value);
event SellOfferWithdrawn(uint256 tokenId, address seller);
event BuyOfferWithdrawn(uint256 tokenId, address buyer);
event RoyaltiesPaid(uint256 tokenId, uint value);
event Sale(uint256 tokenId, address seller, address buyer, uint256 value);
constructor(address tokenContractAddress) {
_tokenContractAddress = tokenContractAddress;
token = Token(_tokenContractAddress);
}
/// @notice Checks if NFT contract implements the ERC-2981 interface
/// @param _contract - the address of the NFT contract to query
/// @return true if ERC-2981 interface is supported, false otherwise
function _checkRoyalties(address _contract) internal returns (bool) {
(bool success) = IERC2981(_contract).
supportsInterface(_INTERFACE_ID_ERC2981);
return success;
}
/// @notice Puts a token on sale at a given price
/// @param tokenId - id of the token to sell
/// @param minPrice - minimum price at which the token can be sold
function makeSellOffer(uint256 tokenId, uint256 minPrice)
external isMarketable(tokenId) tokenOwnerOnly(tokenId)
{
// Create sell offer
activeSellOffers[tokenId] = SellOffer({seller : msg.sender,
minPrice : minPrice});
// Broadcast sell offer
emit NewSellOffer(tokenId, msg.sender, minPrice);
}
/// @notice Withdraw a sell offer
/// @param tokenId - id of the token whose sell order needs to be cancelled
function withdrawSellOffer(uint256 tokenId)
external isMarketable(tokenId)
{
require(activeSellOffers[tokenId].seller != address(0),
"No sale offer");
require(activeSellOffers[tokenId].seller == msg.sender,
"Not seller");
// Removes the current sell offer
delete (activeSellOffers[tokenId]);
// Broadcast offer withdrawal
emit SellOfferWithdrawn(tokenId, msg.sender);
}
/// @notice Transfers royalties to the rightsowner if applicable
/// @param tokenId - the NFT assed queried for royalties
/// @param grossSaleValue - the price at which the asset will be sold
/// @return netSaleAmount - the value that will go to the seller after
/// deducting royalties
function _deduceRoyalties(uint256 tokenId, uint256 grossSaleValue)
internal returns (uint256 netSaleAmount) {
// Get amount of royalties to pays and recipient
(address royaltiesReceiver, uint256 royaltiesAmount) = token
.royaltyInfo(tokenId, grossSaleValue);
// Deduce royalties from sale value
uint256 netSaleValue = grossSaleValue - royaltiesAmount;
// Transfer royalties to rightholder if not zero
if (royaltiesAmount > 0) {
royaltiesReceiver.call{value: royaltiesAmount}('');
}
// Broadcast royalties payment
emit RoyaltiesPaid(tokenId, royaltiesAmount);
return netSaleValue;
}
/// @notice Purchases a token and transfers royalties if applicable
/// @param tokenId - id of the token to sell
function purchase(uint256 tokenId)
external tokenOwnerForbidden(tokenId) payable {
address seller = activeSellOffers[tokenId].seller;
require(seller != address(0),
"No active sell offer");
// If, for some reason, the token is not approved anymore (transfer or
// sale on another market place for instance), we remove the sell order
// and throw
if (token.getApproved(tokenId) != address(this)) {
delete (activeSellOffers[tokenId]);
// Broadcast offer withdrawal
emit SellOfferWithdrawn(tokenId, seller);
// Revert
revert("Invalid sell offer");
}
require(msg.value >= activeSellOffers[tokenId].minPrice,
"Amount sent too low");
uint256 saleValue = msg.value;
// Pay royalties if applicable
if (_checkRoyalties(_tokenContractAddress)) {
saleValue = _deduceRoyalties(tokenId, saleValue);
}
// Transfer funds to the seller
activeSellOffers[tokenId].seller.call{value: saleValue}('');
// And token to the buyer
token.safeTransferFrom(
seller,
msg.sender,
tokenId
);
// Remove all sell and buy offers
delete (activeSellOffers[tokenId]);
delete (activeBuyOffers[tokenId]);
// Broadcast the sale
emit Sale(tokenId,
seller,
msg.sender,
msg.value);
}
/// @notice Makes a buy offer for a token. The token does not need to have
/// been put up for sale. A buy offer can not be withdrawn or
/// replaced for 24 hours. Amount of the offer is put in escrow
/// until the offer is withdrawn or superceded
/// @param tokenId - id of the token to buy
function makeBuyOffer(uint256 tokenId)
external tokenOwnerForbidden(tokenId)
payable {
// Reject the offer if item is already available for purchase at a
// lower or identical price
if (activeSellOffers[tokenId].minPrice != 0) {
require((msg.value > activeSellOffers[tokenId].minPrice),
"Sell order at this price or lower exists");
}
// Only process the offer if it is higher than the previous one or the
// previous one has expired
require(activeBuyOffers[tokenId].createTime <
(block.timestamp - 1 days) || msg.value >
activeBuyOffers[tokenId].price,
"Previous buy offer higher or not expired");
address previousBuyOfferOwner = activeBuyOffers[tokenId].buyer;
uint256 refundBuyOfferAmount = buyOffersEscrow[previousBuyOfferOwner]
[tokenId];
// Refund the owner of the previous buy offer
buyOffersEscrow[previousBuyOfferOwner][tokenId] = 0;
if (refundBuyOfferAmount > 0) {
payable(previousBuyOfferOwner).call{value: refundBuyOfferAmount}('');
}
// Create a new buy offer
activeBuyOffers[tokenId] = BuyOffer({buyer : msg.sender,
price : msg.value,
createTime : block.timestamp});
// Create record of funds deposited for this offer
buyOffersEscrow[msg.sender][tokenId] = msg.value;
// Broadcast the buy offer
emit NewBuyOffer(tokenId, msg.sender, msg.value);
}
/// @notice Withdraws a buy offer. Can only be withdrawn a day after being
/// posted
/// @param tokenId - id of the token whose buy order to remove
function withdrawBuyOffer(uint256 tokenId)
external lastBuyOfferExpired(tokenId) {
require(activeBuyOffers[tokenId].buyer == msg.sender,
"Not buyer");
uint256 refundBuyOfferAmount = buyOffersEscrow[msg.sender][tokenId];
// Set the buyer balance to 0 before refund
buyOffersEscrow[msg.sender][tokenId] = 0;
// Remove the current buy offer
delete(activeBuyOffers[tokenId]);
// Refund the current buy offer if it is non-zero
if (refundBuyOfferAmount > 0) {
msg.sender.call{value: refundBuyOfferAmount}('');
}
// Broadcast offer withdrawal
emit BuyOfferWithdrawn(tokenId, msg.sender);
}
/// @notice Lets a token owner accept the current buy offer
/// (even without a sell offer)
/// @param tokenId - id of the token whose buy order to accept
function acceptBuyOffer(uint256 tokenId)
external isMarketable(tokenId) tokenOwnerOnly(tokenId) {
address currentBuyer = activeBuyOffers[tokenId].buyer;
require(currentBuyer != address(0),
"No buy offer");
uint256 saleValue = activeBuyOffers[tokenId].price;
uint256 netSaleValue = saleValue;
// Pay royalties if applicable
if (_checkRoyalties(_tokenContractAddress)) {
netSaleValue = _deduceRoyalties(tokenId, saleValue);
}
// Delete the current sell offer whether it exists or not
delete (activeSellOffers[tokenId]);
// Delete the buy offer that was accepted
delete (activeBuyOffers[tokenId]);
// Withdraw buyer's balance
buyOffersEscrow[currentBuyer][tokenId] = 0;
// Transfer funds to the seller
msg.sender.call{value: netSaleValue}('');
// And token to the buyer
token.safeTransferFrom(
msg.sender,
currentBuyer,
tokenId
);
// Broadcast the sale
emit Sale(tokenId,
msg.sender,
currentBuyer,
saleValue);
}
modifier isMarketable(uint256 tokenId) {
require(token.getApproved(tokenId) == address(this),
"Not approved");
_;
}
modifier tokenOwnerForbidden(uint256 tokenId) {
require(token.ownerOf(tokenId) != msg.sender,
"Token owner not allowed");
_;
}
modifier tokenOwnerOnly(uint256 tokenId) {
require(token.ownerOf(tokenId) == msg.sender,
"Not token owner");
_;
}
modifier lastBuyOfferExpired(uint256 tokenId) {
require(
activeBuyOffers[tokenId].createTime < (block.timestamp - 1 days),
"Buy offer not expired");
_;
}
}
|
Transfers royalties to the rightsowner if applicable tokenId - the NFT assed queried for royalties grossSaleValue - the price at which the asset will be sold return netSaleAmount - the value that will go to the seller after deducting royalties Get amount of royalties to pays and recipient Deduce royalties from sale value Transfer royalties to rightholder if not zero
|
function _deduceRoyalties(uint256 tokenId, uint256 grossSaleValue)
internal returns (uint256 netSaleAmount) {
(address royaltiesReceiver, uint256 royaltiesAmount) = token
.royaltyInfo(tokenId, grossSaleValue);
uint256 netSaleValue = grossSaleValue - royaltiesAmount;
if (royaltiesAmount > 0) {
}
return netSaleValue;
}
| 13,042,310
|
pragma solidity ^0.4.24;
contract CAE4Devents {
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
// fired at end of buy or reload
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
// fired whenever theres a withdraw
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
// fired whenever a withdraw forces end round to be ran
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// (fomo3d long only) fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// (fomo3d long only) fired whenever a player tries a reload after round timer
// hit zero, and causes end round to be ran.
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever an affiliate is paid
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
// received pot swap deposit
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
// fired whenever an janwin is paid
event onNewJanWin
(
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
}
contract modularLong is CAE4Devents {}
library CAE4Ddatasets {
//compressedData key
// [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0]
// 0 - new player (bool)
// 1 - joined round (bool)
// 2 - new leader (bool)
// 3-5 - air drop tracker (uint 0-999)
// 6-16 - round end time
// 17 - winnerTeam
// 18 - 28 timestamp
// 29 - team
// 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico)
// 31 - airdrop happened bool
// 32 - airdrop tier
// 33 - airdrop amount won
//compressedIDs key
// [77-52][51-26][25-0]
// 0-25 - pID
// 26-51 - winPID
// 52-77 - rID
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
bytes32 winnerName; // winner name
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 P3DAmount; // amount distributed to p3d
uint256 genAmount; // amount distributed to gen
uint256 potAmount; // amount added to pot
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 aff; // affiliate vault
uint256 lrnd; // last round played
uint256 laff; // last affiliate id used
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys
uint256 mask; // player mask
uint256 ico; // ICO phase investment
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 team; // tID of team in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
uint256 ico; // total eth sent in during ICO phase
uint256 icoGen; // total eth for gen during ICO phase
uint256 icoAvg; // average key price for ICO phase
uint256 initPot; // the init pot from last round
}
struct TeamFee {
uint256 gen; // % of buy in thats paid to key holders of current round
uint256 pot; // % of buy in thats paid to p3d holders
uint256 aff;
uint256 com;
}
struct PotSplit {
uint256 gen; // % of pot thats paid to key holders of current round
uint256 win; // % of pot thats paid to p3d holders
uint256 next;
uint256 com;
}
}
interface JIincForwarderInterface {
function deposit() external payable returns(bool);
function status() external view returns(address, address, bool);
function startMigration(address _newCorpBank) external returns(bool);
function cancelMigration() external returns(bool);
function finishMigration() external returns(bool);
function setup(address _firstCorpBank) external;
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
contract CAE4Dlong is modularLong {
using SafeMath for *;
using NameFilter for string;
using CAE4DKeysCalcLong for uint256;
JIincForwarderInterface constant private Jekyll_Island_Inc = JIincForwarderInterface(0xBE207a22b2dcabB7AAd232d8F631cBEda56E379d);
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xBCE0e39E0b9CbD62fde3B490523231eA2827Df1d);
//JIincForwarderInterface private Jekyll_Island_Inc ;
//PlayerBookInterface private PlayerBook ;
//address public playerbookaddr ;
//address public jekylladdr ;
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
string constant public name = "CAE4D";
string constant public symbol = "CAE4D";
uint256 private rndExtra_ = 30;//extSettings.getLongExtra(); // length of the very first ICO
uint256 private rndGap_ = 30;//extSettings.getLongGap(); // length of ICO phase, set to 1 year for EOS.
uint256 constant private rndInit_ = 1 hours; // round timer starts at this
uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 24 hours; // max length a round timer can be
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
uint256 public rID_; // round id number / total rounds that have happened
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => CAE4Ddatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => CAE4Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => CAE4Ddatasets.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
//****************
// TEAM FEE DATA
//****************
mapping (uint256 => CAE4Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => CAE4Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
//constructor(address addr1,address addr2)
constructor()
public
{
//playerbookaddr = addr2;
//jekylladdr = addr1;
//DiviesInterface constant private Divies = DiviesInterface(0xc7029Ed9EBa97A096e72607f4340c34049C7AF48);
//Jekyll_Island_Inc = JIincForwarderInterface(jekylladdr);
//PlayerBook = PlayerBookInterface(playerbookaddr);
// Team allocation structures
// 0 = elephants
// 1 = nuts
// 2 = rock
// 3 = rivulets
// Team allocation percentages
// (Gen,Pot,Referrals,Community)
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = CAE4Ddatasets.TeamFee(20,60,15,5); //60% to pot, 15% to aff, 5% to com
fees_[1] = CAE4Ddatasets.TeamFee(41,24,30,5); //24% to pot, 30% to aff, 5% to com
fees_[2] = CAE4Ddatasets.TeamFee(55,30,10,5); //30% to pot, 10% to aff, 5% to com
fees_[3] = CAE4Ddatasets.TeamFee(50,20,25,5); //20% to pot, 25% to aff, 5% to com
// how to split up the final pot based on which team was picked
// (gen,win,next,com)
potSplit_[0] = CAE4Ddatasets.PotSplit(10,75,13,2); //75% to winner, 13% to next round, 2% to com
potSplit_[1] = CAE4Ddatasets.PotSplit(20,65,13,2); //65% to winner, 13% to next round, 2% to com
potSplit_[2] = CAE4Ddatasets.PotSplit(25,65,8,2); //65% to winner, 8% to next round, 2% to com
potSplit_[3] = CAE4Ddatasets.PotSplit(40,45,13,2); //45% to winner, 13% to next round, 2% to com
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
CAE4Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
/**
* @dev converts all incoming ethereum to keys.
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
*/
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
CAE4Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
CAE4Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
CAE4Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
CAE4Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
CAE4Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
CAE4Ddatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// set up our tx event data
CAE4Ddatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit CAE4Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit CAE4Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
/**
* @dev use these to register names. they are just wrappers that will send the
* registration requests to the PlayerBook contract. So registering here is the
* same as registering there. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who referred you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit CAE4Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit CAE4Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit CAE4Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
/**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// if player is winner
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return eth invested during ICO phase
* @return round id
* @return total keys for round
* @return time round ends
* @return time round started
* @return current pot
* @return current team ID & player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return elephants eth in for round
* @return nuts eth in for round
* @return rock eth in for round
* @return rivulets eth in for round
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
round_[_rID].eth, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
}
function getCurrentRoundRewards()
public
view
returns(uint256){
uint256 _rID = rID_;
return (round_[_rID].eth.add(round_[_rID].initPot).sub(round_[_rID].pot));
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, CAE4Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit CAE4Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, CAE4Ddatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_rID, _pID, _eth, _affID, _team, _eventData_);
// if round is not active and end round needs to be ran
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit CAE4Devents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, CAE4Ddatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// early round eth limiter
//if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 5000000000000000000)
//{
// uint256 _availableLimit = (5000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
// uint256 _refund = _eth.sub(_availableLimit);
// plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
// _eth = _availableLimit;
//}
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// manage airdrops
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
// gib muni
uint256 _prize;
if (_eth >= 10000000000000000000)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
}
// set airdrop happened bool to true
_eventData_.compressedData += 10000000000000000000000000000000;
// let event know how much was won
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
// reset air drop tracker
airDropTracker_ = 0;
}
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// distribute eth
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(CAE4Ddatasets.EventReturns memory _eventData_)
private
returns (CAE4Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of fomo3d
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev checks to make sure user picked a valid team. if not sets team
* to default (rock)
*/
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, CAE4Ddatasets.EventReturns memory _eventData_)
private
returns (CAE4Ddatasets.EventReturns)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(CAE4Ddatasets.EventReturns memory _eventData_)
private
returns (CAE4Ddatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(potSplit_[_winTID].win)) / 100;
uint256 _com = (_pot.mul(potSplit_[_winTID].com)) / 100;
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _res = ((_pot.sub(_win)).sub(_com)).sub(_gen);
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()"))))
{
// This ensures Team Just cannot influence the outcome of FoMo3D with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
//_p3d = _p3d.add(_com);
_res = _res.add(_com);
_com = 0;
}
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// send share for p3d to divies
//if (_p3d > 0)
//Divies.deposit.value(_p3d)();
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
//_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
round_[_rID].initPot = round_[_rID].pot;
return(_eventData_);
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*/
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d
* CAE4Ddatasets.TeamFee(20,0); //60% to pot, 15% to aff, 5% to com
*/
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, CAE4Ddatasets.EventReturns memory _eventData_)
private
returns(CAE4Ddatasets.EventReturns)
{
// pay x% out to community rewards
uint256 _com = _eth.mul(fees_[_team].com) / 100;
// distribute share to affiliate
uint256 _aff = _eth.mul(fees_[_team].aff) / 100;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit CAE4Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_com = _com.add(_aff);
//_p3d = _aff;
}
if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()"))))
{
// This ensures Team Just cannot influence the outcome of FoMo3D with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
//_p3d = _com;
round_[rID_].pot = round_[rID_].pot.add(_com);
_com = 0;
}
// pay out p3d
//_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
//if (_p3d > 0)
//{
// deposit to divies contract
//Divies.deposit.value(_p3d)();
// set up event data
// _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
//}
return(_eventData_);
}
function potSwap()
external
payable
{
// setup local rID
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit CAE4Devents.onPotSwapDeposit(_rID, msg.value);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, CAE4Ddatasets.EventReturns memory _eventData_)
private
returns(CAE4Ddatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// toss 1% into airdrop pot
//uint256 _air = (_eth / 100);
//airDropPot_ = airDropPot_.add(_air);
// update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share))
//_eth = _eth.sub(((14) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
_eth = _eth.sub((_eth.mul(fees_[_team].com + fees_[_team].aff)) / 100);
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, CAE4Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit CAE4Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = false;
function activate()
public
{
// only team just can activate
require(
msg.sender == 0xe1A375cd31baF61D2fDAbd93F85c22A49a3795aF ||
msg.sender == 0xbD63f951D2FbbA361b2B48F65fce7E227EFD0CAC ,
"only team just can activate"
);
// can only be ran once
require(activated_ == false, "fomo3d already activated");
// activate the contract
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
library UintCompressor {
using SafeMath for *;
function insert(uint256 _var, uint256 _include, uint256 _start, uint256 _end)
internal
pure
returns(uint256)
{
// check conditions
require(_end < 77 && _start < 77, "start/end must be less than 77");
require(_end >= _start, "end must be >= start");
// format our start/end points
_end = exponent(_end).mul(10);
_start = exponent(_start);
// check that the include data fits into its segment
require(_include < (_end / _start));
// build middle
if (_include > 0)
_include = _include.mul(_start);
return((_var.sub((_var / _start).mul(_start))).add(_include).add((_var / _end).mul(_end)));
}
function extract(uint256 _input, uint256 _start, uint256 _end)
internal
pure
returns(uint256)
{
// check conditions
require(_end < 77 && _start < 77, "start/end must be less than 77");
require(_end >= _start, "end must be >= start");
// format our start/end points
_end = exponent(_end).mul(10);
_start = exponent(_start);
// return requested section
return((((_input / _start).mul(_start)).sub((_input / _end).mul(_end))) / _start);
}
function exponent(uint256 _position)
private
pure
returns(uint256)
{
return((10).pwr(_position));
}
}
library CAE4DKeysCalcLong {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
|
distributes eth based on fees to com, aff, and p3d/ pay x% out to community rewards distribute share to affiliate decide what to do with affiliate share of fees affiliate must not be self, and must have a name registered_p3d = _aff; This ensures Team Just cannot influence the outcome of FoMo3D with bank migrations by breaking outgoing transactions. Something we would never do. But that's not the point. We spent 2000$ in eth re-deploying just to patch this, we hold the highest belief that everything we create should be trustless. Team JUST, The name you shouldn't have to trust._p3d = _com;
|
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, CAE4Ddatasets.EventReturns memory _eventData_)
private
returns(CAE4Ddatasets.EventReturns)
{
uint256 _com = _eth.mul(fees_[_team].com) / 100;
uint256 _aff = _eth.mul(fees_[_team].aff) / 100;
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit CAE4Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
_com = _com.add(_aff);
}
if (!address(Jekyll_Island_Inc).call.value(_com)(bytes4(keccak256("deposit()"))))
{
round_[rID_].pot = round_[rID_].pot.add(_com);
_com = 0;
}
return(_eventData_);
}
| 12,043,213
|
/**
*Submitted for verification at Etherscan.io on 2021-10-05
*/
pragma solidity 0.8.9;
interface IBXRToken {
function transfer(address to, uint value) external returns (bool);
function balanceOf(address) external view returns (uint256);
}
contract Sale {
address public owner;
address public updater;
address public token;
uint256 internal rate;
uint256 internal constant RATE_DELIMITER = 1000;
uint256 internal oldRate;
uint256 internal rateUpdateDelay = 5 minutes;
uint256 internal rateBecomesValidAt;
event Purchase(address indexed buyer, uint256 amount);
event RateUpdate(uint256 newRate, uint256 rateBecomesValidAt);
event DelayUpdate(uint256 newDelay);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event TokensReceived(uint256 amount);
event ChangedUpdater(address indexed previousUpdater, address indexed newUpdater);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyUpdater() {
require(msg.sender == updater, "This function is callable only by updater");
_;
}
constructor(address _token, uint256 _rate) {
require(_token != address(0));
require(_rate != 0);
owner = msg.sender;
token = _token;
rate = _rate;
}
function recieve() external payable {
require(msg.data.length == 0);
buy();
}
function updateRate(uint256 newRate) internal {
require(newRate != 0);
if (block.timestamp > rateBecomesValidAt) {
oldRate = rate;
}
rate = newRate;
rateBecomesValidAt = block.timestamp + rateUpdateDelay;
emit RateUpdate(newRate, rateBecomesValidAt);
}
function updateRateByOwner(uint256 newRate) external onlyOwner {
updateRate(newRate);
}
function updateRateByUpdater(uint256 newRate) external onlyUpdater {
(uint256 future_rate, uint256 timePriorToApply) = futureRate();
require(timePriorToApply == 0, "New rate hasn't been applied yet");
uint256 newRateMultiplied = newRate * 100;
require(newRateMultiplied / 100 == newRate, "Integer overflow");
// No need to check previous rate for overflow as newRate is checked
// uint256 rateMultiplied = rate * 100;
// require(rateMultiplied / 100 == rate, "Integer overflow");
require(newRate * 99 <= future_rate * 100, "New rate is too high");
updateRate(newRate);
}
function changeRateUpdateDelay(uint256 newDelay) external onlyOwner {
rateUpdateDelay = newDelay;
emit DelayUpdate(newDelay);
}
function withdraw() external onlyOwner {
require(address(this).balance > 0);
payable(msg.sender).transfer(address(this).balance);
}
function withdraw(address payable to) external onlyOwner {
require(address(this).balance > 0);
to.transfer(address(this).balance);
}
function transferOwnership(address _owner) external onlyOwner {
require(_owner != address(0));
emit OwnershipTransferred(owner, _owner);
owner = _owner;
}
function tokenFallback(address, uint value, bytes calldata) external {
require(msg.sender == token);
emit TokensReceived(value);
}
function buy() public payable returns (uint256) {
uint256 availableTotal = availableTokens();
require(availableTotal > 0);
uint256 amount = weiToTokens(msg.value);
// actual = min(amount, availableTotal)
uint256 actual = amount < availableTotal ? amount : availableTotal;
require(IBXRToken(token).transfer(msg.sender, actual));
if (amount != actual) {
uint256 weiRefund = msg.value - tokensToWei(actual);
payable(msg.sender).transfer(weiRefund);
}
emit Purchase(msg.sender, actual);
return actual;
}
function currentRate() public view returns (uint256) {
return (block.timestamp < rateBecomesValidAt) ? oldRate : rate;
}
function weiToTokens(uint256 weiAmount) public view returns (uint256) {
uint256 exchangeRate = currentRate();
return weiAmount * exchangeRate / RATE_DELIMITER;
}
function tokensToWei(uint256 tokensAmount) public view returns (uint256) {
uint256 exchangeRate = currentRate();
return tokensAmount * RATE_DELIMITER / exchangeRate;
}
function futureRate() public view returns (uint256, uint256) {
return (block.timestamp < rateBecomesValidAt) ? (rate, rateBecomesValidAt - block.timestamp) : (rate, 0);
}
function availableTokens() public view returns (uint256) {
return IBXRToken(token).balanceOf(address(this));
}
function changeUpdater(address _updater) external onlyOwner {
require(_updater != address(0), "Invalid _updater address");
emit ChangedUpdater(updater, _updater);
updater = _updater;
}
}
|
No need to check previous rate for overflow as newRate is checked uint256 rateMultiplied = rate 100; require(rateMultiplied / 100 == rate, "Integer overflow");
|
function updateRateByUpdater(uint256 newRate) external onlyUpdater {
(uint256 future_rate, uint256 timePriorToApply) = futureRate();
require(timePriorToApply == 0, "New rate hasn't been applied yet");
uint256 newRateMultiplied = newRate * 100;
require(newRateMultiplied / 100 == newRate, "Integer overflow");
require(newRate * 99 <= future_rate * 100, "New rate is too high");
updateRate(newRate);
}
| 6,833,524
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.5.16;
contract JoetrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
JOETROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint256 error, uint256 info, uint256 detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), 0);
return uint256(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(
Error err,
FailureInfo info,
uint256 opaqueError
) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), opaqueError);
return uint256(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
JOETROLLER_REJECTION,
JOETROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_MARKET_NOT_LISTED,
BORROW_JOETROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_JOETROLLER_REJECTION,
LIQUIDATE_JOETROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_JOETROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_JOETROLLER_REJECTION,
MINT_FRESHNESS_CHECK,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_JOETROLLER_REJECTION,
REDEEM_FRESHNESS_CHECK,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_JOETROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_JOETROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_JOETROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint256 error, uint256 info, uint256 detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), 0);
return uint256(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(
Error err,
FailureInfo info,
uint256 opaqueError
) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), opaqueError);
return uint256(err);
}
}
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
/**
* @title Compound's InterestRateModel Interface
* @author Compound
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per sec
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @return The borrow rate per sec (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(
uint256 cash,
uint256 borrows,
uint256 reserves
) external view returns (uint256);
/**
* @notice Calculates the current supply interest rate per sec
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per sec (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(
uint256 cash,
uint256 borrows,
uint256 reserves,
uint256 reserveFactorMantissa
) external view returns (uint256);
}
interface ERC3156FlashBorrowerInterface {
/**
* @dev Receive a flash loan.
* @param initiator The initiator of the loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param fee The additional amount of tokens to repay.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
* @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan"
*/
function onFlashLoan(
address initiator,
address token,
uint256 amount,
uint256 fee,
bytes calldata data
) external returns (bytes32);
}
contract PriceOracle {
/**
* @notice Get the underlying price of a jToken asset
* @param jToken The jToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(JToken jToken) external view returns (uint256);
}
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint256 c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {
uint256 c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(
uint256 a,
uint256 b,
uint256 c
) internal pure returns (MathError, uint256) {
(MathError err0, uint256 sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath {
uint256 constant expScale = 1e18;
uint256 constant doubleScale = 1e36;
uint256 constant halfExpScale = expScale / 2;
uint256 constant mantissaOne = expScale;
struct Exp {
uint256 mantissa;
}
struct Double {
uint256 mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint256 num, uint256 denom) internal pure returns (MathError, Exp memory) {
(MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint256 rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {
(MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {
(MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) {
(MathError err0, uint256 scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (MathError, uint256) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(
Exp memory a,
uint256 scalar,
uint256 addend
) internal pure returns (MathError, uint256) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(
Exp memory a,
uint256 scalar,
uint256 addend
) internal pure returns (uint256) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) {
(MathError err0, uint256 descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint256 numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function div_ScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
uint256 numerator = mul_(expScale, scalar);
return Exp({mantissa: div_(numerator, divisor)});
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function div_ScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (uint256) {
Exp memory fraction = div_ScalarByExp(scalar, divisor);
return truncate(fraction);
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {
(MathError err0, uint256 doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint256 product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint256 a, uint256 b) internal pure returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(
Exp memory a,
Exp memory b,
Exp memory c
) internal pure returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) internal pure returns (uint256) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) internal pure returns (bool) {
return value.mantissa == 0;
}
function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint256 a, uint256 b) internal pure returns (uint256) {
return add_(a, b, "addition overflow");
}
function add_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint256 a, uint256 b) internal pure returns (uint256) {
return sub_(a, b, "subtraction underflow");
}
function sub_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint256 a, Exp memory b) internal pure returns (uint256) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint256 b) internal pure returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint256 a, Double memory b) internal pure returns (uint256) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint256 a, uint256 b) internal pure returns (uint256) {
return mul_(a, b, "multiplication overflow");
}
function mul_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint256 a, Exp memory b) internal pure returns (uint256) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint256 b) internal pure returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint256 a, Double memory b) internal pure returns (uint256) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint256 a, uint256 b) internal pure returns (uint256) {
return div_(a, b, "divide by zero");
}
function div_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint256 a, uint256 b) internal pure returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
// implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0
// original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
contract UnitrollerAdminStorage {
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @notice Active brains of Unitroller
*/
address public joetrollerImplementation;
/**
* @notice Pending brains of Unitroller
*/
address public pendingJoetrollerImplementation;
}
contract JoetrollerV1Storage is UnitrollerAdminStorage {
/**
* @notice Oracle which gives the price of any given asset
*/
PriceOracle public oracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint256 public closeFactorMantissa;
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint256 public liquidationIncentiveMantissa;
/**
* @notice Per-account mapping of "assets you are in"
*/
mapping(address => JToken[]) public accountAssets;
enum Version {
VANILLA,
COLLATERALCAP,
WRAPPEDNATIVE
}
struct Market {
/// @notice Whether or not this market is listed
bool isListed;
/**
* @notice Multiplier representing the most one can borrow against their collateral in this market.
* For instance, 0.9 to allow borrowing 90% of collateral value.
* Must be between 0 and 1, and stored as a mantissa.
*/
uint256 collateralFactorMantissa;
/// @notice Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
/// @notice JToken version
Version version;
}
/**
* @notice Official mapping of jTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/**
* @notice The Pause Guardian can pause certain actions as a safety mechanism.
* Actions which allow users to remove their own assets cannot be paused.
* Liquidation / seizing / transfer can only be paused globally, not by market.
*/
address public pauseGuardian;
bool public _mintGuardianPaused;
bool public _borrowGuardianPaused;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public mintGuardianPaused;
mapping(address => bool) public borrowGuardianPaused;
/// @notice A list of all markets
JToken[] public allMarkets;
// @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market.
address public borrowCapGuardian;
// @notice Borrow caps enforced by borrowAllowed for each jToken address. Defaults to zero which corresponds to unlimited borrowing.
mapping(address => uint256) public borrowCaps;
// @notice The supplyCapGuardian can set supplyCaps to any number for any market. Lowering the supply cap could disable supplying to the given market.
address public supplyCapGuardian;
// @notice Supply caps enforced by mintAllowed for each jToken address. Defaults to zero which corresponds to unlimited supplying.
mapping(address => uint256) public supplyCaps;
// @notice creditLimits allowed specific protocols to borrow and repay without collateral.
mapping(address => uint256) public creditLimits;
// @notice flashloanGuardianPaused can pause flash loan as a safety mechanism.
mapping(address => bool) public flashloanGuardianPaused;
// @notice rewardDistributor The module that handles reward distribution.
address payable public rewardDistributor;
}
contract JoetrollerInterface {
/// @notice Indicator that this is a Joetroller contract (for inspection)
bool public constant isJoetroller = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata jTokens) external returns (uint256[] memory);
function exitMarket(address jToken) external returns (uint256);
/*** Policy Hooks ***/
function mintAllowed(
address jToken,
address minter,
uint256 mintAmount
) external returns (uint256);
function mintVerify(
address jToken,
address minter,
uint256 mintAmount,
uint256 mintTokens
) external;
function redeemAllowed(
address jToken,
address redeemer,
uint256 redeemTokens
) external returns (uint256);
function redeemVerify(
address jToken,
address redeemer,
uint256 redeemAmount,
uint256 redeemTokens
) external;
function borrowAllowed(
address jToken,
address borrower,
uint256 borrowAmount
) external returns (uint256);
function borrowVerify(
address jToken,
address borrower,
uint256 borrowAmount
) external;
function repayBorrowAllowed(
address jToken,
address payer,
address borrower,
uint256 repayAmount
) external returns (uint256);
function repayBorrowVerify(
address jToken,
address payer,
address borrower,
uint256 repayAmount,
uint256 borrowerIndex
) external;
function liquidateBorrowAllowed(
address jTokenBorrowed,
address jTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount
) external returns (uint256);
function liquidateBorrowVerify(
address jTokenBorrowed,
address jTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount,
uint256 seizeTokens
) external;
function seizeAllowed(
address jTokenCollateral,
address jTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256);
function seizeVerify(
address jTokenCollateral,
address jTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external;
function transferAllowed(
address jToken,
address src,
address dst,
uint256 transferTokens
) external returns (uint256);
function transferVerify(
address jToken,
address src,
address dst,
uint256 transferTokens
) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address jTokenBorrowed,
address jTokenCollateral,
uint256 repayAmount
) external view returns (uint256, uint256);
}
interface JoetrollerInterfaceExtension {
function checkMembership(address account, JToken jToken) external view returns (bool);
function updateJTokenVersion(address jToken, JoetrollerV1Storage.Version version) external;
function flashloanAllowed(
address jToken,
address receiver,
uint256 amount,
bytes calldata params
) external view returns (bool);
}
contract JTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / sec)
*/
uint256 internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint256 internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-jToken operations
*/
JoetrollerInterface public joetroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first JTokens (used when totalSupply = 0)
*/
uint256 internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint256 public reserveFactorMantissa;
/**
* @notice Block timestamp that interest was last accrued at
*/
uint256 public accrualBlockTimestamp;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint256 public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint256 public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint256 public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint256 public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping(address => uint256) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping(address => mapping(address => uint256)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint256 principal;
uint256 interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
contract JErc20Storage {
/**
* @notice Underlying asset for this JToken
*/
address public underlying;
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract JSupplyCapStorage {
/**
* @notice Internal cash counter for this JToken. Should equal underlying.balanceOf(address(this)) for CERC20.
*/
uint256 public internalCash;
}
contract JCollateralCapStorage {
/**
* @notice Total number of tokens used as collateral in circulation.
*/
uint256 public totalCollateralTokens;
/**
* @notice Record of token balances which could be treated as collateral for each account.
* If collateral cap is not set, the value should be equal to accountTokens.
*/
mapping(address => uint256) public accountCollateralTokens;
/**
* @notice Check if accountCollateralTokens have been initialized.
*/
mapping(address => bool) public isCollateralTokenInit;
/**
* @notice Collateral cap for this JToken, zero for no cap.
*/
uint256 public collateralCap;
}
/*** Interface ***/
contract JTokenInterface is JTokenStorage {
/**
* @notice Indicator that this is a JToken contract (for inspection)
*/
bool public constant isJToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint256 mintAmount, uint256 mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(
address payer,
address borrower,
uint256 repayAmount,
uint256 accountBorrows,
uint256 totalBorrows
);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(
address liquidator,
address borrower,
uint256 repayAmount,
address jTokenCollateral,
uint256 seizeTokens
);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when joetroller is changed
*/
event NewJoetroller(JoetrollerInterface oldJoetroller, JoetrollerInterface newJoetroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint256 amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Failure event
*/
event Failure(uint256 error, uint256 info, uint256 detail);
/*** User Interface ***/
function transfer(address dst, uint256 amount) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 amount
) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function borrowRatePerSecond() external view returns (uint256);
function supplyRatePerSecond() external view returns (uint256);
function totalBorrowsCurrent() external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account) public view returns (uint256);
function exchangeRateCurrent() public returns (uint256);
function exchangeRateStored() public view returns (uint256);
function getCash() external view returns (uint256);
function accrueInterest() public returns (uint256);
function seize(
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256);
function _acceptAdmin() external returns (uint256);
function _setJoetroller(JoetrollerInterface newJoetroller) public returns (uint256);
function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256);
function _reduceReserves(uint256 reduceAmount) external returns (uint256);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256);
}
contract JErc20Interface is JErc20Storage {
/*** User Interface ***/
function mint(uint256 mintAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function repayBorrow(uint256 repayAmount) external returns (uint256);
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);
function liquidateBorrow(
address borrower,
uint256 repayAmount,
JTokenInterface jTokenCollateral
) external returns (uint256);
function _addReserves(uint256 addAmount) external returns (uint256);
}
contract JWrappedNativeInterface is JErc20Interface {
/**
* @notice Flash loan fee ratio
*/
uint256 public constant flashFeeBips = 3;
/*** Market Events ***/
/**
* @notice Event emitted when a flashloan occured
*/
event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee);
/*** User Interface ***/
function mintNative() external payable returns (uint256);
function redeemNative(uint256 redeemTokens) external returns (uint256);
function redeemUnderlyingNative(uint256 redeemAmount) external returns (uint256);
function borrowNative(uint256 borrowAmount) external returns (uint256);
function repayBorrowNative() external payable returns (uint256);
function repayBorrowBehalfNative(address borrower) external payable returns (uint256);
function liquidateBorrowNative(address borrower, JTokenInterface jTokenCollateral)
external
payable
returns (uint256);
function flashLoan(
ERC3156FlashBorrowerInterface receiver,
address initiator,
uint256 amount,
bytes calldata data
) external returns (bool);
function _addReservesNative() external payable returns (uint256);
}
contract JCapableErc20Interface is JErc20Interface, JSupplyCapStorage {
/**
* @notice Flash loan fee ratio
*/
uint256 public constant flashFeeBips = 3;
/*** Market Events ***/
/**
* @notice Event emitted when a flashloan occured
*/
event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee);
/*** User Interface ***/
function gulp() external;
}
contract JCollateralCapErc20Interface is JCapableErc20Interface, JCollateralCapStorage {
/*** Admin Events ***/
/**
* @notice Event emitted when collateral cap is set
*/
event NewCollateralCap(address token, uint256 newCap);
/**
* @notice Event emitted when user collateral is changed
*/
event UserCollateralChanged(address account, uint256 newCollateralTokens);
/*** User Interface ***/
function registerCollateral(address account) external returns (uint256);
function unregisterCollateral(address account) external;
function flashLoan(
ERC3156FlashBorrowerInterface receiver,
address initiator,
uint256 amount,
bytes calldata data
) external returns (bool);
/*** Admin Functions ***/
function _setCollateralCap(uint256 newCollateralCap) external;
}
contract JDelegatorInterface {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(
address implementation_,
bool allowResign,
bytes memory becomeImplementationData
) public;
}
contract JDelegateInterface {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
/*** External interface ***/
/**
* @title Flash loan receiver interface
*/
interface IFlashloanReceiver {
function executeOperation(
address sender,
address underlying,
uint256 amount,
uint256 fee,
bytes calldata params
) external;
}
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(
address src,
address dst,
uint256 amount
) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
/**
* @title Compound's JToken Contract
* @notice Abstract base for JTokens
* @author Compound
*/
contract JToken is JTokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param joetroller_ The address of the Joetroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(
JoetrollerInterface joetroller_,
InterestRateModel interestRateModel_,
uint256 initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_
) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockTimestamp == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the joetroller
uint256 err = _setJoetroller(joetroller_);
require(err == uint256(Error.NO_ERROR), "setting joetroller failed");
// Initialize block timestamp and borrow index (block timestamp mocks depend on joetroller being set)
accrualBlockTimestamp = getBlockTimestamp();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block timestamp / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint256(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint256(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint256(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint256) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
return mul_ScalarTruncate(exchangeRate, accountTokens[owner]);
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by joetroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
uint256 jTokenBalance = getJTokenBalanceInternal(account);
uint256 borrowBalance = borrowBalanceStoredInternal(account);
uint256 exchangeRateMantissa = exchangeRateStoredInternal();
return (uint256(Error.NO_ERROR), jTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block timestamp
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockTimestamp() internal view returns (uint256) {
return block.timestamp;
}
/**
* @notice Returns the current per-sec borrow interest rate for this jToken
* @return The borrow interest rate per sec, scaled by 1e18
*/
function borrowRatePerSecond() external view returns (uint256) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-sec supply interest rate for this jToken
* @return The supply interest rate per sec, scaled by 1e18
*/
function supplyRatePerSecond() external view returns (uint256) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the estimated per-sec borrow interest rate for this jToken after some change
* @return The borrow interest rate per sec, scaled by 1e18
*/
function estimateBorrowRatePerSecondAfterChange(uint256 change, bool repay) external view returns (uint256) {
uint256 cashPriorNew;
uint256 totalBorrowsNew;
if (repay) {
cashPriorNew = add_(getCashPrior(), change);
totalBorrowsNew = sub_(totalBorrows, change);
} else {
cashPriorNew = sub_(getCashPrior(), change);
totalBorrowsNew = add_(totalBorrows, change);
}
return interestRateModel.getBorrowRate(cashPriorNew, totalBorrowsNew, totalReserves);
}
/**
* @notice Returns the estimated per-sec supply interest rate for this jToken after some change
* @return The supply interest rate per sec, scaled by 1e18
*/
function estimateSupplyRatePerSecondAfterChange(uint256 change, bool repay) external view returns (uint256) {
uint256 cashPriorNew;
uint256 totalBorrowsNew;
if (repay) {
cashPriorNew = add_(getCashPrior(), change);
totalBorrowsNew = sub_(totalBorrows, change);
} else {
cashPriorNew = sub_(getCashPrior(), change);
totalBorrowsNew = add_(totalBorrows, change);
}
return interestRateModel.getSupplyRate(cashPriorNew, totalBorrowsNew, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint256) {
require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint256) {
require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint256) {
return borrowBalanceStoredInternal(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return the calculated balance or 0 if error code is non-zero
*/
function borrowBalanceStoredInternal(address account) internal view returns (uint256) {
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return 0;
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
uint256 principalTimesIndex = mul_(borrowSnapshot.principal, borrowIndex);
uint256 result = div_(principalTimesIndex, borrowSnapshot.interestIndex);
return result;
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint256) {
require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the JToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint256) {
return exchangeRateStoredInternal();
}
/**
* @notice Calculates the exchange rate from the underlying to the JToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return calculated exchange rate scaled by 1e18
*/
function exchangeRateStoredInternal() internal view returns (uint256) {
uint256 _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return initialExchangeRateMantissa;
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint256 totalCash = getCashPrior();
uint256 cashPlusBorrowsMinusReserves = sub_(add_(totalCash, totalBorrows), totalReserves);
uint256 exchangeRate = div_(cashPlusBorrowsMinusReserves, Exp({mantissa: _totalSupply}));
return exchangeRate;
}
}
/**
* @notice Get cash balance of this jToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint256) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed timestamp
* up to the current timestamp and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint256) {
/* Remember the initial block timestamp */
uint256 currentBlockTimestamp = getBlockTimestamp();
uint256 accrualBlockTimestampPrior = accrualBlockTimestamp;
/* Short-circuit accumulating 0 interest */
if (accrualBlockTimestampPrior == currentBlockTimestamp) {
return uint256(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint256 cashPrior = getCashPrior();
uint256 borrowsPrior = totalBorrows;
uint256 reservesPrior = totalReserves;
uint256 borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint256 borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of seconds elapsed since the last accrual */
uint256 timestampDelta = sub_(currentBlockTimestamp, accrualBlockTimestampPrior);
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * timestampDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), timestampDelta);
uint256 interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowsPrior);
uint256 totalBorrowsNew = add_(interestAccumulated, borrowsPrior);
uint256 totalReservesNew = mul_ScalarTruncateAddUInt(
Exp({mantissa: reserveFactorMantissa}),
interestAccumulated,
reservesPrior
);
uint256 borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockTimestamp = currentBlockTimestamp;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint256(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives jTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint256 mintAmount, bool isNative) internal nonReentrant returns (uint256, uint256) {
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount, isNative);
}
/**
* @notice Sender redeems jTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of jTokens to redeem into underlying
* @param isNative The amount is in native or not
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint256 redeemTokens, bool isNative) internal nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0, isNative);
}
/**
* @notice Sender redeems jTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming jTokens
* @param isNative The amount is in native or not
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint256 redeemAmount, bool isNative) internal nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount, isNative);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @param isNative The amount is in native or not
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint256 borrowAmount, bool isNative) internal nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount, isNative);
}
struct BorrowLocalVars {
MathError mathErr;
uint256 accountBorrows;
uint256 accountBorrowsNew;
uint256 totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @param isNative The amount is in native or not
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(
address payable borrower,
uint256 borrowAmount,
bool isNative
) internal returns (uint256) {
/* Fail if borrow not allowed */
uint256 allowed = joetroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.BORROW_JOETROLLER_REJECTION, allowed);
}
/*
* Return if borrowAmount is zero.
* Put behind `borrowAllowed` for accuring potential JOE rewards.
*/
if (borrowAmount == 0) {
accountBorrows[borrower].interestIndex = borrowIndex;
return uint256(Error.NO_ERROR);
}
/* Verify market's block timestamp equals current block timestamp */
if (accrualBlockTimestamp != getBlockTimestamp()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
vars.accountBorrows = borrowBalanceStoredInternal(borrower);
vars.accountBorrowsNew = add_(vars.accountBorrows, borrowAmount);
vars.totalBorrowsNew = add_(totalBorrows, borrowAmount);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The jToken must handle variations between ERC-20 and ETH underlying.
* On success, the jToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount, isNative);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
// unused function
// joetroller.borrowVerify(address(this), borrower, borrowAmount);
return uint256(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint256 repayAmount, bool isNative) internal nonReentrant returns (uint256, uint256) {
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount, isNative);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(
address borrower,
uint256 repayAmount,
bool isNative
) internal nonReentrant returns (uint256, uint256) {
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount, isNative);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint256 repayAmount;
uint256 borrowerIndex;
uint256 accountBorrows;
uint256 accountBorrowsNew;
uint256 totalBorrowsNew;
uint256 actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(
address payer,
address borrower,
uint256 repayAmount,
bool isNative
) internal returns (uint256, uint256) {
/* Fail if repayBorrow not allowed */
uint256 allowed = joetroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.REPAY_BORROW_JOETROLLER_REJECTION, allowed), 0);
}
/*
* Return if repayAmount is zero.
* Put behind `repayBorrowAllowed` for accuring potential JOE rewards.
*/
if (repayAmount == 0) {
accountBorrows[borrower].interestIndex = borrowIndex;
return (uint256(Error.NO_ERROR), 0);
}
/* Verify market's block timestamp equals current block timestamp */
if (accrualBlockTimestamp != getBlockTimestamp()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
vars.accountBorrows = borrowBalanceStoredInternal(borrower);
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint256(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The jToken must handle variations between ERC-20 and ETH underlying.
* On success, the jToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount, isNative);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
vars.accountBorrowsNew = sub_(vars.accountBorrows, vars.actualRepayAmount);
vars.totalBorrowsNew = sub_(totalBorrows, vars.actualRepayAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
// unused function
// joetroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint256(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this jToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param jTokenCollateral The market in which to seize collateral from the borrower
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(
address borrower,
uint256 repayAmount,
JTokenInterface jTokenCollateral,
bool isNative
) internal nonReentrant returns (uint256, uint256) {
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = jTokenCollateral.accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, jTokenCollateral, isNative);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this jToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param jTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(
address liquidator,
address borrower,
uint256 repayAmount,
JTokenInterface jTokenCollateral,
bool isNative
) internal returns (uint256, uint256) {
/* Fail if liquidate not allowed */
uint256 allowed = joetroller.liquidateBorrowAllowed(
address(this),
address(jTokenCollateral),
liquidator,
borrower,
repayAmount
);
if (allowed != 0) {
return (failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.LIQUIDATE_JOETROLLER_REJECTION, allowed), 0);
}
/* Verify market's block timestamp equals current block timestamp */
if (accrualBlockTimestamp != getBlockTimestamp()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify jTokenCollateral market's block timestamp equals current block timestamp */
if (jTokenCollateral.accrualBlockTimestamp() != getBlockTimestamp()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint256(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint256 repayBorrowError, uint256 actualRepayAmount) = repayBorrowFresh(
liquidator,
borrower,
repayAmount,
isNative
);
if (repayBorrowError != uint256(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint256 amountSeizeError, uint256 seizeTokens) = joetroller.liquidateCalculateSeizeTokens(
address(this),
address(jTokenCollateral),
actualRepayAmount
);
require(amountSeizeError == uint256(Error.NO_ERROR), "LIQUIDATE_JOETROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(jTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint256 seizeError;
if (address(jTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = jTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint256(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(jTokenCollateral), seizeTokens);
/* We call the defense hook */
// unused function
// joetroller.liquidateBorrowVerify(address(this), address(jTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint256(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another jToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed jToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of jTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(
address liquidator,
address borrower,
uint256 seizeTokens
) external nonReentrant returns (uint256) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint256(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint256) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets a new joetroller for the market
* @dev Admin function to set a new joetroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setJoetroller(JoetrollerInterface newJoetroller) public returns (uint256) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_JOETROLLER_OWNER_CHECK);
}
JoetrollerInterface oldJoetroller = joetroller;
// Ensure invoke joetroller.isJoetroller() returns true
require(newJoetroller.isJoetroller(), "marker method returned false");
// Set market's joetroller to newJoetroller
joetroller = newJoetroller;
// Emit NewJoetroller(oldJoetroller, newJoetroller)
emit NewJoetroller(oldJoetroller, newJoetroller);
return uint256(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint256 newReserveFactorMantissa) external nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint256 newReserveFactorMantissa) internal returns (uint256) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block timestamp equals current block timestamp
if (accrualBlockTimestamp != getBlockTimestamp()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint256 oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint256(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @param isNative The amount is in native or not
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint256 addAmount, bool isNative) internal nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount, isNative);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint256 addAmount, bool isNative) internal returns (uint256, uint256) {
// totalReserves + actualAddAmount
uint256 totalReservesNew;
uint256 actualAddAmount;
// We fail gracefully unless market's block timestamp equals current block timestamp
if (accrualBlockTimestamp != getBlockTimestamp()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The jToken must handle variations between ERC-20 and ETH underlying.
* On success, the jToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount, isNative);
totalReservesNew = add_(totalReserves, actualAddAmount);
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint256(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint256 reduceAmount) external nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint256 reduceAmount) internal returns (uint256) {
// totalReserves - reduceAmount
uint256 totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block timestamp equals current block timestamp
if (accrualBlockTimestamp != getBlockTimestamp()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = sub_(totalReserves, reduceAmount);
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
// Restrict reducing reserves in native token. Implementations except `JWrappedNative` won't use parameter `isNative`.
doTransferOut(admin, reduceAmount, true);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint256(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint256) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block timestamp equals current block timestamp
if (accrualBlockTimestamp != getBlockTimestamp()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint256(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint256);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(
address from,
uint256 amount,
bool isNative
) internal returns (uint256);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(
address payable to,
uint256 amount,
bool isNative
) internal;
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
*/
function transferTokens(
address spender,
address src,
address dst,
uint256 tokens
) internal returns (uint256);
/**
* @notice Get the account's jToken balances
*/
function getJTokenBalanceInternal(address account) internal view returns (uint256);
/**
* @notice User supplies assets into the market and receives jTokens in exchange
* @dev Assumes interest has already been accrued up to the current timestamp
*/
function mintFresh(
address minter,
uint256 mintAmount,
bool isNative
) internal returns (uint256, uint256);
/**
* @notice User redeems jTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current timestamp
*/
function redeemFresh(
address payable redeemer,
uint256 redeemTokensIn,
uint256 redeemAmountIn,
bool isNative
) internal returns (uint256);
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another JToken.
* Its absolutely critical to use msg.sender as the seizer jToken and not a parameter.
*/
function seizeInternal(
address seizerToken,
address liquidator,
address borrower,
uint256 seizeTokens
) internal returns (uint256);
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
pragma experimental ABIEncoderV2;
contract RewardDistributorStorage {
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Active brains of Unitroller
*/
Joetroller public joetroller;
struct RewardMarketState {
/// @notice The market's last updated joeBorrowIndex or joeSupplyIndex
uint224 index;
/// @notice The timestamp number the index was last updated at
uint32 timestamp;
}
/// @notice The portion of reward rate that each market currently receives
mapping(uint8 => mapping(address => uint256)) public rewardSpeeds;
/// @notice The JOE/AVAX market supply state for each market
mapping(uint8 => mapping(address => RewardMarketState)) public rewardSupplyState;
/// @notice The JOE/AVAX market borrow state for each market
mapping(uint8 => mapping(address => RewardMarketState)) public rewardBorrowState;
/// @notice The JOE/AVAX borrow index for each market for each supplier as of the last time they accrued reward
mapping(uint8 => mapping(address => mapping(address => uint256))) public rewardSupplierIndex;
/// @notice The JOE/AVAX borrow index for each market for each borrower as of the last time they accrued reward
mapping(uint8 => mapping(address => mapping(address => uint256))) public rewardBorrowerIndex;
/// @notice The JOE/AVAX accrued but not yet transferred to each user
mapping(uint8 => mapping(address => uint256)) public rewardAccrued;
/// @notice The initial reward index for a market
uint224 public constant rewardInitialIndex = 1e36;
/// @notice JOE token contract address
address public joeAddress;
}
contract RewardDistributor is RewardDistributorStorage, Exponential {
/// @notice Emitted when a new reward speed is calculated for a market
event RewardSpeedUpdated(uint8 rewardType, JToken indexed jToken, uint256 newSpeed);
/// @notice Emitted when JOE/AVAX is distributed to a supplier
event DistributedSupplierReward(
uint8 rewardType,
JToken indexed jToken,
address indexed supplier,
uint256 rewardDelta,
uint256 rewardSupplyIndex
);
/// @notice Emitted when JOE/AVAX is distributed to a borrower
event DistributedBorrowerReward(
uint8 rewardType,
JToken indexed jToken,
address indexed borrower,
uint256 rewardDelta,
uint256 rewardBorrowIndex
);
/// @notice Emitted when JOE is granted by admin
event RewardGranted(uint8 rewardType, address recipient, uint256 amount);
bool private initialized;
constructor() public {
admin = msg.sender;
}
function initialize() public {
require(!initialized, "RewardDistributor already initialized");
joetroller = Joetroller(msg.sender);
initialized = true;
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == address(joetroller);
}
/**
* @notice Set JOE/AVAX speed for a single market
* @param rewardType 0 = QI, 1 = AVAX
* @param jToken The market whose reward speed to update
* @param rewardSpeed New reward speed for market
*/
function _setRewardSpeed(
uint8 rewardType,
JToken jToken,
uint256 rewardSpeed
) public {
require(rewardType <= 1, "rewardType is invalid");
require(adminOrInitializing(), "only admin can set reward speed");
setRewardSpeedInternal(rewardType, jToken, rewardSpeed);
}
/**
* @notice Set JOE/AVAX speed for a single market
* @param rewardType 0: JOE, 1: AVAX
* @param jToken The market whose speed to update
* @param newSpeed New JOE or AVAX speed for market
*/
function setRewardSpeedInternal(
uint8 rewardType,
JToken jToken,
uint256 newSpeed
) internal {
uint256 currentRewardSpeed = rewardSpeeds[rewardType][address(jToken)];
if (currentRewardSpeed != 0) {
// note that JOE speed could be set to 0 to halt liquidity rewards for a market
Exp memory borrowIndex = Exp({mantissa: jToken.borrowIndex()});
updateRewardSupplyIndex(rewardType, address(jToken));
updateRewardBorrowIndex(rewardType, address(jToken), borrowIndex);
} else if (newSpeed != 0) {
// Add the JOE market
require(joetroller.isMarketListed(address(jToken)), "reward market is not listed");
if (
rewardSupplyState[rewardType][address(jToken)].index == 0 &&
rewardSupplyState[rewardType][address(jToken)].timestamp == 0
) {
rewardSupplyState[rewardType][address(jToken)] = RewardMarketState({
index: rewardInitialIndex,
timestamp: safe32(getBlockTimestamp(), "block timestamp exceeds 32 bits")
});
}
if (
rewardBorrowState[rewardType][address(jToken)].index == 0 &&
rewardBorrowState[rewardType][address(jToken)].timestamp == 0
) {
rewardBorrowState[rewardType][address(jToken)] = RewardMarketState({
index: rewardInitialIndex,
timestamp: safe32(getBlockTimestamp(), "block timestamp exceeds 32 bits")
});
}
}
if (currentRewardSpeed != newSpeed) {
rewardSpeeds[rewardType][address(jToken)] = newSpeed;
emit RewardSpeedUpdated(rewardType, jToken, newSpeed);
}
}
/**
* @notice Accrue JOE/AVAX to the market by updating the supply index
* @param rewardType 0: JOE, 1: AVAX
* @param jToken The market whose supply index to update
*/
function updateRewardSupplyIndex(uint8 rewardType, address jToken) internal {
require(rewardType <= 1, "rewardType is invalid");
RewardMarketState storage supplyState = rewardSupplyState[rewardType][jToken];
uint256 supplySpeed = rewardSpeeds[rewardType][jToken];
uint256 blockTimestamp = getBlockTimestamp();
uint256 deltaTimestamps = sub_(blockTimestamp, uint256(supplyState.timestamp));
if (deltaTimestamps > 0 && supplySpeed > 0) {
uint256 supplyTokens = JToken(jToken).totalSupply();
uint256 rewardAccrued = mul_(deltaTimestamps, supplySpeed);
Double memory ratio = supplyTokens > 0 ? fraction(rewardAccrued, supplyTokens) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: supplyState.index}), ratio);
rewardSupplyState[rewardType][jToken] = RewardMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
timestamp: safe32(blockTimestamp, "block timestamp exceeds 32 bits")
});
} else if (deltaTimestamps > 0) {
supplyState.timestamp = safe32(blockTimestamp, "block timestamp exceeds 32 bits");
}
}
/**
* @notice Accrue JOE/AVAX to the market by updating the borrow index
* @param rewardType 0: JOE, 1: AVAX
* @param jToken The market whose borrow index to update
*/
function updateRewardBorrowIndex(
uint8 rewardType,
address jToken,
Exp memory marketBorrowIndex
) internal {
require(rewardType <= 1, "rewardType is invalid");
RewardMarketState storage borrowState = rewardBorrowState[rewardType][jToken];
uint256 borrowSpeed = rewardSpeeds[rewardType][jToken];
uint256 blockTimestamp = getBlockTimestamp();
uint256 deltaTimestamps = sub_(blockTimestamp, uint256(borrowState.timestamp));
if (deltaTimestamps > 0 && borrowSpeed > 0) {
uint256 borrowAmount = div_(JToken(jToken).totalBorrows(), marketBorrowIndex);
uint256 rewardAccrued = mul_(deltaTimestamps, borrowSpeed);
Double memory ratio = borrowAmount > 0 ? fraction(rewardAccrued, borrowAmount) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: borrowState.index}), ratio);
rewardBorrowState[rewardType][jToken] = RewardMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
timestamp: safe32(blockTimestamp, "block timestamp exceeds 32 bits")
});
} else if (deltaTimestamps > 0) {
borrowState.timestamp = safe32(blockTimestamp, "block timestamp exceeds 32 bits");
}
}
/**
* @notice Calculate JOE/AVAX accrued by a supplier and possibly transfer it to them
* @param rewardType 0: JOE, 1: AVAX
* @param jToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute JOE/AVAX to
*/
function distributeSupplierReward(
uint8 rewardType,
address jToken,
address supplier
) internal {
require(rewardType <= 1, "rewardType is invalid");
RewardMarketState storage supplyState = rewardSupplyState[rewardType][jToken];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: rewardSupplierIndex[rewardType][jToken][supplier]});
rewardSupplierIndex[rewardType][jToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = rewardInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint256 supplierTokens = JToken(jToken).balanceOf(supplier);
uint256 supplierDelta = mul_(supplierTokens, deltaIndex);
uint256 supplierAccrued = add_(rewardAccrued[rewardType][supplier], supplierDelta);
rewardAccrued[rewardType][supplier] = supplierAccrued;
emit DistributedSupplierReward(rewardType, JToken(jToken), supplier, supplierDelta, supplyIndex.mantissa);
}
/**
* @notice Calculate JOE/AVAX accrued by a borrower and possibly transfer it to them
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param rewardType 0: JOE, 1: AVAX
* @param jToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute JOE/AVAX to
*/
function distributeBorrowerReward(
uint8 rewardType,
address jToken,
address borrower,
Exp memory marketBorrowIndex
) internal {
require(rewardType <= 1, "rewardType is invalid");
RewardMarketState storage borrowState = rewardBorrowState[rewardType][jToken];
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: rewardBorrowerIndex[rewardType][jToken][borrower]});
rewardBorrowerIndex[rewardType][jToken][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint256 borrowerAmount = div_(JToken(jToken).borrowBalanceStored(borrower), marketBorrowIndex);
uint256 borrowerDelta = mul_(borrowerAmount, deltaIndex);
uint256 borrowerAccrued = add_(rewardAccrued[rewardType][borrower], borrowerDelta);
rewardAccrued[rewardType][borrower] = borrowerAccrued;
emit DistributedBorrowerReward(rewardType, JToken(jToken), borrower, borrowerDelta, borrowIndex.mantissa);
}
}
/**
* @notice Refactored function to calc and rewards accounts supplier rewards
* @param jToken The market to verify the mint against
* @param supplier The supplier to be rewarded
*/
function updateAndDistributeSupplierRewardsForToken(address jToken, address supplier) external {
require(adminOrInitializing(), "only admin can update and distribute supplier rewards");
for (uint8 rewardType = 0; rewardType <= 1; rewardType++) {
updateRewardSupplyIndex(rewardType, jToken);
distributeSupplierReward(rewardType, jToken, supplier);
}
}
/**
* @notice Refactored function to calc and rewards accounts supplier rewards
* @param jToken The market to verify the mint against
* @param borrower Borrower to be rewarded
*/
function updateAndDistributeBorrowerRewardsForToken(
address jToken,
address borrower,
Exp calldata marketBorrowIndex
) external {
require(adminOrInitializing(), "only admin can update and distribute borrower rewards");
for (uint8 rewardType = 0; rewardType <= 1; rewardType++) {
updateRewardBorrowIndex(rewardType, jToken, marketBorrowIndex);
distributeBorrowerReward(rewardType, jToken, borrower, marketBorrowIndex);
}
}
/*** User functions ***/
/**
* @notice Claim all the JOE/AVAX accrued by holder in all markets
* @param holder The address to claim JOE/AVAX for
*/
function claimReward(uint8 rewardType, address payable holder) public {
return claimReward(rewardType, holder, joetroller.getAllMarkets());
}
/**
* @notice Claim all the JOE/AVAX accrued by holder in the specified markets
* @param holder The address to claim JOE/AVAX for
* @param jTokens The list of markets to claim JOE/AVAX in
*/
function claimReward(
uint8 rewardType,
address payable holder,
JToken[] memory jTokens
) public {
address payable[] memory holders = new address payable[](1);
holders[0] = holder;
claimReward(rewardType, holders, jTokens, true, true);
}
/**
* @notice Claim all JOE/AVAX accrued by the holders
* @param rewardType 0 = JOE, 1 = AVAX
* @param holders The addresses to claim JOE/AVAX for
* @param jTokens The list of markets to claim JOE/AVAX in
* @param borrowers Whether or not to claim JOE/AVAX earned by borrowing
* @param suppliers Whether or not to claim JOE/AVAX earned by supplying
*/
function claimReward(
uint8 rewardType,
address payable[] memory holders,
JToken[] memory jTokens,
bool borrowers,
bool suppliers
) public payable {
require(rewardType <= 1, "rewardType is invalid");
for (uint256 i = 0; i < jTokens.length; i++) {
JToken jToken = jTokens[i];
require(joetroller.isMarketListed(address(jToken)), "market must be listed");
if (borrowers == true) {
Exp memory borrowIndex = Exp({mantissa: jToken.borrowIndex()});
updateRewardBorrowIndex(rewardType, address(jToken), borrowIndex);
for (uint256 j = 0; j < holders.length; j++) {
distributeBorrowerReward(rewardType, address(jToken), holders[j], borrowIndex);
rewardAccrued[rewardType][holders[j]] = grantRewardInternal(
rewardType,
holders[j],
rewardAccrued[rewardType][holders[j]]
);
}
}
if (suppliers == true) {
updateRewardSupplyIndex(rewardType, address(jToken));
for (uint256 j = 0; j < holders.length; j++) {
distributeSupplierReward(rewardType, address(jToken), holders[j]);
rewardAccrued[rewardType][holders[j]] = grantRewardInternal(
rewardType,
holders[j],
rewardAccrued[rewardType][holders[j]]
);
}
}
}
}
/**
* @notice Transfer JOE/AVAX to the user
* @dev Note: If there is not enough JOE/AVAX, we do not perform the transfer all.
* @param user The address of the user to transfer JOE/AVAX to
* @param amount The amount of JOE/AVAX to (possibly) transfer
* @return The amount of JOE/AVAX which was NOT transferred to the user
*/
function grantRewardInternal(
uint256 rewardType,
address payable user,
uint256 amount
) internal returns (uint256) {
if (rewardType == 0) {
EIP20Interface joe = EIP20Interface(joeAddress);
uint256 joeRemaining = joe.balanceOf(address(this));
if (amount > 0 && amount <= joeRemaining) {
joe.transfer(user, amount);
return 0;
}
} else if (rewardType == 1) {
uint256 avaxRemaining = address(this).balance;
if (amount > 0 && amount <= avaxRemaining) {
user.transfer(amount);
return 0;
}
}
return amount;
}
/*** Joe Distribution Admin ***/
/**
* @notice Transfer JOE to the recipient
* @dev Note: If there is not enough JOE, we do not perform the transfer all.
* @param recipient The address of the recipient to transfer JOE to
* @param amount The amount of JOE to (possibly) transfer
*/
function _grantReward(
uint8 rewardType,
address payable recipient,
uint256 amount
) public {
require(adminOrInitializing(), "only admin can grant joe");
uint256 amountLeft = grantRewardInternal(rewardType, recipient, amount);
require(amountLeft == 0, "insufficient joe for grant");
emit RewardGranted(rewardType, recipient, amount);
}
/**
* @notice Set the JOE token address
*/
function setJoeAddress(address newJoeAddress) public {
require(msg.sender == admin, "only admin can set JOE");
joeAddress = newJoeAddress;
}
/**
* @notice Set the Joetroller address
*/
function setJoetroller(address _joetroller) public {
require(msg.sender == admin, "only admin can set Joetroller");
joetroller = Joetroller(_joetroller);
}
/**
* @notice Set the admin
*/
function setAdmin(address _newAdmin) public {
require(msg.sender == admin, "only admin can set admin");
admin = _newAdmin;
}
/**
* @notice payable function needed to receive AVAX
*/
function() external payable {}
function getBlockTimestamp() public view returns (uint256) {
return block.timestamp;
}
}
/**
* @title JoetrollerCore
* @dev Storage for the joetroller is at this address, while execution is delegated to the `joetrollerImplementation`.
* JTokens should reference this contract as their joetroller.
*/
contract Unitroller is UnitrollerAdminStorage, JoetrollerErrorReporter {
/**
* @notice Emitted when pendingJoetrollerImplementation is changed
*/
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
/**
* @notice Emitted when pendingJoetrollerImplementation is accepted, which means joetroller implementation is updated
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
constructor() public {
// Set admin to caller
admin = msg.sender;
}
/*** Admin Functions ***/
function _setPendingImplementation(address newPendingImplementation) public returns (uint256) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);
}
address oldPendingImplementation = pendingJoetrollerImplementation;
pendingJoetrollerImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingJoetrollerImplementation);
return uint256(Error.NO_ERROR);
}
/**
* @notice Accepts new implementation of joetroller. msg.sender must be pendingImplementation
* @dev Admin function for new implementation to accept it's role as implementation
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptImplementation() public returns (uint256) {
// Check caller is pendingImplementation and pendingImplementation ≠ address(0)
if (msg.sender != pendingJoetrollerImplementation || pendingJoetrollerImplementation == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);
}
// Save current values for inclusion in log
address oldImplementation = joetrollerImplementation;
address oldPendingImplementation = pendingJoetrollerImplementation;
joetrollerImplementation = pendingJoetrollerImplementation;
pendingJoetrollerImplementation = address(0);
emit NewImplementation(oldImplementation, joetrollerImplementation);
emit NewPendingImplementation(oldPendingImplementation, pendingJoetrollerImplementation);
return uint256(Error.NO_ERROR);
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address newPendingAdmin) public returns (uint256) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint256(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() public returns (uint256) {
// Check caller is pendingAdmin
if (msg.sender != pendingAdmin) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint256(Error.NO_ERROR);
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
function() external payable {
// delegate all other functions to current implementation
(bool success, ) = joetrollerImplementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 {
revert(free_mem_ptr, returndatasize)
}
default {
return(free_mem_ptr, returndatasize)
}
}
}
}
/**
* @title Compound's Joetroller Contract
* @author Compound (modified by Cream)
*/
contract Joetroller is JoetrollerV1Storage, JoetrollerInterface, JoetrollerErrorReporter, Exponential {
/// @notice Emitted when an admin supports a market
event MarketListed(JToken jToken);
/// @notice Emitted when an admin delists a market
event MarketDelisted(JToken jToken);
/// @notice Emitted when an account enters a market
event MarketEntered(JToken jToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(JToken jToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(JToken jToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPaused(JToken jToken, string action, bool pauseState);
/// @notice Emitted when borrow cap for a jToken is changed
event NewBorrowCap(JToken indexed jToken, uint256 newBorrowCap);
/// @notice Emitted when borrow cap guardian is changed
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);
/// @notice Emitted when supply cap for a jToken is changed
event NewSupplyCap(JToken indexed jToken, uint256 newSupplyCap);
/// @notice Emitted when supply cap guardian is changed
event NewSupplyCapGuardian(address oldSupplyCapGuardian, address newSupplyCapGuardian);
/// @notice Emitted when protocol's credit limit has changed
event CreditLimitChanged(address protocol, uint256 creditLimit);
/// @notice Emitted when jToken version is changed
event NewJTokenVersion(JToken jToken, Version oldVersion, Version newVersion);
// No collateralFactorMantissa may exceed this value
uint256 internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
constructor() public {
admin = msg.sender;
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (JToken[] memory) {
return allMarkets;
}
function getBlockTimestamp() public view returns (uint256) {
return block.timestamp;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (JToken[] memory) {
JToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param jToken The jToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, JToken jToken) external view returns (bool) {
return markets[address(jToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param jTokens The list of addresses of the jToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory jTokens) public returns (uint256[] memory) {
uint256 len = jTokens.length;
uint256[] memory results = new uint256[](len);
for (uint256 i = 0; i < len; i++) {
JToken jToken = JToken(jTokens[i]);
results[i] = uint256(addToMarketInternal(jToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param jToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(JToken jToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(jToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.version == Version.COLLATERALCAP) {
// register collateral for the borrower if the token is CollateralCap version.
JCollateralCapErc20Interface(address(jToken)).registerCollateral(borrower);
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(jToken);
emit MarketEntered(jToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param jTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address jTokenAddress) external returns (uint256) {
JToken jToken = JToken(jTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the jToken */
(uint256 oErr, uint256 tokensHeld, uint256 amountOwed, ) = jToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint256 allowed = redeemAllowedInternal(jTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[jTokenAddress];
if (marketToExit.version == Version.COLLATERALCAP) {
JCollateralCapErc20Interface(jTokenAddress).unregisterCollateral(msg.sender);
}
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint256(Error.NO_ERROR);
}
/* Set jToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete jToken from the account’s list of assets */
// load into memory for faster iteration
JToken[] memory userAssetList = accountAssets[msg.sender];
uint256 len = userAssetList.length;
uint256 assetIndex = len;
for (uint256 i = 0; i < len; i++) {
if (userAssetList[i] == jToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
JToken[] storage storedList = accountAssets[msg.sender];
if (assetIndex != storedList.length - 1) {
storedList[assetIndex] = storedList[storedList.length - 1];
}
storedList.length--;
emit MarketExited(jToken, msg.sender);
return uint256(Error.NO_ERROR);
}
/**
* @notice Return whether a specific market is listed or not
* @param jTokenAddress The address of the asset to be checked
* @return Whether or not the market is listed
*/
function isMarketListed(address jTokenAddress) public view returns (bool) {
return markets[jTokenAddress].isListed;
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param jToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(
address jToken,
address minter,
uint256 mintAmount
) external returns (uint256) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[jToken], "mint is paused");
require(!isCreditAccount(minter), "credit account cannot mint");
if (!isMarketListed(jToken)) {
return uint256(Error.MARKET_NOT_LISTED);
}
uint256 supplyCap = supplyCaps[jToken];
// Supply cap of 0 corresponds to unlimited supplying
if (supplyCap != 0) {
uint256 totalCash = JToken(jToken).getCash();
uint256 totalBorrows = JToken(jToken).totalBorrows();
uint256 totalReserves = JToken(jToken).totalReserves();
// totalSupplies = totalCash + totalBorrows - totalReserves
(MathError mathErr, uint256 totalSupplies) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
require(mathErr == MathError.NO_ERROR, "totalSupplies failed");
uint256 nextTotalSupplies = add_(totalSupplies, mintAmount);
require(nextTotalSupplies < supplyCap, "market supply cap reached");
}
// Keep the flywheel moving
RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jToken, minter);
return uint256(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param jToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(
address jToken,
address minter,
uint256 actualMintAmount,
uint256 mintTokens
) external {
// Shh - currently unused
jToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
closeFactorMantissa = closeFactorMantissa;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param jToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of jTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(
address jToken,
address redeemer,
uint256 redeemTokens
) external returns (uint256) {
uint256 allowed = redeemAllowedInternal(jToken, redeemer, redeemTokens);
if (allowed != uint256(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel going
RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jToken, redeemer);
return uint256(Error.NO_ERROR);
}
function redeemAllowedInternal(
address jToken,
address redeemer,
uint256 redeemTokens
) internal view returns (uint256) {
if (!isMarketListed(jToken)) {
return uint256(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[jToken].accountMembership[redeemer]) {
return uint256(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint256 shortfall) = getHypotheticalAccountLiquidityInternal(
redeemer,
JToken(jToken),
redeemTokens,
0
);
if (err != Error.NO_ERROR) {
return uint256(err);
}
if (shortfall > 0) {
return uint256(Error.INSUFFICIENT_LIQUIDITY);
}
return uint256(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param jToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(
address jToken,
address redeemer,
uint256 redeemAmount,
uint256 redeemTokens
) external {
// Shh - currently unused
jToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param jToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(
address jToken,
address borrower,
uint256 borrowAmount
) external returns (uint256) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[jToken], "borrow is paused");
if (!isMarketListed(jToken)) {
return uint256(Error.MARKET_NOT_LISTED);
}
if (!markets[jToken].accountMembership[borrower]) {
// only jTokens may call borrowAllowed if borrower not in market
require(msg.sender == jToken, "sender must be jToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(JToken(jToken), borrower);
if (err != Error.NO_ERROR) {
return uint256(err);
}
// it should be impossible to break the important invariant
assert(markets[jToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(JToken(jToken)) == 0) {
return uint256(Error.PRICE_ERROR);
}
uint256 borrowCap = borrowCaps[jToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint256 totalBorrows = JToken(jToken).totalBorrows();
uint256 nextTotalBorrows = add_(totalBorrows, borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint256 shortfall) = getHypotheticalAccountLiquidityInternal(
borrower,
JToken(jToken),
0,
borrowAmount
);
if (err != Error.NO_ERROR) {
return uint256(err);
}
if (shortfall > 0) {
return uint256(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel going
Exp memory borrowIndex = Exp({mantissa: JToken(jToken).borrowIndex()});
RewardDistributor(rewardDistributor).updateAndDistributeBorrowerRewardsForToken(jToken, borrower, borrowIndex);
return uint256(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param jToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(
address jToken,
address borrower,
uint256 borrowAmount
) external {
// Shh - currently unused
jToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
closeFactorMantissa = closeFactorMantissa;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param jToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address jToken,
address payer,
address borrower,
uint256 repayAmount
) external returns (uint256) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!isMarketListed(jToken)) {
return uint256(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel going
Exp memory borrowIndex = Exp({mantissa: JToken(jToken).borrowIndex()});
RewardDistributor(rewardDistributor).updateAndDistributeBorrowerRewardsForToken(jToken, borrower, borrowIndex);
return uint256(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param jToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address jToken,
address payer,
address borrower,
uint256 actualRepayAmount,
uint256 borrowerIndex
) external {
// Shh - currently unused
jToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
closeFactorMantissa = closeFactorMantissa;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param jTokenBorrowed Asset which was borrowed by the borrower
* @param jTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address jTokenBorrowed,
address jTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount
) external returns (uint256) {
require(!isCreditAccount(borrower), "cannot liquidate credit account");
// Shh - currently unused
liquidator;
if (!isMarketListed(jTokenBorrowed) || !isMarketListed(jTokenCollateral)) {
return uint256(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint256 shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint256(err);
}
if (shortfall == 0) {
return uint256(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint256 borrowBalance = JToken(jTokenBorrowed).borrowBalanceStored(borrower);
uint256 maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (repayAmount > maxClose) {
return uint256(Error.TOO_MUCH_REPAY);
}
return uint256(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param jTokenBorrowed Asset which was borrowed by the borrower
* @param jTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address jTokenBorrowed,
address jTokenCollateral,
address liquidator,
address borrower,
uint256 actualRepayAmount,
uint256 seizeTokens
) external {
// Shh - currently unused
jTokenBorrowed;
jTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
closeFactorMantissa = closeFactorMantissa;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param jTokenCollateral Asset which was used as collateral and will be seized
* @param jTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address jTokenCollateral,
address jTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
require(!isCreditAccount(borrower), "cannot sieze from credit account");
// Shh - currently unused
liquidator;
seizeTokens;
if (!isMarketListed(jTokenCollateral) || !isMarketListed(jTokenBorrowed)) {
return uint256(Error.MARKET_NOT_LISTED);
}
if (JToken(jTokenCollateral).joetroller() != JToken(jTokenBorrowed).joetroller()) {
return uint256(Error.JOETROLLER_MISMATCH);
}
// Keep the flywheel moving
RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jTokenCollateral, borrower);
RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jTokenCollateral, liquidator);
return uint256(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param jTokenCollateral Asset which was used as collateral and will be seized
* @param jTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address jTokenCollateral,
address jTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external {
// Shh - currently unused
jTokenCollateral;
jTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
closeFactorMantissa = closeFactorMantissa;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param jToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of jTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(
address jToken,
address src,
address dst,
uint256 transferTokens
) external returns (uint256) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
require(!isCreditAccount(dst), "cannot transfer to a credit account");
// Shh - currently unused
dst;
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint256 allowed = redeemAllowedInternal(jToken, src, transferTokens);
if (allowed != uint256(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jToken, src);
RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jToken, dst);
return uint256(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param jToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of jTokens to transfer
*/
function transferVerify(
address jToken,
address src,
address dst,
uint256 transferTokens
) external {
// Shh - currently unused
jToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
closeFactorMantissa = closeFactorMantissa;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param jToken The market to verify the transfer against
* @param receiver The account which receives the tokens
* @param amount The amount of the tokens
* @param params The other parameters
*/
function flashloanAllowed(
address jToken,
address receiver,
uint256 amount,
bytes calldata params
) external view returns (bool) {
return !flashloanGuardianPaused[jToken];
}
/**
* @notice Update JToken's version.
* @param jToken Version of the asset being updated
* @param newVersion The new version
*/
function updateJTokenVersion(address jToken, Version newVersion) external {
require(msg.sender == jToken, "only jToken could update its version");
// This function will be called when a new JToken implementation becomes active.
// If a new JToken is newly created, this market is not listed yet. The version of
// this market will be taken care of when calling `_supportMarket`.
if (isMarketListed(jToken)) {
Version oldVersion = markets[jToken].version;
markets[jToken].version = newVersion;
emit NewJTokenVersion(JToken(jToken), oldVersion, newVersion);
}
}
/**
* @notice Check if the account is a credit account
* @param account The account needs to be checked
* @return The account is a credit account or not
*/
function isCreditAccount(address account) public view returns (bool) {
return creditLimits[account] > 0;
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `jTokenBalance` is the number of jTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint256 sumCollateral;
uint256 sumBorrowPlusEffects;
uint256 jTokenBalance;
uint256 borrowBalance;
uint256 exchangeRateMantissa;
uint256 oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account)
public
view
returns (
uint256,
uint256,
uint256
)
{
(Error err, uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal(
account,
JToken(0),
0,
0
);
return (uint256(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account)
internal
view
returns (
Error,
uint256,
uint256
)
{
return getHypotheticalAccountLiquidityInternal(account, JToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param jTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address jTokenModify,
uint256 redeemTokens,
uint256 borrowAmount
)
public
view
returns (
uint256,
uint256,
uint256
)
{
(Error err, uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal(
account,
JToken(jTokenModify),
redeemTokens,
borrowAmount
);
return (uint256(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param jTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral jToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
JToken jTokenModify,
uint256 redeemTokens,
uint256 borrowAmount
)
internal
view
returns (
Error,
uint256,
uint256
)
{
// If credit limit is set to MAX, no need to check account liquidity.
if (creditLimits[account] == uint256(-1)) {
return (Error.NO_ERROR, uint256(-1), 0);
}
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint256 oErr;
// For each asset the account is in
JToken[] memory assets = accountAssets[account];
for (uint256 i = 0; i < assets.length; i++) {
JToken asset = assets[i];
// Read the balances and exchange rate from the jToken
(oErr, vars.jTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(
account
);
if (oErr != 0) {
// semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
// Unlike compound protocol, getUnderlyingPrice is relatively expensive because we use ChainLink as our primary price feed.
// If user has no supply / borrow balance on this asset, and user is not redeeming / borrowing this asset, skip it.
if (vars.jTokenBalance == 0 && vars.borrowBalance == 0 && asset != jTokenModify) {
continue;
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> ether (normalized price value)
vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice);
// sumCollateral += tokensToDenom * jTokenBalance
vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.jTokenBalance, vars.sumCollateral);
// sumBorrowPlusEffects += oraclePrice * borrowBalance
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(
vars.oraclePrice,
vars.borrowBalance,
vars.sumBorrowPlusEffects
);
// Calculate effects of interacting with jTokenModify
if (asset == jTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(
vars.tokensToDenom,
redeemTokens,
vars.sumBorrowPlusEffects
);
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(
vars.oraclePrice,
borrowAmount,
vars.sumBorrowPlusEffects
);
}
}
// If credit limit is set, no need to consider collateral.
if (creditLimits[account] > 0) {
vars.sumCollateral = creditLimits[account];
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in jToken.liquidateBorrowFresh)
* @param jTokenBorrowed The address of the borrowed jToken
* @param jTokenCollateral The address of the collateral jToken
* @param actualRepayAmount The amount of jTokenBorrowed underlying to convert into jTokenCollateral tokens
* @return (errorCode, number of jTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(
address jTokenBorrowed,
address jTokenCollateral,
uint256 actualRepayAmount
) external view returns (uint256, uint256) {
/* Read oracle prices for borrowed and collateral markets */
uint256 priceBorrowedMantissa = oracle.getUnderlyingPrice(JToken(jTokenBorrowed));
uint256 priceCollateralMantissa = oracle.getUnderlyingPrice(JToken(jTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint256(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint256 exchangeRateMantissa = JToken(jTokenCollateral).exchangeRateStored(); // Note: reverts on error
Exp memory numerator = mul_(
Exp({mantissa: liquidationIncentiveMantissa}),
Exp({mantissa: priceBorrowedMantissa})
);
Exp memory denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa}));
Exp memory ratio = div_(numerator, denominator);
uint256 seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount);
return (uint256(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
function _setRewardDistributor(address payable newRewardDistributor) public returns (uint256) {
if (msg.sender != admin) {
return uint256(Error.UNAUTHORIZED);
}
(bool success, ) = newRewardDistributor.call.value(0)(abi.encodeWithSignature("initialize()", 0));
if (!success) {
return uint256(Error.REJECTION);
}
address oldRewardDistributor = rewardDistributor;
rewardDistributor = newRewardDistributor;
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets a new price oracle for the joetroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint256) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the joetroller
PriceOracle oldOracle = oracle;
// Set joetroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCloseFactor(uint256 newCloseFactorMantissa) external returns (uint256) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK);
}
uint256 oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param jToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(JToken jToken, uint256 newCollateralFactorMantissa) external returns (uint256) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(jToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(jToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint256 oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(jToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external returns (uint256) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Save current value for use in log
uint256 oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint256(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param jToken The address of the market (token) to list
* @param version The version of the market (token)
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(JToken jToken, Version version) external returns (uint256) {
require(msg.sender == admin, "only admin may support market");
require(!isMarketListed(address(jToken)), "market already listed");
jToken.isJToken(); // Sanity check to make sure its really a JToken
markets[address(jToken)] = Market({isListed: true, collateralFactorMantissa: 0, version: version});
_addMarketInternal(address(jToken));
emit MarketListed(jToken);
return uint256(Error.NO_ERROR);
}
/**
* @notice Remove the market from the markets mapping
* @param jToken The address of the market (token) to delist
*/
function _delistMarket(JToken jToken) external {
require(msg.sender == admin, "only admin may delist market");
require(isMarketListed(address(jToken)), "market not listed");
require(jToken.totalSupply() == 0, "market not empty");
jToken.isJToken(); // Sanity check to make sure its really a JToken
delete markets[address(jToken)];
for (uint256 i = 0; i < allMarkets.length; i++) {
if (allMarkets[i] == jToken) {
allMarkets[i] = allMarkets[allMarkets.length - 1];
delete allMarkets[allMarkets.length - 1];
allMarkets.length--;
break;
}
}
emit MarketDelisted(jToken);
}
function _addMarketInternal(address jToken) internal {
for (uint256 i = 0; i < allMarkets.length; i++) {
require(allMarkets[i] != JToken(jToken), "market already added");
}
allMarkets.push(JToken(jToken));
}
/**
* @notice Admin function to change the Supply Cap Guardian
* @param newSupplyCapGuardian The address of the new Supply Cap Guardian
*/
function _setSupplyCapGuardian(address newSupplyCapGuardian) external {
require(msg.sender == admin, "only admin can set supply cap guardian");
// Save current value for inclusion in log
address oldSupplyCapGuardian = supplyCapGuardian;
// Store supplyCapGuardian with value newSupplyCapGuardian
supplyCapGuardian = newSupplyCapGuardian;
// Emit NewSupplyCapGuardian(OldSupplyCapGuardian, NewSupplyCapGuardian)
emit NewSupplyCapGuardian(oldSupplyCapGuardian, newSupplyCapGuardian);
}
/**
* @notice Set the given supply caps for the given jToken markets. Supplying that brings total supplys to or above supply cap will revert.
* @dev Admin or supplyCapGuardian function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying. If the total borrows
* already exceeded the cap, it will prevent anyone to borrow.
* @param jTokens The addresses of the markets (tokens) to change the supply caps for
* @param newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying.
*/
function _setMarketSupplyCaps(JToken[] calldata jTokens, uint256[] calldata newSupplyCaps) external {
require(
msg.sender == admin || msg.sender == supplyCapGuardian,
"only admin or supply cap guardian can set supply caps"
);
uint256 numMarkets = jTokens.length;
uint256 numSupplyCaps = newSupplyCaps.length;
require(numMarkets != 0 && numMarkets == numSupplyCaps, "invalid input");
for (uint256 i = 0; i < numMarkets; i++) {
supplyCaps[address(jTokens[i])] = newSupplyCaps[i];
emit NewSupplyCap(jTokens[i], newSupplyCaps[i]);
}
}
/**
* @notice Set the given borrow caps for the given jToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. If the total supplies
* already exceeded the cap, it will prevent anyone to mint.
* @param jTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(JToken[] calldata jTokens, uint256[] calldata newBorrowCaps) external {
require(
msg.sender == admin || msg.sender == borrowCapGuardian,
"only admin or borrow cap guardian can set borrow caps"
);
uint256 numMarkets = jTokens.length;
uint256 numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for (uint256 i = 0; i < numMarkets; i++) {
borrowCaps[address(jTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(jTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian) external {
require(msg.sender == admin, "only admin can set borrow cap guardian");
// Save current value for inclusion in log
address oldBorrowCapGuardian = borrowCapGuardian;
// Store borrowCapGuardian with value newBorrowCapGuardian
borrowCapGuardian = newBorrowCapGuardian;
// Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)
emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public returns (uint256) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint256(Error.NO_ERROR);
}
function _setMintPaused(JToken jToken, bool state) public returns (bool) {
require(isMarketListed(address(jToken)), "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
mintGuardianPaused[address(jToken)] = state;
emit ActionPaused(jToken, "Mint", state);
return state;
}
function _setBorrowPaused(JToken jToken, bool state) public returns (bool) {
require(isMarketListed(address(jToken)), "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
borrowGuardianPaused[address(jToken)] = state;
emit ActionPaused(jToken, "Borrow", state);
return state;
}
function _setFlashloanPaused(JToken jToken, bool state) public returns (bool) {
require(isMarketListed(address(jToken)), "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
flashloanGuardianPaused[address(jToken)] = state;
emit ActionPaused(jToken, "Flashloan", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _become(Unitroller unitroller) public {
require(msg.sender == unitroller.admin(), "only unitroller admin can change brains");
require(unitroller._acceptImplementation() == 0, "change not authorized");
}
/**
* @notice Sets whitelisted protocol's credit limit
* @param protocol The address of the protocol
* @param creditLimit The credit limit
*/
function _setCreditLimit(address protocol, uint256 creditLimit) public {
require(msg.sender == admin, "only admin can set protocol credit limit");
creditLimits[protocol] = creditLimit;
emit CreditLimitChanged(protocol, creditLimit);
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == joetrollerImplementation;
}
/*** Reward distribution functions ***/
/**
* @notice Claim all the JOE/AVAX accrued by holder in all markets
* @param holder The address to claim JOE/AVAX for
*/
function claimReward(uint8 rewardType, address payable holder) public {
RewardDistributor(rewardDistributor).claimReward(rewardType, holder);
}
/**
* @notice Claim all the JOE/AVAX accrued by holder in the specified markets
* @param holder The address to claim JOE/AVAX for
* @param jTokens The list of markets to claim JOE/AVAX in
*/
function claimReward(
uint8 rewardType,
address payable holder,
JToken[] memory jTokens
) public {
RewardDistributor(rewardDistributor).claimReward(rewardType, holder, jTokens);
}
/**
* @notice Claim all JOE/AVAX accrued by the holders
* @param rewardType 0 = JOE, 1 = AVAX
* @param holders The addresses to claim JOE/AVAX for
* @param jTokens The list of markets to claim JOE/AVAX in
* @param borrowers Whether or not to claim JOE/AVAX earned by borrowing
* @param suppliers Whether or not to claim JOE/AVAX earned by supplying
*/
function claimReward(
uint8 rewardType,
address payable[] memory holders,
JToken[] memory jTokens,
bool borrowers,
bool suppliers
) public payable {
RewardDistributor(rewardDistributor).claimReward(rewardType, holders, jTokens, borrowers, suppliers);
}
}
|
Accepts transfer of admin rights. msg.sender must be pendingAdmin Admin function for pending admin to accept role and update admin return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ Check caller is pendingAdmin
|
function _acceptAdmin() public returns (uint256) {
if (msg.sender != pendingAdmin) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
address oldPendingAdmin = pendingAdmin;
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint256(Error.NO_ERROR);
}
| 1,810,204
|
/**
* @authors: [@mtsalenc]
* @reviewers: []
* @auditors: []
* @bounties: []
* @deployments: []
*/
pragma solidity ^0.5.17;
interface IArbitrableTCR {
enum Party {
None, // Party per default when there is no challenger or requester. Also used for unconclusive ruling.
Requester, // Party that made the request to change an address status.
Challenger // Party that challenges the request to change an address status.
}
function governor() external view returns(address);
function arbitrator() external view returns(address);
function arbitratorExtraData() external view returns(bytes memory);
function requesterBaseDeposit() external view returns(uint);
function challengerBaseDeposit() external view returns(uint);
function challengePeriodDuration() external view returns(uint);
function metaEvidenceUpdates() external view returns(uint);
function winnerStakeMultiplier() external view returns(uint);
function loserStakeMultiplier() external view returns(uint);
function sharedStakeMultiplier() external view returns(uint);
function MULTIPLIER_DIVISOR() external view returns(uint);
function countByStatus()
external
view
returns(
uint absent,
uint registered,
uint registrationRequest,
uint clearingRequest,
uint challengedRegistrationRequest,
uint challengedClearingRequest
);
}
interface IArbitrableAddressTCR {
enum AddressStatus {
Absent, // The address is not in the registry.
Registered, // The address is in the registry.
RegistrationRequested, // The address has a request to be added to the registry.
ClearingRequested // The address has a request to be removed from the registry.
}
function addressCount() external view returns(uint);
function addressList(uint index) external view returns(address);
function getAddressInfo(address _address)
external
view
returns (
AddressStatus status,
uint numberOfRequests
);
function getRequestInfo(address _address, uint _request)
external
view
returns (
bool disputed,
uint disputeID,
uint submissionTime,
bool resolved,
address[3] memory parties,
uint numberOfRounds,
IArbitrableTCR.Party ruling,
address arbitrator,
bytes memory arbitratorExtraData
);
function getRoundInfo(address _address, uint _request, uint _round)
external
view
returns (
bool appealed,
uint[3] memory paidFees,
bool[3] memory hasPaid,
uint feeRewards
);
}
interface IArbitrableTokenTCR {
enum TokenStatus {
Absent, // The address is not in the registry.
Registered, // The address is in the registry.
RegistrationRequested, // The address has a request to be added to the registry.
ClearingRequested // The address has a request to be removed from the registry.
}
function tokenCount() external view returns(uint);
function tokensList(uint index) external view returns(bytes32);
function getTokenInfo(bytes32 _tokenID)
external
view
returns (
string memory name,
string memory ticker,
address addr,
string memory symbolMultihash,
TokenStatus status,
uint numberOfRequests
);
function getRequestInfo(bytes32 _tokenID, uint _request)
external
view
returns (
bool disputed,
uint disputeID,
uint submissionTime,
bool resolved,
address[3] memory parties,
uint numberOfRounds,
IArbitrableTCR.Party ruling,
address arbitrator,
bytes memory arbitratorExtraData
);
function getRoundInfo(bytes32 _tokenID, uint _request, uint _round)
external
view
returns (
bool appealed,
uint[3] memory paidFees,
bool[3] memory hasPaid,
uint feeRewards
);
function addressToSubmissions(address _addr, uint _index) external view returns (bytes32);
}
interface IArbitrator {
enum DisputeStatus {Waiting, Appealable, Solved}
function createDispute(uint _choices, bytes calldata _extraData) external payable returns(uint disputeID);
function arbitrationCost(bytes calldata _extraData) external view returns(uint cost);
function appeal(uint _disputeID, bytes calldata _extraData) external payable;
function appealCost(uint _disputeID, bytes calldata _extraData) external view returns(uint cost);
function appealPeriod(uint _disputeID) external view returns(uint start, uint end);
function disputeStatus(uint _disputeID) external view returns(DisputeStatus status);
function currentRuling(uint _disputeID) external view returns(uint ruling);
}
pragma experimental ABIEncoderV2;
contract ArbitrableTCRViewV2 {
struct CountByStatus {
uint absent;
uint registered;
uint registrationRequest;
uint clearingRequest;
uint challengedRegistrationRequest;
uint challengedClearingRequest;
}
struct ArbitrableTCRData {
address governor;
address arbitrator;
bytes arbitratorExtraData;
uint requesterBaseDeposit;
uint challengerBaseDeposit;
uint challengePeriodDuration;
uint metaEvidenceUpdates;
uint winnerStakeMultiplier;
uint loserStakeMultiplier;
uint sharedStakeMultiplier;
uint MULTIPLIER_DIVISOR;
CountByStatus countByStatus;
uint arbitrationCost;
}
struct Token {
bytes32 ID;
string name;
string ticker;
address addr;
string symbolMultihash;
IArbitrableTokenTCR.TokenStatus status;
uint decimals;
}
// Some arrays below have 3 elements to map with the Party enums for better readability:
// - 0: is unused, matches `Party.None`.
// - 1: for `Party.Requester`.
// - 2: for `Party.Challenger`.
struct Request {
bool disputed;
uint disputeID;
uint submissionTime;
bool resolved;
address[3] parties;
uint numberOfRounds;
IArbitrableTCR.Party ruling;
address arbitrator;
bytes arbitratorExtraData;
IArbitrator.DisputeStatus disputeStatus;
uint currentRuling;
uint appealCost;
uint[3] requiredForSide;
uint[2] appealPeriod;
}
struct Round {
uint[3] paidFees; // Tracks the fees paid by each side on this round.
bool[3] hasPaid; // True when the side has fully paid its fee. False otherwise.
uint feeRewards; // Sum of reimbursable fees and stake rewards available to the parties that made contributions to the side that ultimately wins a dispute.
}
struct AppealableToken {
uint disputeID;
address arbitrator;
bytes32 tokenID;
bool inAppealPeriod;
}
struct AppealableAddress {
uint disputeID;
address arbitrator;
address addr;
bool inAppealPeriod;
}
/** @dev Fetch arbitrable TCR data in a single call.
* @param _address The address of the Generalized TCR to query.
* @return The latest data on an arbitrable TCR contract.
*/
function fetchArbitrable(address _address) public view returns (ArbitrableTCRData memory result) {
IArbitrableTCR tcr = IArbitrableTCR(_address);
result.governor = tcr.governor();
result.arbitrator = tcr.arbitrator();
result.arbitratorExtraData = tcr.arbitratorExtraData();
result.requesterBaseDeposit = tcr.requesterBaseDeposit();
result.challengerBaseDeposit = tcr.challengerBaseDeposit();
result.challengePeriodDuration = tcr.challengePeriodDuration();
result.metaEvidenceUpdates = tcr.metaEvidenceUpdates();
result.winnerStakeMultiplier = tcr.winnerStakeMultiplier();
result.loserStakeMultiplier = tcr.loserStakeMultiplier();
result.sharedStakeMultiplier = tcr.sharedStakeMultiplier();
result.MULTIPLIER_DIVISOR = tcr.MULTIPLIER_DIVISOR();
{
(
uint absent,
uint registered,
uint registrationRequest,
uint clearingRequest,
uint challengedRegistrationRequest,
uint challengedClearingRequest
) = tcr.countByStatus();
result.countByStatus = CountByStatus({
absent: absent,
registered: registered,
registrationRequest: registrationRequest,
clearingRequest: clearingRequest,
challengedRegistrationRequest: challengedRegistrationRequest,
challengedClearingRequest: challengedClearingRequest
});
}
IArbitrator arbitrator = IArbitrator(result.arbitrator);
result.arbitrationCost = arbitrator.arbitrationCost(result.arbitratorExtraData);
}
function fetchAppealableAddresses(address _addressTCR, uint _cursor, uint _count) external view returns (AppealableAddress[] memory results) {
IArbitrableAddressTCR tcr = IArbitrableAddressTCR(_addressTCR);
results = new AppealableAddress[]( tcr.addressCount() < _count ? tcr.addressCount() : _count);
for (uint i = _cursor; i < tcr.addressCount() && _count - i > 0; i++) {
address itemAddr = tcr.addressList(i);
(
IArbitrableAddressTCR.AddressStatus status,
uint numberOfRequests
) = tcr.getAddressInfo(itemAddr);
if (status == IArbitrableAddressTCR.AddressStatus.Absent || status == IArbitrableAddressTCR.AddressStatus.Registered) continue;
// Using arrays to get around stack limit.
bool[] memory disputedResolved = new bool[](2);
uint[] memory disputeIDNumberOfRounds = new uint[](2);
address arbitrator;
(
disputedResolved[0],
disputeIDNumberOfRounds[0],
,
disputedResolved[1],
,
disputeIDNumberOfRounds[1],
,
arbitrator,
) = tcr.getRequestInfo(itemAddr, numberOfRequests - 1);
if (!disputedResolved[0] || disputedResolved[1]) continue;
IArbitrator arbitratorContract = IArbitrator(arbitrator);
uint[] memory appealPeriod = new uint[](2);
(appealPeriod[0], appealPeriod[1]) = arbitratorContract.appealPeriod(disputeIDNumberOfRounds[0]);
if (appealPeriod[0] > 0 && appealPeriod[1] > 0) {
results[i] = AppealableAddress({
disputeID: disputeIDNumberOfRounds[0],
arbitrator: arbitrator,
addr: itemAddr,
inAppealPeriod: now < appealPeriod[1]
});
// If the arbitrator gave a decisive ruling (i.e. did not rule for Party.None)
// we must check if the loser fully funded and the dispute is in the second half
// of the appeal period. If the dispute is in the second half, and the loser is not
// funded the appeal period is over.
IArbitrableTCR.Party currentRuling = IArbitrableTCR.Party(arbitratorContract.currentRuling(disputeIDNumberOfRounds[0]));
if (
currentRuling != IArbitrableTCR.Party.None &&
now > (appealPeriod[1] - appealPeriod[0]) / 2 + appealPeriod[0]
) {
IArbitrableTCR.Party loser = currentRuling == IArbitrableTCR.Party.Requester
? IArbitrableTCR.Party.Challenger
: IArbitrableTCR.Party.Requester;
(
,
,
bool[3] memory hasPaid,
) = tcr.getRoundInfo(itemAddr, numberOfRequests - 1, disputeIDNumberOfRounds[1] - 1);
if(!hasPaid[uint(loser)]) results[i].inAppealPeriod = false;
}
}
}
}
function fetchAppealableToken(address _addressTCR, uint _cursor, uint _count) external view returns (AppealableToken[] memory results) {
IArbitrableTokenTCR tcr = IArbitrableTokenTCR(_addressTCR);
results = new AppealableToken[](tcr.tokenCount() < _count ? tcr.tokenCount() : _count);
for (uint i = _cursor; i < tcr.tokenCount() && _count - i > 0; i++) {
bytes32 tokenID = tcr.tokensList(i);
(
,
,
,
,
IArbitrableTokenTCR.TokenStatus status,
uint numberOfRequests
) = tcr.getTokenInfo(tokenID);
if (status == IArbitrableTokenTCR.TokenStatus.Absent || status == IArbitrableTokenTCR.TokenStatus.Registered) continue;
// Using arrays to get around stack limit.
bool[] memory disputedResolved = new bool[](2);
uint[] memory disputeIDNumberOfRounds = new uint[](2);
address arbitrator;
(
disputedResolved[0],
disputeIDNumberOfRounds[0],
,
disputedResolved[1],
,
disputeIDNumberOfRounds[1],
,
arbitrator,
) = tcr.getRequestInfo(tokenID, numberOfRequests - 1);
if (!disputedResolved[0] || disputedResolved[1]) continue;
IArbitrator arbitratorContract = IArbitrator(arbitrator);
uint[] memory appealPeriod = new uint[](2);
(appealPeriod[0], appealPeriod[1]) = arbitratorContract.appealPeriod(disputeIDNumberOfRounds[0]);
if (appealPeriod[0] > 0 && appealPeriod[1] > 0) {
results[i] = AppealableToken({
disputeID: disputeIDNumberOfRounds[0],
arbitrator: arbitrator,
tokenID: tokenID,
inAppealPeriod: now < appealPeriod[1]
});
// If the arbitrator gave a decisive ruling (i.e. did not rule for Party.None)
// we must check if the loser fully funded and the dispute is in the second half
// of the appeal period. If the dispute is in the second half, and the loser is not
// funded the appeal period is over.
IArbitrableTCR.Party currentRuling = IArbitrableTCR.Party(arbitratorContract.currentRuling(disputeIDNumberOfRounds[0]));
if (
currentRuling != IArbitrableTCR.Party.None &&
now > (appealPeriod[1] - appealPeriod[0]) / 2 + appealPeriod[0]
) {
IArbitrableTCR.Party loser = currentRuling == IArbitrableTCR.Party.Requester
? IArbitrableTCR.Party.Challenger
: IArbitrableTCR.Party.Requester;
(
,
,
bool[3] memory hasPaid,
) = tcr.getRoundInfo(tokenID, numberOfRequests - 1, disputeIDNumberOfRounds[1] - 1);
if(!hasPaid[uint(loser)]) results[i].inAppealPeriod = false;
}
}
}
}
/** @dev Fetch token IDs of the first tokens present on the tcr for the addresses.
* @param _t2crAddress The address of the t2cr contract from where to fetch token information.
* @param _tokenAddresses The address of each token.
*/
function getTokensIDsForAddresses(
address _t2crAddress,
address[] calldata _tokenAddresses
) external view returns (bytes32[] memory result) {
IArbitrableTokenTCR t2cr = IArbitrableTokenTCR(_t2crAddress);
result = new bytes32[](_tokenAddresses.length);
for (uint i = 0; i < _tokenAddresses.length; i++){
// Count how many submissions were made for an address.
address tokenAddr = _tokenAddresses[i];
bool counting = true;
bytes4 sig = bytes4(keccak256("addressToSubmissions(address,uint256)"));
uint submissions = 0;
while(counting) {
assembly {
let x := mload(0x40) // Find empty storage location using "free memory pointer"
mstore(x, sig) // Set the signature to the first call parameter.
mstore(add(x, 0x04), tokenAddr)
mstore(add(x, 0x24), submissions)
counting := staticcall( // `counting` will be set to false if the call reverts (which will happen if we reached the end of the array.)
30000, // 30k gas
_t2crAddress, // The call target.
x, // Inputs are stored at location x
0x44, // Input is 44 bytes long (signature (4B) + address (20B) + index(20B))
x, // Overwrite x with output
0x20 // The output length
)
}
if (counting) {
submissions++;
}
}
// Search for the oldest submission currently in the registry.
for(uint j = 0; j < submissions; j++) {
bytes32 tokenID = t2cr.addressToSubmissions(tokenAddr, j);
(,,,,IArbitrableTokenTCR.TokenStatus status,) = t2cr.getTokenInfo(tokenID);
if (status == IArbitrableTokenTCR.TokenStatus.Registered || status == IArbitrableTokenTCR.TokenStatus.ClearingRequested)
{
result[i] = tokenID;
break;
}
}
}
}
/** @dev Fetch token information with token IDs. If a token contract does not implement the decimals() function, its decimals field will be 0.
* @param _t2crAddress The address of the t2cr contract from where to fetch token information.
* @param _tokenIDs The IDs of the tokens we want to query.
* @return tokens The tokens information.
*/
function getTokens(address _t2crAddress, bytes32[] calldata _tokenIDs)
external
view
returns (Token[] memory tokens)
{
IArbitrableTokenTCR t2cr = IArbitrableTokenTCR(_t2crAddress);
tokens = new Token[](_tokenIDs.length);
for (uint i = 0; i < _tokenIDs.length ; i++){
string[] memory strings = new string[](3); // name, ticker and symbolMultihash respectively.
address tokenAddress;
IArbitrableTokenTCR.TokenStatus status;
(
strings[0],
strings[1],
tokenAddress,
strings[2],
status,
) = t2cr.getTokenInfo(_tokenIDs[i]);
tokens[i] = Token(
_tokenIDs[i],
strings[0],
strings[1],
tokenAddress,
strings[2],
status,
0
);
// Call the contract's decimals() function without reverting when
// the contract does not implement it.
//
// Two things should be noted: if the contract does not implement the function
// and does not implement the contract fallback function, `success` will be set to
// false and decimals won't be set. However, in some cases (such as old contracts)
// the fallback function is implemented, and so staticcall will return true
// even though the value returned will not be correct (the number below):
//
// 22270923699561257074107342068491755213283769984150504402684791726686939079929
//
// We handle that edge case by also checking against this value.
uint decimals;
bool success;
bytes4 sig = bytes4(keccak256("decimals()"));
assembly {
let x := mload(0x40) // Find empty storage location using "free memory pointer"
mstore(x, sig) // Set the signature to the first call parameter. 0x313ce567 === bytes4(keccak256("decimals()")
success := staticcall(
30000, // 30k gas
tokenAddress, // The call target.
x, // Inputs are stored at location x
0x04, // Input is 4 bytes long
x, // Overwrite x with output
0x20 // The output length
)
decimals := mload(x)
}
if (success && decimals != 22270923699561257074107342068491755213283769984150504402684791726686939079929) {
tokens[i].decimals = decimals;
}
}
}
/** @dev Fetch token information in batches
* @param _t2crAddress The address of the t2cr contract from where to fetch token information.
* @param _cursor The index from where to start iterating.
* @param _count The number of items to iterate. If 0 is given, defaults to t2cr.tokenCount().
* @param _filter The filter to use. Each element of the array in sequence means:
* - Include absent addresses in result.
* - Include registered addresses in result.
* - Include addresses with registration requests that are not disputed in result.
* - Include addresses with clearing requests that are not disputed in result.
* - Include disputed addresses with registration requests in result.
* - Include disputed addresses with clearing requests in result.
* @return tokens The tokens information.
*/
function getTokensCursor(address _t2crAddress, uint _cursor, uint _count, bool[6] calldata _filter)
external
view
returns (Token[] memory tokens, bool hasMore)
{
IArbitrableTokenTCR t2cr = IArbitrableTokenTCR(_t2crAddress);
if (_count == 0) _count = t2cr.tokenCount();
if (_cursor >= t2cr.tokenCount()) _cursor = t2cr.tokenCount() - 1;
if (_cursor + _count > t2cr.tokenCount() - 1) _count = t2cr.tokenCount() - _cursor - 1;
if (_cursor + _count < t2cr.tokenCount() - 1) hasMore = true;
tokens = new Token[](_count);
uint index = 0;
for (uint i = _cursor; i < t2cr.tokenCount() && i < _cursor + _count ; i++){
bytes32 tokenID = t2cr.tokensList(i);
string[] memory strings = new string[](3); // name, ticker and symbolMultihash respectively.
address tokenAddress;
IArbitrableTokenTCR.TokenStatus status;
uint numberOfRequests;
(
strings[0],
strings[1],
tokenAddress,
strings[2],
status,
numberOfRequests
) = t2cr.getTokenInfo(tokenID);
tokens[index] = Token(
tokenID,
strings[0],
strings[1],
tokenAddress,
strings[2],
status,
0
);
(bool disputed,,,,,,,,) = t2cr.getRequestInfo(tokenID, numberOfRequests - 1);
if (
/* solium-disable operator-whitespace */
(_filter[0] && status == IArbitrableTokenTCR.TokenStatus.Absent) ||
(_filter[1] && status == IArbitrableTokenTCR.TokenStatus.Registered) ||
(_filter[2] && status == IArbitrableTokenTCR.TokenStatus.RegistrationRequested && !disputed) ||
(_filter[3] && status == IArbitrableTokenTCR.TokenStatus.ClearingRequested && !disputed) ||
(_filter[4] && status == IArbitrableTokenTCR.TokenStatus.RegistrationRequested && disputed) ||
(_filter[5] && status == IArbitrableTokenTCR.TokenStatus.ClearingRequested && disputed)
/* solium-enable operator-whitespace */
) {
if (index < _count) {
// Call the contract's decimals() function without reverting when
// the contract does not implement it.
//
// Two things should be noted: if the contract does not implement the function
// and does not implement the contract fallback function, `success` will be set to
// false and decimals won't be set. However, in some cases (such as old contracts)
// the fallback function is implemented, and so staticcall will return true
// even though the value returned will not be correct (the number below):
//
// 22270923699561257074107342068491755213283769984150504402684791726686939079929
//
// We handle that edge case by also checking against this value.
uint decimals;
bool success;
bytes4 sig = bytes4(keccak256("decimals()"));
assembly {
let x := mload(0x40) // Find empty storage location using "free memory pointer"
mstore(x, sig) // Set the signature to the first call parameter. 0x313ce567 === bytes4(keccak256("decimals()")
success := staticcall(
30000, // 30k gas
tokenAddress, // The call target.
x, // Inputs are stored at location x
0x04, // Input is 4 bytes long
x, // Overwrite x with output
0x20 // The output length
)
decimals := mload(x)
}
if (success && decimals != 22270923699561257074107342068491755213283769984150504402684791726686939079929) {
tokens[index].decimals = decimals;
}
index++;
} else {
hasMore = true;
break;
}
}
}
}
function getRequestDetails(address _t2crAddress, bytes32 _tokenID, uint _requestID) public view returns (Request memory request) {
IArbitrableTokenTCR t2cr = IArbitrableTokenTCR(_t2crAddress);
(
bool disputed,
uint disputeID,
uint submissionTime,
bool resolved,
address[3] memory parties,
uint numberOfRounds,
IArbitrableTCR.Party ruling,
address arbitrator,
bytes memory arbitratorExtraData
) = t2cr.getRequestInfo(_tokenID, _requestID);
request = Request(
disputed,
disputeID,
submissionTime,
resolved,
parties,
numberOfRounds,
ruling,
arbitrator,
arbitratorExtraData,
IArbitrator.DisputeStatus.Waiting,
0,
0,
[uint(0),uint(0),uint(0)],
[uint(0),uint(0)]
);
}
function getRequestsDetails(address _t2crAddress, bytes32 _tokenID) public view returns (
Request[10] memory requests // Ideally this should be resizable. In practice it is unlikely submissions will have more than 2 or 3 requests.
) {
IArbitrableTokenTCR t2cr = IArbitrableTokenTCR(_t2crAddress);
(,,,,, uint numberOfRequests) = t2cr.getTokenInfo(_tokenID);
for (uint256 i = 0; i < numberOfRequests; i++) {
Request memory request = getRequestDetails(_t2crAddress, _tokenID, i);
IArbitrator arbitrator = IArbitrator(request.arbitrator);
if (request.disputed) {
request.disputeStatus = arbitrator.disputeStatus(request.disputeID);
request.currentRuling = arbitrator.currentRuling(request.disputeID);
if (request.disputeStatus == IArbitrator.DisputeStatus.Appealable) {
request.appealCost = arbitrator.appealCost(request.disputeID, request.arbitratorExtraData);
ArbitrableTCRData memory arbitrableTCRData = fetchArbitrable(_t2crAddress);
if (request.ruling == IArbitrableTCR.Party.None) {
request.requiredForSide[1] = request.appealCost + request.appealCost * arbitrableTCRData.sharedStakeMultiplier / arbitrableTCRData.MULTIPLIER_DIVISOR;
request.requiredForSide[2] = request.appealCost + request.appealCost * arbitrableTCRData.sharedStakeMultiplier / arbitrableTCRData.MULTIPLIER_DIVISOR;
} else if (request.ruling == IArbitrableTCR.Party.Requester) {
request.requiredForSide[1] = request.appealCost + request.appealCost * arbitrableTCRData.winnerStakeMultiplier / arbitrableTCRData.MULTIPLIER_DIVISOR;
request.requiredForSide[2] = request.appealCost + request.appealCost * arbitrableTCRData.loserStakeMultiplier / arbitrableTCRData.MULTIPLIER_DIVISOR;
} else {
request.requiredForSide[1] = request.appealCost + request.appealCost * arbitrableTCRData.loserStakeMultiplier / arbitrableTCRData.MULTIPLIER_DIVISOR;
request.requiredForSide[2] = request.appealCost + request.appealCost * arbitrableTCRData.winnerStakeMultiplier / arbitrableTCRData.MULTIPLIER_DIVISOR;
}
(request.appealPeriod[0], request.appealPeriod[1]) = arbitrator.appealPeriod(request.disputeID);
}
}
requests[i] = request;
}
}
}
|
Fetch token information with token IDs. If a token contract does not implement the decimals() function, its decimals field will be 0. _t2crAddress The address of the t2cr contract from where to fetch token information. _tokenIDs The IDs of the tokens we want to query. return tokens The tokens information./ Call the contract's decimals() function without reverting when the contract does not implement it. Two things should be noted: if the contract does not implement the function and does not implement the contract fallback function, `success` will be set to false and decimals won't be set. However, in some cases (such as old contracts) the fallback function is implemented, and so staticcall will return true even though the value returned will not be correct (the number below): 22270923699561257074107342068491755213283769984150504402684791726686939079929 We handle that edge case by also checking against this value.
|
function getTokens(address _t2crAddress, bytes32[] calldata _tokenIDs)
external
view
returns (Token[] memory tokens)
{
IArbitrableTokenTCR t2cr = IArbitrableTokenTCR(_t2crAddress);
tokens = new Token[](_tokenIDs.length);
for (uint i = 0; i < _tokenIDs.length ; i++){
address tokenAddress;
IArbitrableTokenTCR.TokenStatus status;
(
strings[0],
strings[1],
tokenAddress,
strings[2],
status,
) = t2cr.getTokenInfo(_tokenIDs[i]);
tokens[i] = Token(
_tokenIDs[i],
strings[0],
strings[1],
tokenAddress,
strings[2],
status,
0
);
uint decimals;
bool success;
bytes4 sig = bytes4(keccak256("decimals()"));
assembly {
success := staticcall(
)
decimals := mload(x)
}
if (success && decimals != 22270923699561257074107342068491755213283769984150504402684791726686939079929) {
tokens[i].decimals = decimals;
}
}
}
| 2,222,149
|
./full_match/43113/0xe7d41CfCe28334209CD2bDEd2bB51BB521C1BF59/sources/BatchFlashDemo.sol
|
Rugpull all ERC20 tokens from the contract/ withdraw all x ERC20 tokens
|
function rugPull(address _asset) public payable onlyOwner {
IERC20(_asset).transfer(msg.sender, IERC20(_asset).balanceOf(address(this)));
}
| 7,114,451
|
./partial_match/1/0x2167525D8C894aD1e67Feb63BD98e01ea1E57ACC/sources/DWI.sol
|
Interface of the ERC20 standard as defined in the EIP./
|
interface IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
$DWI ain't sorry bout nothing, just deal with it
}
| 11,007,576
|
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.10;
// types
import "../types/BaseAllocator.sol";
interface ILendingPool {
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
}
interface IStakedTokenIncentivesController {
function claimRewards(
address[] memory assets,
uint256 amount,
address to
) external;
function claimRewardsOnBehalf(
address[] memory assets,
uint256 amount,
address user,
address to
) external;
function getRewardsBalance(address[] memory assets, address user) external view returns (uint256);
}
contract AaveAllocatorV2 is BaseAllocator {
address public constant treasury = 0x9A315BdF513367C0377FB36545857d12e85813Ef;
// stkAave incentive controller
IStakedTokenIncentivesController public immutable incentives =
IStakedTokenIncentivesController(0xd784927Ff2f95ba542BfC824c8a8a98F3495f6b5);
// Aave Lending Pool
ILendingPool public immutable pool = ILendingPool(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9);
IERC20[] internal _aTokens;
uint16 public referralCode;
constructor(AllocatorInitData memory data) BaseAllocator(data) {}
function _update(uint256 id) internal override returns (uint128 gain, uint128 loss) {
// reads
uint256 tokenId = tokenIds[id];
IERC20 token = _tokens[tokenId];
IERC20 aToken = _aTokens[tokenId];
uint256 balance = token.balanceOf(address(this));
// interactions
if (balance > 0) {
token.approve(address(pool), balance);
pool.deposit(address(token), balance, address(this), referralCode);
}
uint256 aBalance = aToken.balanceOf(address(this));
uint256 last = extender.getAllocatorAllocated(id) + extender.getAllocatorPerformance(id).gain;
// we can do this because aToken is 1:1 with deposited
if (aBalance >= last) {
gain = uint128(aBalance - last);
} else {
loss = uint128(last - aBalance);
}
}
function deallocate(uint256[] memory amounts) public override {
// checks
_onlyGuardian();
for (uint256 i; i < amounts.length; i++) {
uint256 amount = amounts[i];
if (amount > 0) {
IERC20 token = _tokens[i];
IERC20 aToken = _aTokens[i];
aToken.approve(address(pool), amount);
pool.withdraw(address(token), amount, address(this));
}
}
}
function _deactivate(bool panic) internal override {
_deallocateAll();
if (panic) {
for (uint256 i; i < _tokens.length; i++) {
IERC20 token = _tokens[i];
token.transfer(treasury, token.balanceOf(address(this)));
}
}
}
function _prepareMigration() internal override {}
function amountAllocated(uint256 id) public view override returns (uint256) {
return _aTokens[tokenIds[id]].balanceOf(address(this));
}
function rewardTokens() public pure override returns (IERC20[] memory) {
IERC20[] memory empty = new IERC20[](0);
return empty;
}
function name() external pure override returns (string memory) {
return "AaveAllocatorV2";
}
function addToken(address token) external {
_onlyGuardian();
_tokens.push(IERC20(token));
IERC20(token).approve(address(extender), type(uint256).max);
}
function addAToken(address aToken) external {
_onlyGuardian();
_aTokens.push(IERC20(aToken));
IERC20(aToken).approve(address(extender), type(uint256).max);
}
function setReferralCode(uint16 code) external {
_onlyGuardian();
referralCode = code;
}
function utilityTokens() public view override returns (IERC20[] memory) {
return _aTokens;
}
function _deallocateAll() internal {
// reads
uint256[] memory amounts = new uint256[](_tokens.length);
// interactions
for (uint256 i; i < _tokens.length; i++) {
amounts[i] = _aTokens[i].balanceOf(address(this));
}
deallocate(amounts);
}
}
pragma solidity ^0.8.10;
// interfaces
import "../interfaces/IAllocator.sol";
import "../interfaces/ITreasury.sol";
// types
import "../types/OlympusAccessControlledV2.sol";
// libraries
import "../libraries/SafeERC20.sol";
error BaseAllocator_AllocatorNotActivated();
error BaseAllocator_AllocatorNotOffline();
error BaseAllocator_Migrating();
error BaseAllocator_NotMigrating();
error BaseAllocator_OnlyExtender(address sender);
/**
* @title BaseAllocator
* @notice
* This abstract contract serves as a template for writing new Olympus Allocators.
* Many of the functionalities regarding handling of Treasury funds by the Guardian have
* been delegated to the `TreasuryExtender` contract, and thus an explanation for them can be found
* in `TreasuryExtender.sol`.
*
* The main purpose of this abstract contract and the `IAllocator` interface is to provide
* a unified framework for how an Allocator should behave. Below an explanation of how
* we expect an Allocator to behave in general, mentioning the most important points.
*
* Activation:
* - An Allocator is first deployed with all necessary arguments.
* Thereafter, each deposit is registered with the `TreasuryExtender`.
* This assigns a unique id for each deposit (set of allocations) in an Allocator.
* - Next, the Allocators allocation and loss limits are set via the extender function.
* - Finally, the Allocator is activated by calling `activate`.
*
* Runtime:
* The Allocator is in communication with the Extender, it must inform the Extender
* what the status of the tokens is which were allocated. We only care about noting down
* their status in the Extender. A quick summary of the important functions on this topic:
*
* - `update(uint256 id)` is the main function that deals with state reporting, where
* `_update(uint256 id)` is the internal function to implement, which should update Allocator
* internal state. `update(uint256 id)` then continues to report the Allocators state via `report`
* to the extender. `_update(uint256 id)` should handle _investment_ of funds present in Contract.
*
* - `deallocate` should handle allocated token withdrawal, preparing the tokens to be withdrawn
* by the Extender. It is not necessary to handle approvals for this token, because it is automatically
* approved in the constructor. For other token withdrawals, it is assumed that reward tokens will
* either be sold into underlying (allocated) or that they will simply rest in the Contract, being reward tokens.
* Please also check function documentation.
*
* - `rewardTokens` and `utilityTokens` should return the above mentioned simple reward tokens for the former case,
* while utility tokens should be those tokens which are continously reinvested or otherwise used by the contract
* in order to accrue more rewards. A reward token can also be a utility token, but then one must prepare them
* separately for withdrawal if they are to be returned to the treasury.
*
* Migration & Deactivation:
* - `prepareMigration()` together with the virtual `_prepareMigration()` sets the state of the Allocator into
* MIGRATING, disabling further token deposits, enabling only withdrawals, and preparing all funds for withdrawal.
*
* - `migrate` then executes the migration and also deactivates the Allocator.
*
* - `deactivate` sets `status` to OFFLINE, meaning it simply deactivates the Allocator. It can be passed
* a panic boolean, meaning it handles deactivation logic in `deactivate`. The Allocator panic deactivates if
* this state if the loss limit is reached via `update`. The Allocator can otherwise also simply be deactivated
* and funds transferred back to the Treasury.
*
* This was a short summary of the Allocator lifecycle.
*/
abstract contract BaseAllocator is OlympusAccessControlledV2, IAllocator {
using SafeERC20 for IERC20;
// Indices which represent the ids of the deposits in the `TreasuryExtender`
uint256[] internal _ids;
// The allocated (underlying) tokens of the Allocator
IERC20[] internal _tokens;
// From deposit id to the token's id
mapping(uint256 => uint256) public tokenIds;
// Allocator status: OFFLINE, ACTIVATED, MIGRATING
AllocatorStatus public status;
// The extender with which the Allocator communicates.
ITreasuryExtender public immutable extender;
constructor(AllocatorInitData memory data) OlympusAccessControlledV2(data.authority) {
_tokens = data.tokens;
extender = data.extender;
for (uint256 i; i < data.tokens.length; i++) {
data.tokens[i].approve(address(data.extender), type(uint256).max);
}
emit AllocatorDeployed(address(data.authority), address(data.extender));
}
/////// MODIFIERS
modifier onlyExtender {
_onlyExtender(msg.sender);
_;
}
modifier onlyActivated {
_onlyActivated(status);
_;
}
modifier onlyOffline {
_onlyOffline(status);
_;
}
modifier notMigrating {
_notMigrating(status);
_;
}
modifier isMigrating {
_isMigrating(status);
_;
}
/////// VIRTUAL FUNCTIONS WHICH NEED TO BE IMPLEMENTED
/////// SORTED BY EXPECTED COMPLEXITY AND DEPENDENCY
/**
* @notice
* Updates an Allocators state.
* @dev
* This function should be implemented by the developer of the Allocator.
* This function should fulfill the following purposes:
* - invest token specified by deposit id
* - handle rebalancing / harvesting for token as needed
* - calculate gain / loss for token and return those values
* - handle any other necessary runtime calculations, such as fees etc.
*
* In essence, this function should update the main runtime state of the Allocator
* so that everything is properly invested, harvested, accounted for.
* @param id the id of the deposit in the `TreasuryExtender`
*/
function _update(uint256 id) internal virtual returns (uint128 gain, uint128 loss);
/**
* @notice
* Deallocates tokens, prepares tokens for return to the Treasury.
* @dev
* This function should deallocate (withdraw) `amounts` of each token so that they may be withdrawn
* by the TreasuryExtender. Otherwise, this function may also prepare the withdraw if it is time-bound.
* @param amounts is the amount of each of token from `_tokens` to withdraw
*/
function deallocate(uint256[] memory amounts) public virtual;
/**
* @notice
* Handles deactivation logic for the Allocator.
*/
function _deactivate(bool panic) internal virtual;
/**
* @notice
* Handles migration preparatory logic.
* @dev
* Within this function, the developer should arrange the withdrawal of all assets for migration.
* A useful function, say, to be passed into this could be `deallocate` with all of the amounts,
* so with n places for n-1 utility tokens + 1 allocated token, maxed out.
*/
function _prepareMigration() internal virtual;
/**
* @notice
* Should estimate total amount of Allocated tokens
* @dev
* The difference between this and `treasury.getAllocatorAllocated`, is that the latter is a static
* value recorded during reporting, but no data is available on _new_ amounts after reporting.
* Thus, this should take into consideration the new amounts. This can be used for say aTokens.
* @param id the id of the deposit in `TreasuryExtender`
*/
function amountAllocated(uint256 id) public view virtual returns (uint256);
/**
* @notice
* Should return all reward token addresses
*/
function rewardTokens() public view virtual returns (IERC20[] memory);
/**
* @notice
* Should return all utility token addresses
*/
function utilityTokens() public view virtual returns (IERC20[] memory);
/**
* @notice
* Should return the Allocator name
*/
function name() external view virtual returns (string memory);
/////// IMPLEMENTATION OPTIONAL
/**
* @notice
* Should handle activation logic
* @dev
* If there is a need to handle any logic during activation, this is the function you should implement it into
*/
function _activate() internal virtual {}
/////// FUNCTIONS
/**
* @notice
* Updates an Allocators state and reports to `TreasuryExtender` if necessary.
* @dev
* Can only be called by the Guardian.
* Can only be called while the Allocator is activated.
*
* This function should update the Allocators internal state via `_update`, which should in turn
* return the `gain` and `loss` the Allocator has sustained in underlying allocated `token` from `_tokens`
* decided by the `id`.
* Please check the docs on `_update` to see what its function should be.
*
* `_lossLimitViolated` checks if the Allocators is above its loss limit and deactivates it in case
* of serious losses. The loss limit should be set to some value which is unnacceptable to be lost
* in the case of normal runtime and thus require a panic shutdown, whatever it is defined to be.
*
* Lastly, the Allocator reports its state to the Extender, which handles gain, loss, allocated logic.
* The documentation on this can be found in `TreasuryExtender.sol`.
* @param id the id of the deposit in `TreasuryExtender`
*/
function update(uint256 id) external override onlyGuardian onlyActivated {
// effects
// handle depositing, harvesting, compounding logic inside of _update()
// if gain is in allocated then gain > 0 otherwise gain == 0
// we only use so we know initia
// loss always in allocated
(uint128 gain, uint128 loss) = _update(id);
if (_lossLimitViolated(id, loss)) {
deactivate(true);
return;
}
// interactions
// there is no interactions happening inside of report
// so allocator has no state changes to make after it
if (gain + loss > 0) extender.report(id, gain, loss);
}
/**
* @notice
* Prepares the Allocator for token migration.
* @dev
* This function prepares the Allocator for token migration by calling the to-be-implemented
* `_prepareMigration`, which should logically withdraw ALL allocated (1) + utility AND reward tokens
* from the contract. The ALLOCATED token and THE UTILITY TOKEN is going to be migrated, while the REWARD
* tokens can be withdrawn by the Extender to the Treasury.
*/
function prepareMigration() external override onlyGuardian notMigrating {
// effects
_prepareMigration();
status = AllocatorStatus.MIGRATING;
}
/**
* @notice
* Migrates the allocated and all utility tokens to the next Allocator.
* @dev
* The allocated token and the utility tokens will be migrated by this function, while it is
* assumed that the reward tokens are either simply kept or already harvested into the underlying
* essentially being the edge case of this contract. This contract is also going to report to the
* Extender that a migration happened and as such it is important to follow the proper sequence of
* migrating.
*
* Steps to migrate:
* - FIRST call `_prepareMigration()` to prepare funds for migration.
* - THEN deploy the new Allocator and activate it according to the normal procedure.
* NOTE: This is to be done RIGHT BEFORE migration as to avoid allocating to the wrong allocator.
* - FINALLY call migrate. This is going to migrate the funds to the LAST allocator registered.
* - Check if everything went fine.
*
* End state should be that allocator amounts have been swapped for allocators, that gain + loss is netted out 0
* for original allocator, and that the new allocators gain has been set to the original allocators gain.
* We don't transfer the loss because we have the information how much was initially invested + gain,
* and the new allocator didn't cause any loss thus we don't really need to add to it.
*/
function migrate() external override onlyGuardian isMigrating {
// reads
IERC20[] memory utilityTokensArray = utilityTokens();
address newAllocator = extender.getAllocatorByID(extender.getTotalAllocatorCount() - 1);
uint256 idLength = _ids.length;
uint256 utilLength = utilityTokensArray.length;
// interactions
for (uint256 i; i < idLength; i++) {
IERC20 token = _tokens[i];
token.safeTransfer(newAllocator, token.balanceOf(address(this)));
extender.report(_ids[i], type(uint128).max, type(uint128).max);
}
for (uint256 i; i < utilLength; i++) {
IERC20 utilityToken = utilityTokensArray[i];
utilityToken.safeTransfer(newAllocator, utilityToken.balanceOf(address(this)));
}
// turn off Allocator
deactivate(false);
emit MigrationExecuted(newAllocator);
}
/**
* @notice
* Activates the Allocator.
* @dev
* Only the Guardian can call this.
*
* Add any logic you need during activation, say interactions with Extender or something else,
* in the virtual method `_activate`.
*/
function activate() external override onlyGuardian onlyOffline {
// effects
_activate();
status = AllocatorStatus.ACTIVATED;
emit AllocatorActivated();
}
/**
* @notice
* Adds a deposit ID to the Allocator.
* @dev
* Only the Extender calls this.
* @param id id to add to the allocator
*/
function addId(uint256 id) external override onlyExtender {
_ids.push(id);
tokenIds[id] = _ids.length - 1;
}
/**
* @notice
* Returns all deposit IDs registered with the Allocator.
* @return the deposit IDs registered
*/
function ids() external view override returns (uint256[] memory) {
return _ids;
}
/**
* @notice
* Returns all tokens registered with the Allocator.
* @return the tokens
*/
function tokens() external view override returns (IERC20[] memory) {
return _tokens;
}
/**
* @notice
* Deactivates the Allocator.
* @dev
* Only the Guardian can call this.
*
* Add any logic you need during deactivation, say interactions with Extender or something else,
* in the virtual method `_deactivate`. Be careful to specifically use the internal or public function
* depending on what you need.
* @param panic should panic logic be executed
*/
function deactivate(bool panic) public override onlyGuardian {
// effects
_deactivate(panic);
status = AllocatorStatus.OFFLINE;
emit AllocatorDeactivated(panic);
}
/**
* @notice
* Getter for Allocator version.
* @return Returns the Allocators version.
*/
function version() public pure override returns (string memory) {
return "v2.0.0";
}
/**
* @notice
* Internal check if the loss limit has been violated by the Allocator.
* @dev
* Called as part of `update`. The rule is that the already sustained loss + newly sustained
* has to be larger or equal to the limit to break the contract.
* @param id deposit id as in `TreasuryExtender`
* @param loss the amount of newly sustained loss
* @return true if the the loss limit has been broken
*/
function _lossLimitViolated(uint256 id, uint128 loss) internal returns (bool) {
// read
uint128 lastLoss = extender.getAllocatorPerformance(id).loss;
// events
if ((loss + lastLoss) >= extender.getAllocatorLimits(id).loss) {
emit LossLimitViolated(lastLoss, loss, amountAllocated(tokenIds[id]));
return true;
}
return false;
}
/**
* @notice
* Internal check to see if sender is extender.
*/
function _onlyExtender(address sender) internal view {
if (sender != address(extender)) revert BaseAllocator_OnlyExtender(sender);
}
/**
* @notice
* Internal check to see if allocator is activated.
*/
function _onlyActivated(AllocatorStatus inputStatus) internal pure {
if (inputStatus != AllocatorStatus.ACTIVATED) revert BaseAllocator_AllocatorNotActivated();
}
/**
* @notice
* Internal check to see if allocator is offline.
*/
function _onlyOffline(AllocatorStatus inputStatus) internal pure {
if (inputStatus != AllocatorStatus.OFFLINE) revert BaseAllocator_AllocatorNotOffline();
}
/**
* @notice
* Internal check to see if allocator is not migrating.
*/
function _notMigrating(AllocatorStatus inputStatus) internal pure {
if (inputStatus == AllocatorStatus.MIGRATING) revert BaseAllocator_Migrating();
}
/**
* @notice
* Internal check to see if allocator is migrating.
*/
function _isMigrating(AllocatorStatus inputStatus) internal pure {
if (inputStatus != AllocatorStatus.MIGRATING) revert BaseAllocator_NotMigrating();
}
}
pragma solidity >=0.8.0;
// interfaces
import "./IERC20.sol";
import "./ITreasuryExtender.sol";
import "./IOlympusAuthority.sol";
enum AllocatorStatus {
OFFLINE,
ACTIVATED,
MIGRATING
}
struct AllocatorInitData {
IOlympusAuthority authority;
ITreasuryExtender extender;
IERC20[] tokens;
}
/**
* @title Interface for the BaseAllocator
* @dev
* These are the standard functions that an Allocator should implement. A subset of these functions
* is implemented in the `BaseAllocator`. Similar to those implemented, if for some reason the developer
* decides to implement a dedicated base contract, or not at all and rather a dedicated Allocator contract
* without base, imitate the functionalities implemented in it.
*/
interface IAllocator {
/**
* @notice
* Emitted when the Allocator is deployed.
*/
event AllocatorDeployed(address authority, address extender);
/**
* @notice
* Emitted when the Allocator is activated.
*/
event AllocatorActivated();
/**
* @notice
* Emitted when the Allocator is deactivated.
*/
event AllocatorDeactivated(bool panic);
/**
* @notice
* Emitted when the Allocators loss limit is violated.
*/
event LossLimitViolated(uint128 lastLoss, uint128 dloss, uint256 estimatedTotalAllocated);
/**
* @notice
* Emitted when a Migration is executed.
* @dev
* After this also `AllocatorDeactivated` should follow.
*/
event MigrationExecuted(address allocator);
/**
* @notice
* Emitted when Ether is received by the contract.
* @dev
* Only the Guardian is able to send the ether.
*/
event EtherReceived(uint256 amount);
function update(uint256 id) external;
function deallocate(uint256[] memory amounts) external;
function prepareMigration() external;
function migrate() external;
function activate() external;
function deactivate(bool panic) external;
function addId(uint256 id) external;
function name() external view returns (string memory);
function ids() external view returns (uint256[] memory);
function tokenIds(uint256 id) external view returns (uint256);
function version() external view returns (string memory);
function status() external view returns (AllocatorStatus);
function tokens() external view returns (IERC20[] memory);
function utilityTokens() external view returns (IERC20[] memory);
function rewardTokens() external view returns (IERC20[] memory);
function amountAllocated(uint256 id) external view returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.7.5;
interface ITreasury {
function deposit(
uint256 _amount,
address _token,
uint256 _profit
) external returns (uint256);
function withdraw(uint256 _amount, address _token) external;
function tokenValue(address _token, uint256 _amount) external view returns (uint256 value_);
function mint(address _recipient, uint256 _amount) external;
function manage(address _token, uint256 _amount) external;
function incurDebt(uint256 amount_, address token_) external;
function repayDebtWithReserve(uint256 amount_, address token_) external;
function excessReserves() external view returns (uint256);
function baseSupply() external view returns (uint256);
}
pragma solidity ^0.8.10;
import "../interfaces/IOlympusAuthority.sol";
error UNAUTHORIZED();
error AUTHORITY_INITIALIZED();
/// @dev Reasoning for this contract = modifiers literaly copy code
/// instead of pointing towards the logic to execute. Over many
/// functions this bloats contract size unnecessarily.
/// imho modifiers are a meme.
abstract contract OlympusAccessControlledV2 {
/* ========== EVENTS ========== */
event AuthorityUpdated(IOlympusAuthority authority);
/* ========== STATE VARIABLES ========== */
IOlympusAuthority public authority;
/* ========== Constructor ========== */
constructor(IOlympusAuthority _authority) {
authority = _authority;
emit AuthorityUpdated(_authority);
}
/* ========== "MODIFIERS" ========== */
modifier onlyGovernor {
_onlyGovernor();
_;
}
modifier onlyGuardian {
_onlyGuardian();
_;
}
modifier onlyPolicy {
_onlyPolicy();
_;
}
modifier onlyVault {
_onlyVault();
_;
}
/* ========== GOV ONLY ========== */
function initializeAuthority(IOlympusAuthority _newAuthority) internal {
if (authority != IOlympusAuthority(address(0))) revert AUTHORITY_INITIALIZED();
authority = _newAuthority;
emit AuthorityUpdated(_newAuthority);
}
function setAuthority(IOlympusAuthority _newAuthority) external {
_onlyGovernor();
authority = _newAuthority;
emit AuthorityUpdated(_newAuthority);
}
/* ========== INTERNAL CHECKS ========== */
function _onlyGovernor() internal view {
if (msg.sender != authority.governor()) revert UNAUTHORIZED();
}
function _onlyGuardian() internal view {
if (msg.sender != authority.guardian()) revert UNAUTHORIZED();
}
function _onlyPolicy() internal view {
if (msg.sender != authority.policy()) revert UNAUTHORIZED();
}
function _onlyVault() internal view {
if (msg.sender != authority.vault()) revert UNAUTHORIZED();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.7.5;
import {IERC20} from "../interfaces/IERC20.sol";
/// @notice Safe IERC20 and ETH transfer library that safely handles missing return values.
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v3-periphery/blob/main/contracts/libraries/TransferHelper.sol)
/// Taken from Solmate
library SafeERC20 {
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, amount)
);
require(success && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FROM_FAILED");
}
function safeTransfer(
IERC20 token,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(IERC20.transfer.selector, to, amount)
);
require(success && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FAILED");
}
function safeApprove(
IERC20 token,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(
abi.encodeWithSelector(IERC20.approve.selector, to, amount)
);
require(success && (data.length == 0 || abi.decode(data, (bool))), "APPROVE_FAILED");
}
function safeTransferETH(address to, uint256 amount) internal {
(bool success, ) = to.call{value: amount}(new bytes(0));
require(success, "ETH_TRANSFER_FAILED");
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.7.5;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.8.10;
struct AllocatorPerformance {
uint128 gain;
uint128 loss;
}
struct AllocatorLimits {
uint128 allocated;
uint128 loss;
}
struct AllocatorHoldings {
uint256 allocated;
}
struct AllocatorData {
AllocatorHoldings holdings;
AllocatorLimits limits;
AllocatorPerformance performance;
}
/**
* @title Interface for the TreasuryExtender
*/
interface ITreasuryExtender {
/**
* @notice
* Emitted when a new Deposit is registered.
*/
event NewDepositRegistered(address allocator, address token, uint256 id);
/**
* @notice
* Emitted when an Allocator is funded
*/
event AllocatorFunded(uint256 id, uint256 amount, uint256 value);
/**
* @notice
* Emitted when allocated funds are withdrawn from an Allocator
*/
event AllocatorWithdrawal(uint256 id, uint256 amount, uint256 value);
/**
* @notice
* Emitted when rewards are withdrawn from an Allocator
*/
event AllocatorRewardsWithdrawal(address allocator, uint256 amount, uint256 value);
/**
* @notice
* Emitted when an Allocator reports a gain
*/
event AllocatorReportedGain(uint256 id, uint128 gain);
/**
* @notice
* Emitted when an Allocator reports a loss
*/
event AllocatorReportedLoss(uint256 id, uint128 loss);
/**
* @notice
* Emitted when an Allocator reports a migration
*/
event AllocatorReportedMigration(uint256 id);
/**
* @notice
* Emitted when an Allocator limits are modified
*/
event AllocatorLimitsChanged(uint256 id, uint128 allocationLimit, uint128 lossLimit);
function registerDeposit(address newAllocator) external;
function setAllocatorLimits(uint256 id, AllocatorLimits memory limits) external;
function report(
uint256 id,
uint128 gain,
uint128 loss
) external;
function requestFundsFromTreasury(uint256 id, uint256 amount) external;
function returnFundsToTreasury(uint256 id, uint256 amount) external;
function returnRewardsToTreasury(
uint256 id,
address token,
uint256 amount
) external;
function getTotalAllocatorCount() external view returns (uint256);
function getAllocatorByID(uint256 id) external view returns (address);
function getAllocatorAllocated(uint256 id) external view returns (uint256);
function getAllocatorLimits(uint256 id) external view returns (AllocatorLimits memory);
function getAllocatorPerformance(uint256 id) external view returns (AllocatorPerformance memory);
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity >=0.7.5;
interface IOlympusAuthority {
/* ========== EVENTS ========== */
event GovernorPushed(address indexed from, address indexed to, bool _effectiveImmediately);
event GuardianPushed(address indexed from, address indexed to, bool _effectiveImmediately);
event PolicyPushed(address indexed from, address indexed to, bool _effectiveImmediately);
event VaultPushed(address indexed from, address indexed to, bool _effectiveImmediately);
event GovernorPulled(address indexed from, address indexed to);
event GuardianPulled(address indexed from, address indexed to);
event PolicyPulled(address indexed from, address indexed to);
event VaultPulled(address indexed from, address indexed to);
/* ========== VIEW ========== */
function governor() external view returns (address);
function guardian() external view returns (address);
function policy() external view returns (address);
function vault() external view returns (address);
}
|
reads interactions we can do this because aToken is 1:1 with deposited
|
function _update(uint256 id) internal override returns (uint128 gain, uint128 loss) {
uint256 tokenId = tokenIds[id];
IERC20 token = _tokens[tokenId];
IERC20 aToken = _aTokens[tokenId];
uint256 balance = token.balanceOf(address(this));
if (balance > 0) {
token.approve(address(pool), balance);
pool.deposit(address(token), balance, address(this), referralCode);
}
uint256 aBalance = aToken.balanceOf(address(this));
uint256 last = extender.getAllocatorAllocated(id) + extender.getAllocatorPerformance(id).gain;
if (aBalance >= last) {
gain = uint128(aBalance - last);
loss = uint128(last - aBalance);
}
}
| 293,584
|
pragma solidity ^0.4.24;
contract ERC20 {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function allowance(address _owner, address _spender)
public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value)
public returns (bool);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract Ownable {
// Owner's address
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0));
emit OwnerChanged(owner, _newOwner);
owner = _newOwner;
}
event OwnerChanged(address indexed previousOwner,address indexed newOwner);
}
contract Pausable is Ownable {
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused, "Contract is paused.");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public 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();
}
event Pause();
event Unpause();
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
contract StandardToken is ERC20 {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
uint256 totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
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 Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 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;
}
}
contract PausableToken is StandardToken, 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);
}
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);
}
}
contract ElpisToken is PausableToken {
// token name
string public constant name = "Elpis AI Trading Token";
// token symbol
string public constant symbol = "ELP";
// token decimals
uint8 public constant decimals = 18;
// contract deployment block
uint256 public deploymentBlock;
constructor() public {
deploymentBlock = block.number;
totalSupply_ = 250000000 ether;
balances[msg.sender] = totalSupply_;
// special contributors
transfer(0x6467704b5CD5a5A380656886AE0284133825D378, 7000000000000000000000000);
transfer(0x7EF7F9104867454f0E3cd8B4aE99045a01f605c0, 1000000000000000000000000);
// transfer to existing contributors
transfer(0x1499493fd2fdb2c6d536569322fe37f5da24a5c9, 4672955120000000000000000);
transfer(0x22a5c82364faa085394b6e82d8d39643d0ad38e7, 2500000000000000000000000);
transfer(0xdc64259785a9dbae1b40fee4dfe2055af4fefd6b, 2000000000000000000000000);
transfer(0xbd14c21b0ed5fefee65d9c0609136fff8aafb1e8, 1500000000000000000000000);
transfer(0x4aca633f98559bb7e6025c629e1789537b9ee72f, 1000000000000000000000000);
transfer(0x4aeac209d18151f79ff5dc320619a554872b099d, 1000000000000000000000000);
transfer(0x9d3b6f11c9f17bf98e1bc8618a17bb1e9928e1c1, 1000000000000000000000000);
transfer(0xffdfb7ef8e05b02a6bc024c15ce5e89f0561a6f7, 646900270000000000000000);
transfer(0x6d91062c251eb5042a71312e704c297fb924409c, 379937110000000000000000);
transfer(0x5182531e3ebeb35af19e00fa5de03a12d46eba72, 379200360000000000000000);
transfer(0x8b751c5d881ab355a0b5109ea1a1a7e0a7c0ea36, 125000000000000000000000);
transfer(0x6a877aa35ef434186985d07270ba50685d1b7ada, 60000000000000000000000);
transfer(0x9ecedc01e9fde532a5f30f398cbc0261e88136a1, 28264000000000000000000);
transfer(0xd24400ae8bfebb18ca49be86258a3c749cf46853, 22641509433000000000000);
transfer(0x964fcf14cbbd03b89caab136050cc02e6949d5e7, 15094339622000000000000);
transfer(0xdc8ce4f0278968f48c059461abbc59c27c08b6f0, 10062893081000000000000);
transfer(0x2c06c71e718ca02435804b0ce313a1333cb06d02, 9811320754000000000000);
transfer(0x9cca8e43a9a37c3969bfd0d3e0cdf60e732c0cee, 8050314464000000000000);
transfer(0xa48f71410d01ec4ca59c36af3a2e2602c28d8fc2, 7547169811000000000000);
transfer(0xeb5e9a1469da277b056a4bc250af4489eda36621, 5031446540000000000000);
transfer(0xbb5c14e2a821c0bada4ae7217d23c919472f7f77, 3773584905000000000000);
transfer(0x46b5c439228015e2596c7b2da8e81a705990c6ac, 3773584905000000000000);
transfer(0x3e7a3fb0976556aaf12484de68350ac3b6ae4c40, 2515723270000000000000);
transfer(0xe14362f83a0625e57f1ca92d515c3c060d7d5659, 2264150943000000000000);
transfer(0x795df9a9699b399ffc512732d2c797c781c22bc7, 1509433962000000000000);
transfer(0xaca9fd46bfa5e903a75fb604f977792bd349a1af, 1396226415000000000000);
transfer(0xe2cdffd7b906cdd7ae74d8eb8553328a66d12b84, 1368887886000000000000);
transfer(0xee76d34d75ee0a72540abca5b26270b975f6adb6, 1320754716000000000000);
transfer(0xc44aa2d68d51fa5195b3d03af14a3706feeb29fc, 1320754716000000000000);
transfer(0xe694d8dd4b01bb12cb44568ebed792bd45a3f2cf, 1257861635000000000000);
transfer(0x9484e40deff4c6b4a475fe7625d3c70c71f54db7, 1207547169000000000000);
transfer(0x15ae5afd84c15f740a28a45fe166e161e3ed9251, 1132075471000000000000);
transfer(0x7fd9138acbcf9b1600eea70befe87729cc30968b, 1006289308000000000000);
transfer(0xfd3c389d724a230b4d086a77c83013ef6b4afdf1, 766037735000000000000);
transfer(0x774c988ec49df627093b6755c3baebb0d9a9d0b3, 758650475000000000000);
transfer(0x7a0702d58d6a4b6f06a9d275dc027555148e81c7, 754716981000000000000);
transfer(0x4b1b467a6a80af7ebc53051015e089b20588f1e7, 566037735000000000000);
transfer(0x0f6e5559ba758638d0931528967a54b9b5182b93, 566037735000000000000);
transfer(0xc1ec7ea396923d1a866a4f3798a87d1a92b9e37a, 556345720000000000000);
transfer(0x64bea49dd8d3a328a4aa4c739d776b0bfdda6128, 503144654000000000000);
transfer(0x472745526b7f72f7a9eb117e738f309d2abcc1a2, 503144654000000000000);
transfer(0xe3f68a6b6b39534a975eb9605dd71c8e36989e52, 490566037000000000000);
transfer(0x0caef953d12a24680c821d6e292a74634351d5a6, 452830188000000000000);
transfer(0x3f5d8a83b470b9d51b9c5a9ac1928e4e77a37842, 427942513000000000000);
transfer(0xfbb1b73c4f0bda4f67dca266ce6ef42f520fbb98, 422382641000000000000);
transfer(0x0b9fe4475e6a5ecbfb1fefc56c4c28fe97064dc1, 415094339000000000000);
transfer(0x83658d1d001092cabf33502cd1c66c91c16a18a6, 377358490000000000000);
transfer(0x236bea162cc2115b20309c632619ac876682becc, 94339622000000000000);
transfer(0xdfb2b0210081bd17bc30bd163c415ba8a0f3e316, 60314465000000000000);
transfer(0x92df16e27d3147cf05e190e633bf934e654eec86, 50314465000000000000);
transfer(0x6dd451c3f06a24da0b37d90e709f0e9f08987673, 40314465000000000000);
transfer(0x550c6de28d89d876ca5b45e3b87e5ae4374aa770, 1000000000000000000);
}
/**
* @dev Revertible fallback function
*/
function() external payable {
revert();
}
/**
* @dev This method can be used by the owner to extract mistakenly sent tokens
* or Ether sent to this contract.
* @param _token address The address of the token contract that you want to
* recover set to 0 in case you want to extract ether.
*/
function claimTokens(address _token) public onlyOwner {
if (_token == address(0)) {
owner.transfer(address(this).balance);
return;
}
ERC20 token = ERC20(_token);
uint balance = token.balanceOf(address(this));
token.transfer(owner, balance);
emit ClaimedTokens(_token, owner, balance);
}
/**
* @dev Owner can burn a specific amount of tokens from the target address.
* @param _target address The address which you want to burn tokens from
* @param _value uint256 The amount of token to be burned
*/
function burn(address _target, uint256 _value) public onlyOwner {
require(_value <= balances[_target]);
balances[_target] = balances[_target].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_target, _value);
emit Transfer(_target, address(0), _value);
}
/**
* Event for logging burning tokens
* @param burner whose tokens are burned
* @param value value of burned tokens
*/
event Burn(address indexed burner, uint256 value);
/**
* Event for logging when tokens are claimed
* @param token claimed token
* @param owner who owns the contract
* @param amount amount of the claimed token
*/
event ClaimedTokens(address indexed token, address indexed owner, uint256 amount);
}
|
This method can be used by the owner to extract mistakenly sent tokens or Ether sent to this contract. _token address The address of the token contract that you want to recover set to 0 in case you want to extract ether./
|
function claimTokens(address _token) public onlyOwner {
if (_token == address(0)) {
owner.transfer(address(this).balance);
return;
}
ERC20 token = ERC20(_token);
uint balance = token.balanceOf(address(this));
token.transfer(owner, balance);
emit ClaimedTokens(_token, owner, balance);
}
| 11,750,774
|
// SPDX-License-Identifier: GPL-3.0
// Author: Pagzi Tech Inc. | 2022
// DeadTownZeds | 2022
pragma solidity >=0.8.0 <0.9.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ERC721Enumerable.sol";
contract DeadTownZeds is ERC721Enumerable, Ownable {
string public baseURI;
uint256 public cost = 0.042 ether;
address pagzi = 0xF4617b57ad853f4Bc2Ce3f06C0D74958c240633c;
address macroverse = 0x02F91c73C0B3D50C79821f2F205Cd5268f0D7E57;
address steven = 0x275715709500a38a86fA48D280Ed88D201681601;
//date settings
uint256 public publicDate = 1644426000;
uint256 public endDate = 1644512400;
//mint passes/claims
mapping(address => uint256) public mintPasses;
address public proxyRegistryAddress;
constructor(
string memory _initBaseURI,
address _proxyRegistryAddress
) ERC721("DeadTownZeds", "ZEDS") {
setBaseURI(_initBaseURI);
proxyRegistryAddress = _proxyRegistryAddress;
initMintPasses();
}
// external
function mint(uint256 count) external payable{
require((publicDate <= block.timestamp) && (endDate >= block.timestamp),"DATE");
require(msg.value >= cost * count,"LOW");
uint256 totalSupply = _owners.length;
for(uint i; i < count; i++) {
_mint(_msgSender(), totalSupply + i + 1);
}
}
function claim() external{
uint256 totalSupply = _owners.length;
require((publicDate <= block.timestamp) && (endDate >= block.timestamp));
uint256 reserve = mintPasses[msg.sender];
require(reserve > 0, "Low reserve");
_mint(_msgSender(), totalSupply + 1);
mintPasses[msg.sender] = reserve - 1;
delete reserve;
}
//only owner
function gift(uint[] calldata quantity, address[] calldata recipient) external onlyOwner{
require(quantity.length == recipient.length, "Provide quantities and recipients" );
uint256 totalSupply = _owners.length;
for(uint i; i < recipient.length; ++i){
for(uint j; j < quantity[i]; ++j){
_mint(recipient[i], totalSupply + j + 1);
}
}
}
function setCost(uint256 _cost) external onlyOwner {
cost = _cost;
}
function setPublicDate(uint256 _publicDate) external onlyOwner {
publicDate = _publicDate;
}
function setEndDate(uint256 _endDate) external onlyOwner {
endDate = _endDate;
}
function setDates(uint256 _publicDate, uint256 _endDate) external onlyOwner {
publicDate = _publicDate;
endDate = _endDate;
}
function setMintPass(address _address,uint256 _quantity) external onlyOwner {
mintPasses[_address] = _quantity;
}
function setMintPasses(address[] calldata _addresses, uint256[] calldata _amounts) external onlyOwner {
for(uint256 i; i < _addresses.length; i++){
mintPasses[_addresses[i]] = _amounts[i];
}
}
//internal
function initMintPasses() internal {
mintPasses[0x275715709500a38a86fA48D280Ed88D201681601] = 10;
mintPasses[0xE2542857B06Ae5cdf7c4664f417e7a56312Da84E] = 5;
mintPasses[0x68fFfD5e532f8ED2727ACFEd097Ee1D065030b9c] = 5;
mintPasses[0x6fa1D14fB34C002c30419BbBFfD725e0A70B43Aa] = 5;
mintPasses[0xF4617b57ad853f4Bc2Ce3f06C0D74958c240633c] = 10;
mintPasses[0x8894802E3599EAA22e729a2DfFAab09c055eE84c] = 100;
mintPasses[0xF1ff23e094C3f83C39d1F5deb92A3e72Ca501cFc] = 5;
mintPasses[0x8500C52ca27f326D3a64B792aA215B1166503076] = 5;
//winners
mintPasses[0x2ad6623Ca66DC36610270fDd7327D904Be6305d7] = 1;
mintPasses[0x815CD9963ed67Fc9a11b18C3f7523885dF2869F7] = 1;
mintPasses[0x664D7462634fAC1815353A10f138750Ee11a91F6] = 1;
mintPasses[0x04aFa47203132436Cd4aAFA10547304B25F7006B] = 1;
mintPasses[0xa2116eB15F9DA56190d5Ac7f500101558b707968] = 1;
mintPasses[0x2a5a847DFeF231ED9a680d32C3Bb39582423E72F] = 1;
mintPasses[0x79c6174F46bD6a90f8d775887F90fBe7ba8A2ae3] = 1;
//twitter contest
mintPasses[0xB2E0f2fb1313FCD8870D683A812a35a483e4E843] = 1;
mintPasses[0xD1570F6B6B37Ad73494A1a7199A2922b1C32b914] = 1;
mintPasses[0x09129Fe9c5D4074B747814b8eCF6D1f43CC39AaC] = 1;
mintPasses[0xfd86Fb68cbC6759Ed4cDd806303e756c53A93887] = 1;
mintPasses[0xe16C26D3435DCCe67752fb5fEB0749F5e184d057] = 1;
mintPasses[0xC6c8347F41916F09B5fa0553100762Dd148e79f8] = 1;
mintPasses[0x67A50fF70d234D89B59Ed3DCBfAd65c4b96e1fa1] = 1;
mintPasses[0x9Bc67600E69d5d2Ab62006ca878D95A894492005] = 1;
mintPasses[0x71Fd9c2440D593AEb4d3C01322F3bcEE32E0712c] = 1;
mintPasses[0x32B4Cc9c6ef7Ea5A3694403704c12AFc46786C03] = 1;
}
function setBaseURI(string memory _baseURI) public onlyOwner {
baseURI = _baseURI;
}
function setProxyRegistryAddress(address _proxyRegistryAddress) external onlyOwner {
proxyRegistryAddress = _proxyRegistryAddress;
}
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
require(_exists(_tokenId), "Token does not exist.");
return string(abi.encodePacked(baseURI, Strings.toString(_tokenId)));
}
function burn(uint256 tokenId) public {
require(_isApprovedOrOwner(_msgSender(), tokenId), "Not approved to burn.");
_burn(tokenId);
}
function tokensOfOwner(address _owner) public view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) return new uint256[](0);
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i; i < tokenCount; i++) {
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds) public {
for (uint256 i = 0; i < _tokenIds.length; i++) {
transferFrom(_from, _to, _tokenIds[i]);
}
}
function batchSafeTransferFrom(address _from, address _to, uint256[] memory _tokenIds, bytes memory data_) public {
for (uint256 i = 0; i < _tokenIds.length; i++) {
safeTransferFrom(_from, _to, _tokenIds[i], data_);
}
}
function isOwnerOf(address account, uint256[] calldata _tokenIds) external view returns (bool){
for(uint256 i; i < _tokenIds.length; ++i ){
if(_owners[_tokenIds[i]] != account)
return false;
}
return true;
}
function isApprovedForAll(address _owner, address operator) public view override returns (bool) {
OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == operator) return true;
return super.isApprovedForAll(_owner, operator);
}
function _mint(address to, uint256 tokenId) internal virtual override {
_owners.push(to);
emit Transfer(address(0), to, tokenId);
}
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(pagzi).transfer((balance * 200) / 1000);
payable(macroverse).transfer((balance * 750) / 1000);
payable(steven).transfer((balance * 50) / 1000);
}
}
contract OwnableDelegateProxy { }
contract OpenSeaProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// SPDX-License-Identifier: GPL-3.0
// Author: Pagzi Tech Inc. | 2022
// DeadTownZeds | 2022
pragma solidity >=0.8.0 <0.9.0;
import "./ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account but rips out the core of the gas-wasting processing that comes from OpenZeppelin.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _owners.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < _owners.length, "ERC721Enumerable: global index out of bounds");
return index + 1;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256 tokenId) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
uint count;
for(uint i; i < _owners.length; i++){
if(owner == _owners[i]){
if(count == index) return i+1;
else count++;
}
}
revert("ERC721Enumerable: owner index out of bounds");
}
}
// SPDX-License-Identifier: GPL-3.0
// Author: Pagzi Tech Inc. | 2022
// DeadTownZeds | 2022
pragma solidity >=0.8.0 <0.9.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./Address.sol";
abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
string private _name;
string private _symbol;
// Mapping from token ID to owner address
address[] internal _owners;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner)
public
view
virtual
override
returns (uint)
{
require(owner != address(0), "ERC721: balance query for the zero address");
uint count;
for( uint i; i < _owners.length; ++i ){
if( owner == _owners[i] )
++count;
}
return count;
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
address owner = _owners[tokenId - 1];
require(
owner != address(0),
"ERC721: owner query for nonexistent token"
);
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(
_exists(tokenId),
"ERC721: approved query for nonexistent token"
);
return _tokenApprovals[tokenId - 1];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return tokenId < (_owners.length + 1) && _owners[tokenId - 1] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
virtual
returns (bool)
{
require(
_exists(tokenId),
"ERC721: operator query for nonexistent token"
);
address owner = ERC721.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_owners.push(to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_owners[tokenId - 1] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
ERC721.ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
);
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_owners[tokenId - 1] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId - 1] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert(
"ERC721: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
library Address {
function isContract(address account) internal view returns (bool) {
uint size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
|
Mints `tokenId` and transfers it to `to`. WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible Requirements: - `tokenId` must not exist. - `to` cannot be the zero address. Emits a {Transfer} event./
|
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_owners.push(to);
emit Transfer(address(0), to, tokenId);
}
| 5,711,320
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.